Possible Reasons Why a PHP File Upload Wouldn't Work - php

Here is the HTML:
<h1>Upload Custom Logo</h1>
<form action="settings.php" enctype="multipart/form-data" method="post">
<input type="file" name="Logo" />
<input type="submit" value="Upload" name="logoUpload" />
</form>
Here is the PHP:
<?php /* Handle Logo Upload */
if($_POST['logoUpload']) {
$target_path = "uploads/";
$Logo = $_FILES['Logo']['name'];
$target_path = $target_path . basename( $_FILES['Logo']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo '<div class="statusUpdate">The file '. basename( $_FILES['Logo']['name']).
' has been uploaded</div>';
}
} else{
echo '<div class="statusUpdate">There was an error uploading the file to: '.$target_path.', please try again! Error Code was: '.$_FILES['Logo']['error'].'</div>';
}
}
?>
It always goes to the "else" statement on that code, I have an uploads folder in the same directory as this php file set to 777 file permissions. The image I am test uploading is under 10KB in size. But the move_uploaded_file() always fails and it doesn't return any error message except for the custom error message made with the else statement.

You're referring to the file in the $_FILES array by two different names -
$Logo = $_FILES['Logo']['name'];
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)
Which one is it? Logo or uploadedfile ?
You're probably referencing an array index which doesn't exist.

Possible reasons:
The uploading of the file failed in some way.
You don't have permission to move the file to the target path.
As PHP.NET says:
If filename is not a valid upload file, then no action will occur, and
move_uploaded_file() will return FALSE.
If filename 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.
Reference: http://php.net/manual/en/function.move-uploaded-file.php

Related

why do i have a corrupted image file after using move_uploaded_file function

I have a form:
<form action='' enctype="multipart/form-data" method="post">
<input type="file" name="image">
<input type="submit" value="send">
</form>
I have php code:
$file = $_FILES['image']
$ext = explode(",", $file['type'])[0];
$location = "../image/movedimage.$ext";
if(move_uploaded_file($file['tmp_name'], $location)) echo 'moved';
else echo 'internal error';
This echos "moved" but the problem is that when I check the path to which the file was moved, the image file in there is corrupted.
I had to change the system of uploading the image by doing this:
$file_content = file_get_contents($file['tmp_name']);
$file_dump = file_put_contents($location, $file_content);
This attempt of placing the file directly using the file_put_contents works fine and the image file is perfect just as uploaded but using the move_uploaded_file leaves a corrupted file in the destination folder. I would like to understand why this is happening as the $file['error'] returns a value 0 and the move_uploaded_file function does not return false.
In your code by using
$ext = explode(",", $file['type'])[0];
you get the extension as image/your_image_type.
Then you are appending that with the file name, which will create an invalid image.
To get the extension, you can do as follows
$ext= explode("/", $file['type'])[1];
or
$ext = strtolower(end(explode('.',$_FILES['image']['name'])));

Understanding uploading files

I apologize for the super long post. I'm super noob and I would LOVE to have your help.
I made a file called Upload Pictures and in this file I have four files. First, php.ini with the following code:
file_uploads = On
Second, upload.html:
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
Third, upload.php:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
And fourth, I have a folder called uploads, with nothing inside that folder.
My main questions are from the upload.php file. Please correct me if I am incorrect in my understanding.
I understand $target_dir to be the directory in which the files will be stored. Now to the line with &target_file. I understand that $_FILES["fileToUpload"]["name"] returns the name of the file that I am uploading. So if my file name was picture.jpg, it will return picture.jpg.
My question is then, why do I need to call the basename()? Because I thought this function just returns the name of the file. So it's almost like returning the name twice with $_FILES["fileToUpload"]["name"] and basename()?
Also, it has been my experience that having a . and some function after is calling a method from a class. Is that what is happening here $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);? If so, I'm not sure what is actually being stored into $target_file.
Also, switching gears a little bit here, when I pressed the Upload Image button from my html, it takes me to another page. Is there a way to prevent that from happening?
basename returns the actual filename from a path.
In your example basename does not need to be used on the name being retrieved from $_FILES because it will have no associated path to begin with. In an upload script basename may be more traditionally used on tmp_name to remove any temporary folders from the name of the file.
The . is how you concatenate strings (or in this case variables containing strings) in PHP.
In this example, the code is concatenating the directory and the name of the file together into a variable in which it is used to get the extension in the $imageFileType variable using pathinfo.
The form has an action attribute. action="upload.php" so you will be taken to the 'upload.php' page when the form is submitted.
I hope this answers your questions-
actually basename() function for get file name with the extension of file.
so basename function stand for
basename(path,suffix)
Explanation
Parameter | Description
--------------------------
path | Required. Specifies the path to check
suffix | Optional. Specifies a file extension. If the filename has this file extension, the file extension will not show
Ex
<?php
$path = "/testweb/home.php";
//Show filename with file extension
echo basename($path) ."<br/>";
//Show filename without file extension
echo basename($path,".php");
?>
Output will be
home.php
home
php 5 basename() function
and we use . (dot) operator on here, $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
so this will bind $target_dir and basename(). so $target_file knows where is file should be goes exactly.

