CakePHP: Error Saving Data - php

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);
}

Related

ImageIntervention & Laravel 9: file_put_contents ERROR Failed to open stream: No such file or directory

I'm using Laravel 9 and Image Intervetion to resize uploaded images:
public static function resize($file, $fileName)
{
$path = self::route();
foreach (self::size() as $key => $value) {
$resizePath = self::route() . "{$value[0]}x{$value[1]}_" . $fileName;
Image::make($file->getRealPath())
->resize($value[0], $value[1], function ($constraint) {
$constraint->aspectRatio();
})
->save(storage_path($resizePath));
$urlResizeImage[] = ["upf_path" => $resizePath, "upf_dimension" => "{$value[0]}x{$value[1]}"];
}
self::$urlResizeImage = $urlResizeImage;
}
But the line ->save(storage_path($resizePath)); returns this error:
Can't write image data to path
So in the Image Facade of Intervention, there's a #file_put_contents:
public function save($path = null, $quality = null, $format = null)
{
$path = is_null($path) ? $this->basePath() : $path;
// dd($path);
if (is_null($path)) {
throw new NotWritableException(
"Can't write to undefined path."
);
}
if ($format === null) {
$format = pathinfo($path, PATHINFO_EXTENSION);
}
$data = $this->encode($format, $quality);
$saved = #file_put_contents($path, $data);
if ($saved === false) {
throw new NotWritableException(
"Can't write image data to path ({$path})"
);
}
// set new file info
$this->setFileInfoFromPath($path);
return $this;
}
And I tried removing # from #file_put_contents to see what's going wrong here, but then I got this:
file_put_contents(C:\xampp\htdocs\project\storage\upload/1401/11/images/questions/107200x200_1671289517402.jpg): Failed to open stream: No such file or directory
So it basically says that it can not find the $path and when I uncomment dd($path), this is the output:
C:\xampp\htdocs\project\storage\upload/1401/11/images/questions/108200x200_1671289517402.jpg
So what's going wrong here?
How can I properly save the resized images into this directory?
Please I beg you to help me with this because it's been a week that I'm struggling with this error and got headache!
UPDATE #1:
Here is the route():
public static function route()
{
return "upload/" . jdate()->format('Y') . "/" . jdate()->format('m') . "/" . self::$typeFile . "/" . strtolower(self::$catType)."s" . "/" . self::$objId;
}
And I changed it to this:
public static function route()
{
return "upload".DIRECTORY_SEPARATOR.jdate()->format('Y').DIRECTORY_SEPARATOR.jdate()->format('m').DIRECTORY_SEPARATOR.self::$typeFile.DIRECTORY_SEPARATOR.strtolower(self::$catType)."s".DIRECTORY_SEPARATOR.self::$objId;
}
But still the same error occurs :(

image field not found

It doesnt see image if I upload. Image input name="projects[]".
I want move file to path but it doesnt see file in my PHP.
My code:
public function processProject()
{
if (!empty($_FILES['projects']['name']) and empty(Message::$msgs)) {
$upl = Upload::instance(3145728, "png,jpg");
$upl->process("projects", UPLOADS . '/' . $safe->category . '/', "MEM_");
}
if (!empty($_FILES['projects']['name'])) {
$data['cover'] = $upl->fileInfo['fname'];
}
}

Symfony 3 form data on edit page has null field for file upload field

I have a fully working file upload which works when a user creates a course. I use a service which contains the following code to upload the files and to update the form data with the image paths that need to be persisted.
public function handleCourseUploads($request, $formData, $originalCourse)
{
if($formData->getImage() !== null)
{
$courseImagePath = $this->upload($formData->getImage(), $formData->getFrameworkID() . '/course-image/');
$formData->setImage($courseImagePath);
}
foreach ($formData->getModules() as $module)
{
if($module->getImageLink() !== null)
{
$moduleImage = $this->upload($module->getImageLink(), $formData->getFrameworkID() . '/' . $module->getTitle() . '/');
$module->setImageLink($moduleImage);
}
foreach ($module->getDownload() as $download)
{
if($download->getDownloadLink() !== null)
{
$downloadItem = $this->upload($download->getDownloadLink(), $formData->getFrameworkID() . '/' . $module->getTitle() . '/downloads/');
$download->setDownloadLink($downloadItem);
}
}
}
return $formData;
}
When I use the same function when the edit page is submitted it says that null cannot be inserted. The formdata shows the "image link" as null which is obviously the problem. But how do I get around this?

POST file and key in vb.net

So I have a problem I want to upload a file to php but I also want to POST a key as well, you see my PHP code requires a key or "k" via POST to allow a file to be uploaded or the user will be redirected.
PHP:
<?php
error_reporting(0);
ini_set('display_errors', 0);
header("Content-Type: text/text");
$key = "Place Key Here";
$uploadhost = "http://example.com/i/index.php";
$redirect = "http://example.com/index.php";
if (isset($_POST['k'])) {
if ($_POST['k'] == $key) {
$target = getcwd() . "/" . basename($_FILES['d']['name']);
if (move_uploaded_file($_FILES['d']['tmp_name'], $target)) {
$md5 = md5_file(getcwd() . "/" . basename($_FILES['d']['name']));
rename(getcwd() . "/" . basename($_FILES['d']['name']), getcwd() . "/" . $md5 . "." . end(explode(".", $_FILES["d"]["name"])));
echo $uploadhost . $md5 . "." . end(explode(".", $_FILES["d"]["name"]));
} else {
echo "Sorry, there was a problem uploading your file.";
}
} else {
header('Location: '.$redirect);
}
} else {
header('Location: '.$redirect);
}
?>
I have looked around for a solution but all examples are for just uploading via
My.Computer.Network.UploadFile(Label1.Text, "http://example.com/i/index.php")
I have tried to POST the Key then Upload the file with the code above but no ball.
There is probably a far easier way to this that I maybe over thinking/looking.
Kind Regards,
Nimesh Patel

Why is this upload file code not working in CakePHP

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'));
}
}

Categories