How to set upload_path in code igniter as url? - api

Helloo....
I have a problem uploading the image in the code igniter.
I use codeigniter as backend.
the code is like this:
public function upload_image_post()
{
if ($_FILES['image']) {
$name = $_FILES['image']['name'];
$this->load->library('upload', array(
'overwrite' => FALSE,
'upload_path' => FCPATH . 'assets/public/image/news',
'max_size' => '2097152',
'allowed_types' => 'png|jpg|gif|jpeg',
));
if (!$this->upload->do_upload('image')) {
return $this->response([
'status' => false,
'message' => 'fail 1'
], 500);
} else {
$upload = $this->upload->data();
return $this->response([
'status' => true,
'message' => 'success',
'data' => $upload,
], 200);
}
} else {
return $this->response([
'status' => false,
'message' => 'fail 2'
], 500);
}
}
When i using it in localhost, it is success to upload image. But when i deploy it, its failed, and show message 'fail 1'
how do I set up upload_path so it can point to any url I want??

If it's uploading on your localhost your logic is probably right.Please try the following see if this helps you.
First of all can you try adding a trailing slash to the path you provided like this assets/public/image/news/
Please check if your upload folder has write permissions set.
Note:
You can check if your directory is writable using this piece of code from this link.
https://forum.codeigniter.com/thread-74330.html
<?php if(is_writable(base_url('assets/public/image/news/'))){
echo 'writable';
}
else { echo (base_url('assets/public/image/news/'). ' ' ."is not writable");} ?>
Check if your htaccess is configured properly. May be any htaccess from the following git repository might work for you if the above points does not work.
https://github.com/tasmanwebsolutions/htaccess_for_codeigniter

Related

Lumen Google reCAPTCHA validation

I already seen some tuts and example about it and I have implemented it somehow.
Method in controller looks like this:
The logic used is just php and I would like to use more a lumen/laravel logic and not just simple vanilla php. Also I have tried and did not worked anhskohbo / no-captcha
public function create(Request $request)
{
try {
$this->validate($request, [
'reference' => 'required|string',
'first_name' => 'required|string|max:50',
'last_name' => 'required|string|max:50',
'birthdate' => 'required|before:today',
'gender' => 'required|string',
'email' => 'required|email|unique:candidates',
'g-recaptcha-response' => 'required',
]);
//Google recaptcha validation
if ($request->has('g-recaptcha-response')) {
$secretAPIkey = env("RECAPTCHA_KEY");
// reCAPTCHA response verification
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secretAPIkey.'&response='.$request->input('captcha-response'));
$response = json_decode($verifyResponse);
if ($response->success) {
//Form submission
//Saving data from request in candidates
$candidate = Candidate::create($request->except('cv_path'));
$response = array(
"status" => "alert-success",
"message" => "Your mail have been sent."
);
} else {
$response = array(
"status" => "alert-danger",
"message" => "Robot verification failed, please try again."
);
}
}
} catch(Exception $e) {
return response()->json($e->getMessage());
}
return response()->json(['id' => $candidate->id, $response]);
}
Okey. Google has an package for this:reCAPTCHA PHP client library
just: composer require google/recaptcha "^1.2"
and in your method inside controller:
$recaptcha = new \ReCaptcha\ReCaptcha(config('app.captcha.secret_key'));
$response = $recaptcha->verify($request->input('g-recaptcha-response'), $_SERVER['REMOTE_ADDR']);
if ($response->isSuccess()) {
//Your logic goes here
} else {
$errors = $response->getErrorCodes();
}
config('app.captcha.site_key') means that I got the key from from config/app.php and there from .env file.
If you have not config folder, you should create it, also create app.php file same as in laravel.

Magento2 module fields still visible in admin after module is disabled

