I am trying to create a PHP file to upload images to my website. I have the following code, but it is not working. Can anyone help me fix it so I do not get any errors? Is there any better way to do such a thing? I know it is old fashioned.
$uploaddir = "uploads/images";
$allowed_ext = "jpg, JPG, png, gif";
$max_size = "500000";
$max_height = "4000";
$max_width = "4000";
$extension = pathinfo ($_FILES['file']['name']);
$extension = $extension[extension];
$allowed_paths = explode(", ", $allowed_ext);
for ($i = 0; $i <= count($allowed_paths); $i++){
if ($allowed_paths[$i] == "$extension"){
$ok = "1";
}
}
if ($ok == "1"){
if($_FILES['file']['size'] > $max_size){
print "Your file is too big!";
exit;
}
}
if($max_width && $max_height){
list($width, $height, $type, $w) = getimagesize($_FILES['file']['name']);
if ($width > $max_width || $height > $max_height){
print "Your file width/height are too big!";
exit;
}
}
if (is_uploaded_file($_FILES['file']['tmp_name'])){
move_uploaded_file($_FILES['file']['tmp_name'], $uploaddir.'/'.$_FILES['file']['name']);
print "Your file was uploaded successfully :)";
}
else
print "Wrong extensin";
?>
When I run the script I get the following error:
Warning: getimagesize(1 (8).jpg) [function.getimagesize]: failed to open stream: No such file or directory in D:\Hosting\8923686\html\uploadedimages\upload.php on line 25
Warning: move_uploaded_file(uploads/images/1 (8).jpg) [function.move-uploaded-file]: failed to open stream: Permission denied in D:\Hosting\8923686\html\uploadedimages\upload.php on line 33
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move 'D:\Temp\php\phpE5F5.tmp' to 'uploads/images/1 (8).jpg' in D:\Hosting\8923686\html\uploadedimages\upload.php on line 33
or
invalid file
Can any one please tell me where is my problem?
As for the first error, change getimagesize($_FILES['file']['name']) to getimagesize($_FILES['file']['tmp_name']).
As for the other two errors, make sure your script has permissions to write files to the folder where you're trying to move the uploaded file to.
Edit: Also try to use a full absolute path in $uploaddir instead of just uploads/images. Since you're using a relative path from a script that isn't located in the document root, it's possible that PHP is looking in the wrong directory.
getimagesize($_FILES['file']['name'] in line 25 is the first culprit: you meant getimagesize($_FILES['file']['tmp_name']
For the othe errors you need to check permissions of uploads/images - they are obviously off limits for the webserver user.
Related
I have a form that lets the user to upload files to the server, but I did not know how to write the correct path for that folder in the server which I want the files to be store in, also how to get the path for specific file to download later.
The path in the server:
/public_html/upload_files
The error I am getting:
Warning: move_uploaded_file(upload_files/project_guidelines.pdf):
failed to open stream: No such file or directory in
D:\sites\dwts.com\public_html\website\creat.php on line 50 Warning:
move_uploaded_file(): Unable to move 'C:\Windows\Temp\php14AC.tmp' to
'upload_files/project_guidelines.pdf' in
D:\sites\dwts.com\public_html\website\creat.php on line 50 Error
uploading file
Code:
$len = count($_FILES['Attachment']['name']);
for($i = 0; $i < $len; $i++) {
$uploadDir = 'upload_files/';
$fileName = $_FILES['Attachment']['name'][$i];
$tmpName = $_FILES['Attachment']['tmp_name'][$i];
$fileSize = $_FILES['Attachment']['size'][$i];
$fileType = $_FILES['Attachment']['type'][$i];
$filePath = $uploadDir . basename($_FILES['Attachment']['name'][$i]);
$result = move_uploaded_file($tmpName,$filePath);
if (!$result) {
echo "Error uploading file";
exit;
}
$uploadDir = 'upload_files/';
Where is the drive? Its Windows, so it needs a drive:
$uploadDir = 'c:/upload_files/';
You can't give a partial location to the second argument of move_uploaded_file...it needs a full path.
I am setting up a file upload service on my website. Here is what I got so far,
upload.php
<form action="uploader.php" method="post" enctype="multipart/form-data">
<input type="file" name="myFile">
<br>
<input type="submit" value="Upload">
</form>
uploader.php
<?php
define("UPLOAD_DIR", "/uploads");
if (!empty($_FILES["myFile"])) {
$myFile = $_FILES["myFile"];
if ($myFile["error"] !== UPLOAD_ERR_OK) {
echo "<p>An error occurred.</p>";
exit;
}
// ensure a safe filename
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
// verify the file is a GIF, JPEG, or PNG
$fileType = exif_imagetype($_FILES["myFile"]["tmp_name"]);
$allowed = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG);
if (!in_array($fileType, $allowed)) {
// file type is not permitted
echo "<p>Unable to save file.</p>";
exit;
}
// don't overwrite an existing file
$i = 0;
$parts = pathinfo($name);
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
// preserve file from temporary directory
$success = move_uploaded_file($myFile["tmp_name"],
UPLOAD_DIR . $name);
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
}
// set proper permissions on the new file
chmod(UPLOAD_DIR . $name, 0644);
}
There is a folder in my directory called uploads, I want my files to upload to there.
However when running it using XAMMP, I try and upload a image called example.png and it comes up with the following errors.
Warning: move_uploaded_file(/uploadsexample.png): failed to open stream: Permission denied in C:\xampp\htdocs\assembly\uploader.php on line 37
Warning: move_uploaded_file(): Unable to move 'C:\xampp\tmp\phpBAE5.tmp' to '/uploadsexample.png' in C:\xampp\htdocs\assembly\uploader.php on line 37
Unable to save file.
If you could help me solve my issue I would be very grateful! thanks.
Add a trailing slash / for
define("UPLOAD_DIR", "/uploads");
^ missing slash
change it to:
define("UPLOAD_DIR", "/uploads/");
Notice the error you got => to '/uploadsexample.png'
and in
Warning: move_uploaded_file(/uploadsexample.png):
^
it's missing a slash after uploads, between uploads and the filename.
Plus, just to be on the safe side, if that still throws you an error that it won't let you upload with another "permission denied" message, make sure that the folder is indeed writeable with proper write permissions set for it.
N.B.:
You may need to modify /uploads/ to uploads/ or ../uploads/ depending on the script's execution location.
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.
I had asked this question and found out that the PHP configuration was limiting my uploads to 2MB, so I fixed it to 3MB. However, I have another problem now: I am also checking for image dimension and it is failing if the image appears to be over 3MB, throwing the below error. So how could I stop the error and check the size by myself instead of the PHP config?
Warning: getimagesize(): Filename cannot be empty
Here is the code:
$size = $_FILES['image']['size'];
list($width, $height) = getimagesize($_FILES['image']['tmp_name']);
$minh = 400;
$minw = 600;
$one_MB = 1024*1024; //1MB
if($size > ($one_MB*3))// this is not checking the size at all, the last echo is what I get if I try to upload over 3mb.
{
echo"File exceeds 3MB";
}
elseif ($width < $minw ) {
echo "Image width shouldn't be less than 600px";
}
elseif ($height < $minh){
echo "Image height shouldn't be less than 400px";
}
else{
if (move_uploaded_file($_FILES['image']['tmp_name'], $new_location)){
//do something
}
else{
echo "Image is too big, try uploading below 3MB";
}
}
Looks like the upload went wrong at some point. Try adding some error handling before getimagesize():
if (!file_exists($_FILES['image']['tmp_name'])) {
echo "File upload failed. ";
if (isset($_FILES['upfile']['error'])) {
echo "Error code: ".$_FILES['upfile']['error'];
}
exit;
}
It's hard to say why it has failed, as there are many parameters involved. The Error code might give you a hint.
Otherwise maybe start reading here: http://de2.php.net/manual/en/features.file-upload.php
I was also having the same error, go to php.ini and go to line 800 "upload_max_filesize".
Choose your max upload file size, i set mine to 4M and in my actual website code I dont allow anything after 3mb.
For some reason having them both the same size doesnt work, PHP.ini needs to be atleast 1mb bigger than what you allow to be uploaded.
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)