Keep getting two errors with my PHP file upload system

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.

Image upload to Temp Folder warning

From the script below, can anyone tell me what I've done wrong to get the warning message on output of the script? The upload script is -
Code:
<?php
// Access the $_FILES global variable for this specific file being uploaded
// and create local PHP variables from the $_FILES array of information
$fileName = $_FILES["thumb"]["name"]; // The file name
$fileTmpLoc = $_FILES["thumb"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["thumb"]["type"]; // The type of file it is
$fileSize = $_FILES["thumb"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["thumb"]["error"]; // 0 = false | 1 = true
$fileSplit = explode(".", $fileName); // Split file name into an array using the dot
$fileExt = end($fileSplit); // Now target the last array element to get the file extension
// START PHP Image Upload Error Handling --------------------------------------------------
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
} else if($fileSize > 5242880) { // if file size is larger than 5 Megabytes
echo "ERROR: Your file was larger than 5 Megabytes in size.";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
exit();
} else if (!preg_match("/.(gif|jpg|png)$/i", $fileName) ) {
// This condition is only if you wish to allow uploading of specific file types
echo "ERROR: Your image was not .gif, .jpg, or .png.";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
exit();
} else if ($fileErrorMsg == 1) { // if file upload error key is equal to 1
echo "ERROR: An error occured while processing the file. Try again.";
exit();
}
// END PHP Image Upload Error Handling ----------------------------------------------------
// Place it into your "Avatars" folder mow using the move_uploaded_file() function
$moveResult = move_uploaded_file($fileTmpLoc, "Avatars/$fileName");
// Check to make sure the move result is true before continuing
if ($moveResult != true) {
echo "ERROR: File not uploaded. Try again.";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
exit();
}
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
// Display things to the page so you can see what is happening for testing purposes
echo "The file named <strong>$fileName</strong> uploaded successfully.<br /><br />";
echo "It is <strong>$fileSize</strong> bytes in size.<br /><br />";
echo "It is an <strong>$fileType</strong> type of file.<br /><br />";
echo "The file extension is <strong>$fileExt</strong><br /><br />";
echo "The Error Message output for this upload is: $fileErrorMsg";
?>
My form is this
<?php
$profile_pic_btn = 'Toggle Avatar Form';
$avatar_form = '<form id="avatar_form" enctype="multipart/form-data" method="POST" action="process_reguser_exec.php">';
$avatar_form .= '<h4>Change your avatar</h4>';
$avatar_form .= '<input type="file" name="thumb">';
$avatar_form .= '<p><input type="submit" value="Upload"></p>';
$avatar_form .= '</form>';
?>
The output is this
Warning: unlink(C:\xampp\tmp\php8E40.tmp): No such file or directory in C:\xampp\htdocs\MyWebSite\process_reguser_exec.php on line 37
The file named image1.JPG uploaded successfully.
It is 3337452 bytes in size.
It is an image/jpeg type of file.
The file extension is JPG
The Error Message output for this upload is: 0
Line 37 is this
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
When you have used the move_uploaded_file command, the file in the tmp location is no longer there, and therefor cannot be removed, I would say.
Looking a bit harder at your code, consider a restructuring:
if(move_uploaded_file($fileTmpLoc, "Avatars/$fileName"))
{
// do the image stuff
}
else
{
echo "ERROR: An error occured uploading and storing your file. Please try again.";
// Add a test to see whether the file exists
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
exit();
}
The regEx that you are using here
preg_match("/.(gif|jpg|png)$/i", $fileName)
is probably wrong. Because it will return true even for this file name $fileName="adjGIF" and i hope that you do not want this.So instead use this
preg_match("/.(\.(gif|jpg|png))$/i", $fileName)
Note:- Even though its not the answer but it will make your code correct.
//returns TRUE if the file or directory specified by filename exists and is readable, FALSE otherwise.
if (is_readable($fileTmpLoc)) {
unlink($fileTmpLoc);
}
use below code to move image file in to avatar named folder :
move_uploaded_file($fileTmpLoc,"Avatars".$fileName);

PHP Uploader, can't upload to specified path, getting error

I am fairly new to PHP coding, but I am trying to do something that is quite simple.
When someone on my website uploads a picture, the image will get renamed to random numbers and moved to my directory 'uploads/'
In my script below, Everything has been working up until :
// Upload the file to your specified path.
if(move_uploaded_file($_FILES['userfile']['tmp_name'], $upload_path . $filename))
echo "Your file has been added. Redirecting in 3 seconds."; //it worked
else
echo "There was a problem uploading your file. Please try again later."; // It failed :(.
I have all of the variables defined.
not sure what the problem is here. Should I post my whole script for the uploader?
Here is the form:
<form enctype="multipart/form-data" action="uploader.php" method="POST">
<p>
<input type="hidden" name="MAX_FILE_SIZE" value="1048576" />
Choose a file to upload:
<br>(Only .jpg, .png, & .gif are allowed. Max file size = 1MB)</br></p>
<input name="uploadedfile" type="file" />
<input type="submit" value="Upload File" />
</form>
Here is my 'uploader.php'
<?php
header('Refresh: 3; URL=index.html');
$path = $_FILES['uploadedfile']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
//This line assigns a random number to a variable. You could also use a timestamp here if you prefer.
$ran = rand () ;
//This takes the random number (or timestamp) you generated and adds a . on the end, so it is ready of the file extension to be appended.
$ran2 = $ran.".";
//This assigns the subdirectory you want to save into... make sure it exists!
$target = "uploads/";
//This combines the directory, the random file name, and the extension
$target = $target . $ran2.$ext;
$ext = ".".$ext;
$upload_path = "uploads/";
$filename = $target;
$allowed_filetypes = array('.jpeg','.jpg','.gif','.bmp','.png'); // These will be the types of file that will pass the validation.
$max_filesize = 1048576; // Maximum filesize in BYTES (currently 0.5MB).
$filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension).
// Check if the filetype is allowed, if not DIE and inform the user.
if(!in_array($ext,$allowed_filetypes))
die('The file you attempted to upload is not allowed.'.$ext);
// Now check the filesize, if it is too large then DIE and inform the user.
if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
die('The file you attempted to upload is too large.');
// Check if we can upload to the specified path, if not DIE and inform the user.
if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.');
// Upload the file to your specified path.
if(move_uploaded_file($_FILES['userfile']['tmp_name'], $upload_path . $filename))
echo "Your file has been added. Redirecting in 3 seconds."; //it worked
else
echo "There was a problem uploading your file. Please try again later."; // It failed :(.
?>
You're resetting $filename to the original name of the file, undoing all your random name generation:
$filename = $target;
$allowed_filetypes = array('.jpeg','.jpg','.gif','.bmp','.png'); // These will be the types of file that will pass the validation.
$max_filesize = 1048576; // Maximum filesize in BYTES (currently 0.5MB).
// this line circumvents the random filename generation
$filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension).
Given that, I'd expect to see the above error if you upload a file with the same name twice.
Just get rid of that last $filename = .... line and see if your error goes away.
You try to move $_FILES['userfile']['tmp_name'] to another destination, but it seems your file is stored in $_FILES['uploadedfile']['tmp_name'] (as uploadedfile is the name of the file input in your form, and you correctly check it at the beggining of the script).
Also, I'd strongly recommend assigning all variables and using/modifying them in one place, otherwise you are vulenrable to such simple mistakes which are hard to track down.
Here's how I'd re-write your PHP code, it's a bit more clear I think:
<?php
header('Refresh: 3; URL=index.html');
//check if file uploaded correctly to server
if ($_FILES['uploadedfile']['error'] != UPLOAD_ERR_OK)
die('Some error occurred on file upload');
$filename = $_FILES['uploadedfile']['name'];
$uploadedFile = $_FILES['uploadedfile']['tmp_name'];
$ext = '.' . pathinfo($filename , PATHINFO_EXTENSION);
$upload_path = "uploads/";
//prepare random filename
do {
$newName = md5(rand().rand().rand().microtime()) . $ext;
} while (file_exists($upload_path . $newName));
$allowed_filetypes = array('.jpeg','.jpg','.gif','.bmp','.png'); // These will be the types of file that will pass the validation.
$max_filesize = 1048576; // Maximum filesize in BYTES (currently 0.5MB).
// Check if the filetype is allowed, if not DIE and inform the user.
if(!in_array($ext,$allowed_filetypes))
die('The file you attempted to upload is not allowed.'.$ext);
// Now check the filesize, if it is too large then DIE and inform the user.
if(filesize($uploadedFile) > $max_filesize)
die('The file you attempted to upload is too large.');
// Check if we can upload to the specified path, if not DIE and inform the user.
if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.');
// Upload the file to your specified path.
if(move_uploaded_file($uploadedFile, $upload_path . $newName))
echo "Your file has been added. Redirecting in 3 seconds."; //it worked
else
echo "There was a problem uploading your file. Please try again later."; // It failed
?>

Categories