I am experiencing an issue while trying to disable a Magento2 module causing custom values to still be visible in the customer edit page.
I would like to know what i have to do to completely get rid of a module and its data from a Magento2 system.
Magento version: 2.3.2
PHP version: 7.2.19
A custom(own) Magento2 module was installed by:
Copying code: app/code/VENDOR/MODULE
Running: magento module:enable VENDOR_MODULE
Running magento setup:upgrade
This module creates a couple of Customer EAV attributes that correctly show in the customer edit form.
I am able to populate/save/update values successfully.
I am disabling the module as such:
Running: magento module:disable VENDOR_MODULE
Running magento setup:upgrade
Completely removing the app/code/VENDOR/MODULE directory
When i navigate back to the customer edit page i can still see the attributes, visible and populated with previously entered data.
At this point i have tried the following:
Manually removing the entry in setup_module.
Including a Uninstall class.
A combination of magento cache:clean && magento setup:di:compile.
Classes attached:
InstallData.php
namespace VENDOR\MODULE\Setup;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Customer\Model\Customer;
use Magento\Customer\Setup\CustomerSetupFactory;
class InstallData implements InstallDataInterface {
private $customerSetupFactory;
/**
* Constructor
*
* #param \Magento\Customer\Setup\CustomerSetupFactory $customerSetupFactory
*/
public function __construct(CustomerSetupFactory $customerSetupFactory) {
$this->customerSetupFactory = $customerSetupFactory;
}
/**
* {#inheritdoc}
*/
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context) {
$this->installModule1($setup, $context);
$this->installModule2($setup, $context);
}
private function installModule1(ModuleDataSetupInterface $setup, ModuleContextInterface $context) {
$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
$customerSetup->addAttribute(\Magento\Customer\Model\Customer::ENTITY, 'module1', [
'type' => 'varchar',
'label' => 'Module1 label',
'input' => 'text',
'source' => '',
'required' => false,
'visible' => true,
'position' => 500,
'system' => false,
'backend' => ''
]);
$attribute = $customerSetup->getEavConfig()->getAttribute('customer', 'module1')
->addData(['used_in_forms' => [
'adminhtml_customer',
'adminhtml_checkout',
'customer_account_create',
'customer_account_edit'
]
]);
$attribute->save();
}
private function installModule1(ModuleDataSetupInterface $setup, ModuleContextInterface $context) {
$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
$customerSetup->addAttribute(\Magento\Customer\Model\Customer::ENTITY, 'module2', [
'type' => 'varchar',
'label' => 'Module2 label',
'input' => 'text',
'source' => '',
'required' => false,
'visible' => true,
'position' => 500,
'system' => false,
'backend' => ''
]);
$attribute = $customerSetup->getEavConfig()->getAttribute('customer', 'module2')
->addData(['used_in_forms' => [
'adminhtml_customer',
'adminhtml_checkout',
'customer_account_create',
'customer_account_edit'
]
]);
$attribute->save();
}
}
Uninstall.php
namespace VENDOR\MODULE\Setup;
use Magento\Framework\DB\Adapter\AdapterInterface;
use Magento\Framework\Db\Select;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\Setup\UninstallInterface;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\ModuleDataSetupInterface;
class Uninstall implements UninstallInterface {
private $_eavSetupFactory;
private $_mDSetup;
public function __construct(EavSetupFactory $eavSetupFactory, ModuleDataSetupInterface $mDSetup) {
$this->_eavSetupFactory = $eavSetupFactory;
$this->_mDSetup = $mDSetup;
}
public function uninstall(SchemaSetupInterface $setup, ModuleContextInterface $context) {
$installer = $setup;
$eavSetup = $this->_eavSetupFactory->create(['setup' => $this->_mDSetup]);
$eavSetup->removeAttribute(\Magento\Catalog\Model\Customer::ENTITY, 'module1');
$eavSetup->removeAttribute(\Magento\Catalog\Model\Customer::ENTITY, 'module2');
}
}
For Customer attributes you need to delete the specific attributes entry from table "eav_attribute" you can search by "attribute_code" and delete that row, you have to delete attributes from the database because there is no functionality in admin to delete an attribute
This is the method by which the custom attribute can be removed as I also tried manually to delete that module attribute and it took more than 1 day to find this solution.
public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
$eavSetup->removeAttribute(Customer::ENTITY, "<attribute name>");
}
You can remove multiple attribute too at same time by separating attribute name by commas.
After this just run -
bin/magento setup:upgrade && bin/magento setup:static-content:deploy -f

