after uploading prestashop from my localhost to the server , a problem showed up
when trying to upload product image i got this error "Server file size is different from local file size"
after searching in prestashop files i found that is uploader class is responsible for the upload process.
public function upload($file, $dest = null)
{
if ($this->validate($file))
{
if (isset($dest) && is_dir($dest))
$file_path = $dest;
else
$file_path = $this->getFilePath(isset($dest) ? $dest : $file['name']);
if ($file['tmp_name'] && is_uploaded_file($file['tmp_name'] ))
move_uploaded_file($file['tmp_name'] , $file_path);
else
// Non-multipart uploads (PUT method support)
file_put_contents($file_path, fopen('php://input', 'r'));
$file_size = $this->_getFileSize($file_path, true);
if ($file_size === $file['size'])
{
$file['save_path'] = $file_path;
}
else
{
$file['size'] = $file_size;
unlink($file_path);
$file['error'] = Tools::displayError('Server file size is different from local file size');
}
}
return $file;
}
when commenting if statement witch responsible of comparing file size and tring to upload an image i got this error
"An error occurred while copying image, the file does not exist anymore."
i changed img folder permissions to 777 still same problem ?
Its a permission issue. I resolved it by giving complete access (777) to cache and theme folders.
If that doesn't help then try giving complete access to all the files. Be sure to change back the permission to 755 for folders and 644 for files for security reasons.
please change " if ($file_size === $file['size']) " to " if ($file_size = $file['size']) "
This method worked for me.
Related
I am having some trouble uploading images to my blog, every time I try summiting the form it returns 'Failed to upload image :'. I can’t figure out the problem
if (!empty($_FILES['image']['name'])) {
$image_name = time() . '_' . $_FILES['image']['name'];
$destination = ROOT_PATH . "/assets/images/" . $image_name;
$result = move_uploaded_file($_FILES['image']['tmp_name'], $destination);
if ($result) {
$_POST['image'] = $image_name;
}else {
array_push($errors, 'Failed to upload image :');
}
}else {
array_push($errors, 'Image is required!');
}
If move_uploaded_file $_FILES['image']['tmp_name'] is not a valid upload file, then no action will occur, and move_uploaded_file() will return false.
If $_FILES['image']['tmp_name'] is a valid upload file, but cannot be moved for some reason, no action will occur, and move_uploaded_file() will return false. Additionally, a warning will be issued.
Make sure that the file is not empty.
Second: make sure the file name in English characters, numbers and (_-.) symbols, For more protection.
Third: Maybe the file is too big. Check the file size and also check php.ini for max_upload_size. Also check $_FILES["image"]["error"] to see what is the real error.
Thanks for the feedback
When using mac insure that the destination folder has read and writing permissions for other users.
I now there are lots of same questions here, but I didn't find my answer.
I want to upload an image using move_uploaded_file() function in PHP. Here is my logic?
//check if file uploaded
if (!isset($_POST) || !isset($_FILES)) {
return back();
}
// allowed extensions
$extensions = ['jpg', 'jpeg', 'gif', 'png'];
$fileName = pathinfo($_FILES['profile-image']['name'], PATHINFO_FILENAME);
// save file extension into a variable for later use
$parts = explode('.',$_FILES['profile-image']['name']);
$extension = strtolower(end($parts));
$fileSize = $_FILES['profile-image']['size'];
// check the extension
if (!in_array($extension, $extensions)) {
return back()->withErrors(['File Extension is not valid']);
}
// check if file size is less than 2MB
if ($fileSize >= 2e+6) {
return back()->withErrors(['File Size is too large.']);
}
//check if there is other errors
if ($_FILES['profile-image']['error']) {
return back()->withErrors(['You have anonymus error']);
}
// generate a unique file name
$profile_image = Hash::make($fileName) . '-' . time() . '.' . $extension;
// make a directory if there isn't one
if (!is_dir('public/img')) {
mkdir('public/img');
}
// if current user has an image then delete it
$user = App::get('database')->find('users', compact('id'));
if ($user->profile_image) {
unlink('public/img/' . $user->profile_image);
}
// move image into directory and final check for errors
if( ! move_uploaded_file($_FILES['profile-image']['tmp_name'], 'public/img/' . $profile_image) ) {
return back()->withErrors(['Your file doesn\'t uploaded']);
}
// Insert Uploaded Image into DB.
App::get('database')->update('users', compact('id'), compact('profile_image'));
return redirect('dashboard')->withMessage('Thank for uploading the file.');
I try this code, everything works properly but just sometimes. I don't know why sometimes my uploaded file doesn't move to the directory and sometimes it does. I tried for the same image, sometimes it uploaded and sometimes it failed. This is interesting, because when I upload an image and it fails, can't catch any errors at all.
Did you check max_file_uploads and post_max_size in your php.ini file ?
Maybe the file is bigger than the maximum size allowed.
Regards.
OK, I find the problem. When I hash the image name and save it to DB, sometimes it includes / inside file name, then when I use the file name in image src attribute, it considers the part before the / as another directory.
It might have trouble with,
Your Destination Directory have some writing permission issue.
Try this for manage file permission,
if (!is_writable($url)) {
try {
chmod($url, 0644);
} catch (Exception $e) {
die($e->getMessage() . ' | File : ' . $url . ' | Needs write permission [0644] to process !');
}
}
All the Best !
I am unable to move file into desired folder. I want to save image into uploaded folder. In mysql i have it in blob type.
this is my code
$target_Path = "uploaded/";
$target_Path = $target_Path.basename( $_FILES['image']['name'] );
move_uploaded_file( $_FILES['image']['tmp_name'], $target_Path );
mysqli_query($con,"UPDATE info SET photo='$target_Path' WHERE user_id='$id'");
In mysql it is showing that something has been saved but it not opening and the file is not moving into uploaded folder. i am doing this in my localhost. Please help.
Try wrapping your move_uploaded_file with an IF statement, and throw an exception if the file fails to transfer:
if (move_uploaded_file($_FILES['image']['tmp_name'], $target_Path ) === false) {
throw new Exception([text]);
}
Alternatively, to test whether the destination is writeable, you could try opening a file there and writing to it:
if (($fp = fopen($target_path, 'w')) === false) {
thrown new Exception("Failed to open file $target_path for writing");
}
fwrite($fp, file_get_contents($_FILES['image']['tmp_name']));
fclose($fp);
Chances are the problem is one of file permissions or ownership, which you'll need to fix at the command line with chmod or chown.
the htdocs folder in xampp has the 777 permissions, i can copy alter any file manually there but uploading a file into a subfolder gives an error. my code is:
<?php
define ('MAX_FILE_SIZE', 1024 * 50);
if (array_key_exists('submit', $_POST)) {
// define constant for upload folder
define('UPLOAD_DIR', '/opt/lampp/htdocs/properties/');
// replace any spaces in original filename with underscores
$file = str_replace(' ', '_', $_FILES['image']['name']);
// create an array of permitted MIME types
$permitted = array('image/gif', 'image/jpeg', 'image/pjpeg','image/png');
// upload if file is OK
if (in_array($_FILES['image']['type'], $permitted)
&& $_FILES['image']['size'] > 0
&& $_FILES['image']['size'] <= MAX_FILE_SIZE) {
switch($_FILES['image']['error']) {
case 0:
// check if a file of the same name has been uploaded
if (!file_exists(UPLOAD_DIR . $file)) {
// move the file to the upload folder and rename it
$success = move_uploaded_file($_FILES['image']['tmp_name'], UPLOAD_DIR $file);
} else {
$result = 'A file of the same name already exists.';
}
if ($success) {
$result = "$file uploaded successfully.";
} else {
$result = "Error uploading $file. Please try again.";
}
break;
case 3:
case 6:
case 7:
case 8:
$result = "Error uploading $file. Please try again.";
break;
case 4:
$result = "You didn't select a file to be uploaded.";
}
} else {
$result = "$file is either too big or not an image.";
}
}
?>
the error i get is:
Warning: move_uploaded_file(/opt/lampp/htdocs/properties/Cover.jpg): failed to open stream: Permission denied in /opt/lampp/htdocs/listprop.php on line 82
check is safe_mode is on in your php.ini
If only the xampp folder is writable that doesn't help, you need the sub-folders writable too.
Second, just asking
define('UPLOAD_DIR', '/opt/lampp/htdocs/properties/');
where lampp is shouldn't that be xampp? just asking (that can cause move problems too)
Hey i have a system were in uploading a file. I have a script I've found online and it seems to work well.
Here is the PHP code:
if((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0))
{
//Check if the file is JPEG image and it's size is less than 350Kb
$filename = basename($_FILES['uploaded_file']['name']);
$ext = substr($filename, strrpos($filename, '.') + 1);
if (($ext == "jpg") && ($_FILES["uploaded_file"]["type"] == "image/jpeg") && ($_FILES["uploaded_file"]["size"] < 350000))
{
//Determine the path to which we want to save this file
$newname = dirname(__FILE__).'upload/'.$filename;
//Check if the file with the same name is already exists on the server
if (!file_exists($newname))
{
//Attempt to move the uploaded file to it's new place
if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname)))
{
echo "It's done! The file has been saved as: ".$newname;
}
else
{
echo "Error: A problem occurred during file upload!";
}
}
else
{
echo "Error: File ".$_FILES["uploaded_file"]["name"]." already exists";
}
}
else
{
echo "Error: Only .jpg images under 350Kb are accepted for upload";
}
}
else
{
echo "Error: No file uploaded";
}
No this works fine if i want to upload a jpg file. But i want to be able to put the file into another directory. because at the moment the upload page is for admin users, they are on a subdomain called admin.mysite.com but the location i want the file to go to is in the members section which is mysite.com/members/video/
Now there are a few bits of code that im not 100% with like "dirname(FILE)" what does this do? I guessed it would get the current locations, but i've changed the whole line where so it looks like this:
$newname = '../mysite.com/members/video/'.$filename;
and
$newname = 'http://www.mysite.com/members/video/'.$filename;
But nothing. Anyone know how i can change this code so i can copy the file to a new directory?
Thanks for the help.
Change $newname to whatever location you want!
//Determine the path to which we want to save this file
$newname = dirname(__FILE__).'upload/'.$filename;
dirname(_ FILE _) returns the current directory of the file, in this case, file_upload.php
So, in this script, the $newname will save the uploaded file to /upload/name_of_new_file_uploaded.ext.
You should try to use realpath() instead dirname. Like this:
$newname = realpath("../../members/video/") . $filename;
depending on you file structure, add/remove the dots.
PS: Remember to change folder permissions, so the php can write on a folder.
For security, you should
Put the file in a location that is not accessible by the general web. /home/uploadedfiles/
Change the name of the file. Store the name of that file in a database and don't let the end users see that actual name.