Why is this upload file code not working in CakePHP - php

I have a problem with the upload of files in CakePHP 2.1. In fact, I always have the error:
Column not found: 1054 Unknown column 'Array' in 'field list'.
for the view:
<?php echo $this->Form->create('Ecole',array('enctype' => 'multipart/form-data')); ?>
<?php echo $this->Form->input('Ecole.logo_ecole', array('type'=>'file','class'=>'','label'=>'')); ?>
When I remove array('enctype' => 'multipart/form-data') I don't have the error but the upload don't work either.
For the controller:
if(!empty($this->data))
{
debug($this->data);
$ext = 'jpg';
// Save success
if($this->Ecole->save($this->data))
{
// Destination folder, new filename and destination path
$dest_folder = IMAGES . DS . 'galleries' . DS . $this->Ecole->id;
$new_filename = $this->Ecole->id. '.' .$ext;
$dest_path = $dest_folder . DS . $new_filename;
// Check if destination folder exists and create if it doesn't
if(!is_dir($dest_folder))
{
mkdir($dest_folder, 0755, true);
}
// We move the picture and rename it with his id
if(move_uploaded_file($this->data['Ecole']['logo_ecole']['tmp_name'], $dest_path))
{
// Show success flash message
$this->Session->setFlash(__('Picture successfully added !', true), 'default', array('class' => 'success'));
echo "<script> parent.location.reload(true); parent.jQuery.fancybox.close(); </script>";
}
// Move failed
else
{
// Delete picture
//$this->Ecole->delete($this->Ecole->id);
// Show error flash message
$this->Session->setFlash(__('Error occurred while adding picture !', true), 'default', array('class' => 'error'));
}
}
// Save failed
else
{
// Show error flash message
$this->Session->setFlash(__('Error occurred while adding picture !', true), 'default', array('class' => 'error'));
}
}
Can anyone explain what I'm doing wrong and how to do it right?

to do multipart/form-data, you have to specify it this way with the helper
<?php echo $this->Form->create('Ecole', array('type' => 'file')); ?>
The type can be ‘post’, ‘get’, ‘file’, ‘put’ or ‘delete’. Please see the sections Options for create here in the FormHelper documentation !

It's probably because you're trying to save the array cake generates when uploading a file ($this->data['Ecole']['logo_ecole'] is an array). Are you meaning to save only the filename to the database?

i have modify your code please take a look
and please not remove array('enctype' => 'multipart/form-data') this line in form
<?php
if(!empty($this->data))
{
debug($this->data);
$ext = 'jpg';
// Destination folder, new filename and destination path
$dest_folder = IMAGES . DS . 'galleries' . DS . $this->Ecole->id;
$new_filename = $this->Ecole->id. '.' .$ext;
$dest_path = $dest_folder . DS . $new_filename;
// Check if destination folder exists and create if it doesn't
if(!is_dir($dest_folder))
{
mkdir($dest_folder, 0755, true);
}
$image='';
// We move the picture and rename it with his id
if(move_uploaded_file($this->data['Ecole']['logo_ecole']['tmp_name'], $dest_path))
{
$image = basename($this->data['Ecole']['logo_ecole']['name'])
// Show success flash message
$this->Session->setFlash(__('Picture successfully added !', true), 'default', array('class' => 'success'));
echo "<script> parent.location.reload(true); parent.jQuery.fancybox.close(); </script>";
}else
{
// Delete picture
//$this->Ecole->delete($this->Ecole->id);
// Show error flash message
$this->Session->setFlash(__('Error occurred while adding picture !', true), 'default', array('class' => 'error'));
}
$this->data['Ecole']['logo_ecole'] = $image;
// Save success
if(!$this->Ecole->save($this->data))
{
// Show error flash message
$this->Session->setFlash(__('Error occurred while adding picture !', true), 'default', array('class' => 'error'));
}
}

Related

how to make a path with read write access in zend form captcha

I have added captcha in Zend form. In this captcha image is generated automatically and saved in captcha folder.
When accessed in server (AWS), in html page that captcha image is not loading because, the path is not readable and writable.
Here is the code I have used for creating the zend form with captcha:
$captcha = new Zend_Form_Element_Captcha('captcha', array(
'captcha' => array(
'captcha' => 'Image',
'wordLen' => 5,
'timeout' => 300,
'expiration' => 300,
'font' => './fonts/calibri_bold.ttf',
'imgDir' => './captcha/',
'imgUrl' => '/captcha/'
)
));
$captcha->removeDecorator('ViewHelper');
How to make the imgDir path with read & write access?
Any help is greatly appreciated. Thanks in advance.
I got this issue fixed by finding the captcha image path in php and provided access to read the image file. Below is the code:
public function giveCaptchaFolderAccess() {
$Path = realpath("../public/captcha");
$dp = opendir($Path);
while ($File = readdir($dp)) {
if ($File != "." AND $File != "..") {
if (is_dir($File)) {
chmod($File, 0744);
chmod_r($Path . "/" . $File);
} else {
chmod($Path . "/" . $File, 0744);
}
}
} closedir($dp);
}