`Skip on empty` not working in Yii2 file upload

I have a provision to upload logo for companies in my application. Uploading and saving on creating profile works fine. But on update, logo goes empty if I am not uploading it again!
Here's my update form
<?php $form = ActiveForm::begin([
'options' => ['enctype'=>'multipart/form-data']
]); ?>
.....
<?= $form->field($model, 'logo')->fileInput() ?>
...
My Controller action
if ($model->load($_POST) ) {
$file = \yii\web\UploadedFile::getInstance($model, 'logo');
if($file){
$model->logo=$file; }
if($model->save()){
if($file)
$file->saveAs(\Yii::$app->basePath . '/web/images/'.$file);
}
return $this->redirect(['profile']);
} else {
return $this->renderPartial('update', [
'model' => $model,
]);
}
My Rules:
public function rules()
{
return [
[['logo'], 'image', 'extensions' => 'jpg,png', 'skipOnEmpty' => true],
[['name'], 'required'],
[['name', 'description'], 'string'],
];
}
Any ideas????
skipOnEmpty does not apply here because in the update action the $model->logo attribute will not be empty, it will be a string with the file name.$file is still an array with only keys, but not values if not uploaded again. So checked the $file->size instead of checking !empty($file). Fixed the issue by modifying the controller code as follows!
$model = $this->findModel($id);
$current_image = $model->featured_image;
if ($model->load(Yii::$app->request->post())) {
$image= UploadedFile::getInstance($model, 'featured_image');
if(!empty($image) && $image->size !== 0) {
//print_R($image);die;
$image->saveAs('uploads/' . $image->baseName . '.' .$image->extension);
$model->featured_image = 'uploads/'.$image->baseName.'.'.$image->extension;
}
else
$model->featured_image = $current_image;
$model->save();
return $this->redirect(['update', 'id' => $model->module_id]);
} else {
return $this->render('add', [
'model' => $model,
]);
}
'skipOnEmpty' => !$this->isNewRecord
For update it can be skipped.

link in cgridview is not displaying correctly