Laravel: Undefined value on image upload

First Laravel Project. I building a feature where I can upload an image. Everything what I did is based on this PDF (page 98-101)
My blade.php
<?php echo Form::open(array('url' =>'/product/imgedit','files'=>'true'));
echo 'Adj meg egy új képet';
echo Form::file('image');
echo Form::submit('Upload File');
echo Form::close();?>
My router
Route::get('product/{id}/imgedit', 'InventoryController#imgreq');
Route::post('product/imgedit', 'InventoryController#imgupl');
My Controller:
public function imgreq($id)
{
$product = DB::select('select * FROM inventory WHERE barcode = ?', [$id]);;
return view('productimgupl', ['product' => $product]);
}
public function imgupl()
{
$file = $request->file('image');
//Display File Name
echo 'File Name: ' . $file->getClientOriginalName();
echo '<br>';
//Display File Extension
echo 'File Extension: ' . $file->getClientOriginalExtension();
echo '<br>';
//Display File Real Path
echo 'File Real Path: ' . $file->getRealPath();
echo '<br>';
//Display File Size
echo 'File Size: ' . $file->getSize();
echo '<br>';
//Display File Mime Type
echo 'File Mime Type: ' . $file->getMimeType();
//Move Uploaded File
$destinationPath = '/media/productimg/';
$file->move($destinationPath, $file->getClientOriginalName());
}
Error message:
ErrorException in InventoryController.php line 28: Undefined variable:
request
What I did wrong?
You need to bring in the Request object in your method's argument. Like so:
public function imgupl(Request $request) {
// code...
}
Then you may use $request in the method.
By default Laravel includes this class when you use php artisan make:controller by inserting it at the top of your Controller with this line: use Illuminate\Http\Request;. All you are doing is casting the Request object to a variable named $request for use in that method.
Hope this helps!

Uploading multiple image with different input file in Codeigniter

So I have four input files in my forms and I send it on my global $_FILES with the following indices: front,rear,right and left.
I want to upload these using codeigniter image class library. This is my code:
public function upload_to_temp($id, $folder, $tags){
$path = realpath(APPPATH . '../public/resources/temps/' . $folder );
//makes a directory
mkdir($path . '/' . $id, 0700);
//navigate to the newly created path
$path = realpath(APPPATH . '../public/resources/temps/' . $folder . '/' . $id);
if(isset($tags)){
//use these tags to check the files present on submission
foreach($tags as $tag){
if(array_key_exists($tag,$_FILES)){
if(!empty($_FILES) && $_FILES[$tag]["name"] != "" && isset($_FILES[$tag]["name"])){
$config = array (
'source_image' => $_FILES[$tag]["name"],
'image_library' => 'gd',
'upload_path' => $path,
'file_name' => $id . '_' . $tag . '.jpg',
'allowed_types' => 'png|jpg|jpeg',
'overwrite' => TRUE,
'max_size' => '2000',
);
$this->_CI->upload->initialize($config);
if(!$this->_CI->upload->do_upload()){
echo 'Error creating image. ';
echo $this->_CI->upload->display_errors();
}else{
echo 'Success saving to temp folder';
}
//kapag failed
if(!$this->_CI->upload->do_upload()){
echo 'Error creating image.';
echo $this->_CI->upload->display_errors();
}else{
//now, the $path will become our resource path for copying and creating thumbnails.
$resouce_path = $config['upload_path'] . '/' . $config['file_name'];
$this->img_create_thumb($resouce_path, $folder);
}
}else{
//Hindi na dapat marating to!
echo $tag . ' not present ';
}
}else{
//use default pictures
echo $tag . ' not present ';
}
}
}
}
However it gives me the following error:
Error creating image. You did not select a file to upload.Error
creating image.You did not select a file to upload.You did
not select a file to upload.Error creating image. You did not
select a file to upload.Error creating image.You did not select
a file to upload.You did not select a file to upload.right
not present left not present
I think I did not correctly specified which resource on the $_FILES should be uploaded.
Your response would be greatly appreciated.
Thanks
I solved it by supplying the indices in codeigniter's do_upload()
$this->_CI->upload->do_upload($tag);

Edit a register with a form upload field

I have an app that I create an register with an file upload. Ok, the file upload and the created register it's fine.
I want that when the user put a file, it will do the update. If not, do not update of the field containing the file path.
But, I need to edit this register. When edditing, my file upload show an error:
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Array' in 'field list'
SQL Query: UPDATE societario.attorneys SET nome = 'teste editar', empresa = '', filial = '', unidade = 'Energia', alcada = 'Até 10.000', validade = '123123111', arquivo = Array WHERE societario.attorneys.id = '83'
My create controller:
if($this->request->is('post')){
$targetFolder = 'societario/app/webroot/uploads/'; // Relative to the root
$tempFile = $this->request->data['Attorney']['arquivo']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
$targetFile = rtrim($targetPath,'/') . '/' . $this->request->data['Attorney']['arquivo']['name'];;
move_uploaded_file($tempFile,$targetFile);
$this->Attorney->saveAll($this->request->data, array('fieldList' => array('nome','empresa','filial','unidade','validade', 'alcada', 'status')));
$this->Attorney->updateAll(
array('arquivo' => "'".$this->request->data['Attorney']['arquivo']['name'] ."'",),
array('id' => $this->Attorney->id));
My edit controller:
EDIT: MODIFIED THE EDIT CONTROLLER. THE SOLUTION IS IN AN ANSWER THAT FOLLOWS.
$this->Attorney->id = $id;
$this->set('poderes',$this->Attorney->Power->find('list', array('fields' => 'resumo')));
if ($this->request->is('get')) {
$this->request->data = $this->Attorney->read();
} else {
if ($this->Attorney->save($this->request->data)) {
$this->Session->setFlash('Usuário editado com sucesso!', 'default', array('class' => 'flash_sucess'));
$this->redirect(array('action' => 'usuarios'));
}
}
arquivo = Array
It thinks Array is a field... So if you literally want "Array" saved then put it in single quotes. Otherwise I think you forgot the $.
EDIT - Thought I'd mention that this is in your UPDATE statement.
I found the solution!! thanks
My edit controller:
$this->Attorney->id = $id;
$this->set('poderes',$this->Attorney->Power->find('list', array('fields' => 'resumo')));
if ($this->request->is('get')) {
$this->request->data = $this->Attorney->read();
} else {
if ($this->Attorney->save($this->request->data, array('fieldList' => array('nome','empresa','filial','unidade','validade', 'alcada', 'status')))) {
if(!empty($this->request->data['Attorney']['arquivo']['name'])) {
$targetFolder = 'societario/app/webroot/uploads/'; // Relative to the root
$tempFile = $this->request->data['Attorney']['arquivo']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
$targetFile = rtrim($targetPath,'/') . '/' . $this->request->data['Attorney']['arquivo']['name'];;
move_uploaded_file($tempFile,$targetFile);
$this->Attorney->updateAll(
array('arquivo' => "'".$this->request->data['Attorney']['arquivo']['name'] ."'",),
array('id' => $this->Attorney->id));
$this->Session->setFlash('procuração editada com sucesso!', 'default', array('class' => 'flash_sucess'));
$this->redirect(array('action' => 'usuarios'));
}
$this->Session->setFlash('Usuário editado com sucesso!', 'default', array('class' => 'flash_sucess'));
$this->redirect(array('action' => 'usuarios'));
}
}

CakePHP: Error Saving Data

So I'm having troubles saving my data in CakePHP.
If I upload an image (meaning ['PictureForm']['file']['name'] exists), everything works fine and the data is saved. However, if ['PictureForm']['file']['name'] is null, and ['PictureForm']['url'] exists, then the image is correctly saved on disk, but then $this->PictureForm->save($this->data) fails.
Anyone see anything blatantly wrong with my code?
if (isset($this->data['PictureForm'])) {
///////////////////////////////////////////////////////DEV
if(!$this->data['PictureForm']['file']['name']) {
if (!$this->data['PictureForm']['url']) {
$this->Session->setFlash('Error: no image URL or file given!');
$this->redirect(array('action' => '/'));
} else {
$fileExtension = getExtension($this->data['PictureForm']['url']);
$this->request->data['PictureForm']['filename'] = randFilename() . "." . $fileExtension;
file_put_contents('files/picture/' . $this->data['PictureForm']['filename'], file_get_contents($this->data['PictureForm']['url']));
}
} else { //file was uploaded
$fileExtension = getExtension($this->data['PictureForm']['file']['name']);
if (!$fileExtension) {
$this->Session->setFlash('Error: no file extension!');
$this->redirect(array('action' => '/'));
}
$this->request->data['PictureForm']['filename'] = randFilename() . "." . $fileExtension;
move_uploaded_file($this->data['PictureForm']['file']['tmp_name'], "files/picture/" . $this->data['PictureForm']['filename']);
}
$this->request->data = Sanitize::clean($this->request->data, array('encode' => false));
if ($this->PictureForm->save($this->data)) {
resizeUpload($this->data['PictureForm']['filename']);
$this->Session->setFlash('Picture saved');
$this->redirect(array('action' => 'p/' . $this->data['PictureForm']['filename']));
} else {
$this->Session->setFlash('Error: could not save to db' . $this->data['PictureForm']['filename']);
$this->redirect(array('action' => '/'));
}
}
If the save fails, in the else block, instead of redirecting try to view the validation errors:
if ($this->PictureForm->save($this->data)) {
// code
} else{
debug($this->PictureForm->validationErrors);
}

Categories