It appears that the links aren't in correct order and I can't figure out why. I have it in other grids, they seem to be fine.
This is what the link shows:
index.php?ajax=gridID&id=180&r=controller/action
when it's suppose to show:
index.php?r=controller/action&id=180
this is my value in gridview:
'value'=>function($data,$row){
if (intval($data->sid) ==$someID){
if($data->accept == "ACCEPTED")
return CHtml::Link("[X]", array("controller/action","id"=>$data->id),
array('confirm' => 'Are you sure?',
'class'=>'stat')
);
}
where grid is suppose to refresh on confirm:
<?php
Yii::app()->clientScript->registerScript('stat', "
$('#gridId a.stat').live('click', function() {
$.fn.yiiGridView.update('gridId', {
type: 'POST',
url: $(this).attr('href'),
success: function() {
$.fn.yiiGridView.update('gridId');
}
});
return false;
});"
);
?>
if you need generate url on "path" format (controller/action/id/180) and without script name you can set urlFormat property in UrlManager to "path" and set showScriptName property to false. Look this and this
in aplication config file:
'urlManager' => array(
'urlFormat' => 'path',
'showScriptName' => false,
)

YII LDAP connection for user authentication

I am new to yii frame work I am trying to create an ldap configuration for user authentication
The following steps which I taken to create but it throws eerro as below
include(Controller.php) [function.include]: failed to open stream: No such file or directory
C:\xampp\htdocs\yiif\framework\YiiBase.php(418)
steps:
1. I have included the following ldaprecord/
extension in C:\xampp\htdocs\seed2\protected\extensions\ldaprecord
2. I have included the following code in config/main.php
`'components'=>array(
'user'=>array(
// enable cookie-based authentication
'allowAutoLogin'=>true,
),
'ldap'=>array(
'class' => 'ext.ldaprecord.LdapComponent',
'server' => 'ldap://192.168.x.xxxx',
'port' => 389,
//'bind_rdn' => 'cn=suren diran,cn=Users,dc=xxxx,dc=demo,dc=com',
//'bind_pwd' => 'pass#123',
'base_dn' => 'dc=rsales,dc=demo,dc=com'),);
'params'=>array(
// this is used in contact page
'adminEmail'=>'sundarapandian#rsalesarm.com',
),
'ldap'=>array(
'class' => 'ext.ldaprecord.LdapComponent',
'server' => 'ldap://192.168.x.xxx',
'port' => 389,
//'bind_rdn' => 'cn=xxxx xxxx,cn=Users,dc=xxxx,dc=demo,dc=com',
//'bind_pwd' => 'pass#123',
'base_dn' => 'dc=xxxxx,dc=demo,dc=com'),
);`
included this line in the index.php
$config=dirname(__FILE__).'/protected/extensions/ldaprecord/CLdapRecord.php';
and I have changed the useridentity authentication function as
`
public function authenticate()
{
$username=$this->username;
$password=$this->password;
$dname= 'xxxxxxx';
$options['host']='ldap://192.168.x.xxx';
$options['port']=389;
$ldap_username = "CN=".$username.",CN=Users,DC=xxxx,DC=demo,DC=com";
$options = Yii::app()->params['ldap'];
print_r($options);
$connection = ldap_connect($options['host'], $options['port']);
//print_r($connection);
ldap_set_option($connection, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($connection, LDAP_OPT_REFERRALS, 0);
if($connection)
{
echo "success";
//exit;
try
{
//echo $connection.$ldap_username.$this->password;
//print_r(ldap_bind($connection,$dname."\\". $ldap_username, $password));
//exit;
#$bind = ldap_bind($connection,$dname."\\". $ldap_username, $password);
print_r(#$bind);
if(#$bind)
{
echo "successfully logedin";
}
}
catch (Exception $e){
echo $e->getMessage();
}
if(!$bind) $this->errorCode = self::ERROR_PASSWORD_INVALID;
else $this->errorCode = self::ERROR_NONE;
}
return !$this->errorCode;
};`
I am stucked here can any one help me hw to resolve this issue .please help me ,Thanks in advance..........
controller.php file was exists in the protected/components
even I check that it was included in the main .php
'import'=>array(
'application.models.*',
'application.components.*',
'ext.ldaprecord.*',
),
if I remove the following line the following error will shown
code:
$config=dirname(__FILE__).'/protected/extensions/ldaprecord/CLdapRecord.php'
error:
Property "CWebApplication.ldap" is not defined.
yes I am using that extension only which u given link above([http://www.yiiframework.com/extension/ldaprecord/]),if u have any other extension please can u provide that link and what the steps need to be taken for that to implement .........thanks in advance..........
HIIIIII
I done mistake in the params now I have changed that as below , and I removed the
$config=dirname(__FILE__).'/protected/extensions/ldaprecord/CLdapRecord.php';
it was not throwing any error .
I am including the my main.php full code below:
<?php
return array(
'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
'name'=>'xxxxxx',
// preloading 'log' component
'preload'=>array('log'),
// autoloading model and component classes
'import'=>array(
'application.models.*',
'application.components.*',
//ldap config added code
'ext.ldaprecord.*',
),
'defaultController' => 'site/login',
'modules'=>array(
// uncomment the following to enable the Gii tool
'gii'=>array(
'class'=>'system.gii.GiiModule',
'password'=>'pass',
// If removed, Gii defaults to localhost only. Edit carefully to taste.
'ipFilters'=>array('127.0.0.1','::1'),
),
),
// application components
'components'=>array(
'user'=>array(
// enable cookie-based authentication
'allowAutoLogin'=>true,
),
// uncomment the following to enable URLs in path-format
/*'urlManager'=>array(
'urlFormat'=>'path',
'rules'=>array(
'<controller:\w+>/<id:\d+>'=>'<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
'<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
),
),*/
/*'db'=>array(
'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db',
),*/
// uncomment the following to use a MySQL database
'db'=>array(
'connectionString' => 'mysql:host=localhost;dbname=xxxxx',
'emulatePrepare' => true,
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'tablePrefix' => '',
),
'errorHandler'=>array(
// use 'site/error' action to display errors
'errorAction'=>'site/error',
),
'log'=>array(
'class'=>'CLogRouter',
'routes'=>array(
array(
'class'=>'CFileLogRoute',
'levels'=>'error, warning',
),
// uncomment the following to show log messages on web pages
/*
array(
'class'=>'CWebLogRoute',
),
*/
),
),
'ldap'=>array(
'class' => 'ext.ldaprecord.LdapComponent',
'server' => 'ldap://192.168.x.xxx',
'port' => 389,
//'bind_rdn' => 'cn=suren diran,cn=Users,dc=xxxxxx,dc=demo,dc=com',
//'bind_pwd' => 'pass#123',
'base_dn' => 'dc=xxxxx,dc=demo,dc=com'),
),
// application-level parameters that can be accessed
// using Yii::app()->params['paramName']
'params'=>array(
// this is used in contact page
'adminEmail'=>'xxx#xxxx.com',
'ldap'=>array(
'class' => 'ext.ldaprecord.LdapComponent',
'server' => 'ldap://192.168.x.xxx',
'port' => 389,
//'bind_rdn' => 'cn=suren diran,cn=Users,dc=xxxxx,dc=demo,dc=com',
//'bind_pwd' => 'pass#123',
'base_dn' => 'dc=xxxx,dc=demo,dc=com'),
),
);
I am including my useridentity function below:
<?php
public function authenticate()
{
$options = Yii::app()->params['ldap'];
//print_r($options);
$connection = ldap_connect($options['host'], $options['port']);
ldap_set_option($connection, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($connection, LDAP_OPT_REFERRALS, 0);
if($connection)
{
// try
// {
//echo $options['domain']."\\".$this->username. $this->password;
//exit;
$ldap_username = "CN=".$this->username.",CN=xxxx,DC=xxxx,DC=demo,DC=com";
$ldap_password=$this->password;
echo $connection.$ldap_username.$ldap_password;
//$bind=ldap_bind($connection, $ldap_username, $ldap_password)
//exit;
//print_r(ldap_bind($connection,$ldap_username,$ldap_password));
$bind = #ldap_bind($connection,$ldap_username, $ldap_password);
print_r($bind);
//exit;
//#$bind = ldap_bind($connection,$ldap_username, $ldap_password);
// $abc=#$bind;
//print_r($abc);
//exit;
/*}
catch (Exception $e){
echo $e->getMessage();
}*/
if(!$bind) $this->errorCode = self::ERROR_PASSWORD_INVALID;
else $this->errorCode = self::ERROR_NONE;
}
return !$this->errorCode;
}
But in the above one the ldap_bind is not working can u help on this ........
Please help me I how to overcome this .........thanks alot.....
I've just been reading this:
$config=dirname(__FILE__).'/protected/extensions/ldaprecord/CLdapRecord.php'
Why have you done that? I assume you're using this extension: It doesn't advise anywhere in thedocumentation to do so. This is pretty much emptying your application's config - including the import-stanza which is ultimately letting the include of the Controller.php fail.
Since you asked for another extension I would point you to this blog post. It's not an extension but is fairly detailed on how to set it up and looks like it will accomplish the same end goal for you.