Just playing around with uploading files as it's actually something I've never done before. I copied some supposedly working code from here.
I'm using cPanel hosting from Namecheap, with absolutely nothing changed from the default config.
I think the most likely problem is something very basic that I haven't activated. My HTML looks like this
<html>
<body>
<form action="upload_file.php" method="post" enctype="multipart/form-data">
Your Photo: <input type="file" name="photo" size="25" />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
and my PHP looks like this
<?php
//if they DID upload a file...
if($_FILES['photo']['name'])
{
//if no errors...
if(!$_FILES['photo']['error'])
{
//now is the time to modify the future file name and validate the file
$new_file_name = strtolower($_FILES['photo']['tmp_name']); //rename file
if($_FILES['photo']['size'] > (1024000)) //can't be larger than 1 MB
{
$valid_file = false;
$message = 'Oops! Your file\'s size is to large.';
}
//if the file has passed the test
if($valid_file)
{
//move it to where we want it to be
move_uploaded_file($_FILES['photo']['tmp_name'], 'uploads/'.$new_file_name);
$message = 'Congratulations! Your file was accepted.';
}
}
//if there is an error...
else
{
//set that to be the returned message
$message = 'Ooops! Your upload triggered the following error: '.$_FILES['photo']['error'];
}
}
//you get the following information for each file:
$_FILES['field_name']['name']
$_FILES['field_name']['size']
$_FILES['field_name']['type']
$_FILES['field_name']['tmp_name']
}
When I try to upload an image, I get a 500 Internal Server Error when I hit submit.
What am I missing?
Thanks
Get rid of the stuff at the bottom:
<?php
//if they DID upload a file...
if($_FILES['photo']['name'])
{
//if no errors...
if(!$_FILES['photo']['error'])
{
//now is the time to modify the future file name and validate the file
$new_file_name = strtolower($_FILES['photo']['tmp_name']); //rename file
if($_FILES['photo']['size'] > (1024000)) //can't be larger than 1 MB
{
$valid_file = false;
$message = 'Oops! Your file\'s size is to large.';
}
//if the file has passed the test
if($valid_file)
{
//move it to where we want it to be
move_uploaded_file($_FILES['photo']['tmp_name'], 'uploads/'.$new_file_name);
$message = 'Congratulations! Your file was accepted.';
}
}
//if there is an error...
else
{
//set that to be the returned message
$message = 'Ooops! Your upload triggered the following error: '.$_FILES['photo']['error'];
}
}
Not sure what that was for... Also, try checking the Namecheap php.ini in your CPanel to see what the max upload size is so your users get your error, not a PHP error or a 500.
Related
I need to get this script to check if the uploaded file is a video file or not and whether the file size is too big or not over the limit. Therefore, need to replace the getimagesize with something else that gets the video file size. How can I accomplish this? Which function to use here? getvideosize function does not exist.
This is where I am stuck.
<?php
if($_SERVER["REQUEST_METHOD"] == "POST")
{
//Check whether the file was uploaded or not without any errors.
if(!isset($_FILES["id_verification_video_file"]) &&
$_FILES["id_verification_video_file"]["Error"] == 0)
{
$Errors = Array();
$Errors[] = "Error: " . $_FILES["id_verification_video_file"]
["ERROR"];
print_r($_FILES); ?><br><?php
print_r($_ERRORS);
exit();
}
else
{
//Feed Id Verification Video File Upload Directory path.
$directory_path = "uploads/videos/id_verifications/";
//Make Directory under $user in 'uploads/videos/id_verifications'
Folder.
if(!is_dir($directory_path . $user)) //IS THIS LINE CORRECT ?
{
$mode = "0777";
mkdir($directory_path . $user, "$mode", TRUE); //IS THIS LINE
CORRECT ?
}
//Grab Uploading File details.
$Errors = Array(); //SHOULD I KEEP THIS LINE OR NOT ?
$file_name = $_FILES["id_verification_video_file"]["name"];
$file_tmp = $_FILES["id_verification_video_file"]["tmp_name"];
$file_type = $_FILES["id_verification_video_file"]["type"];
$file_size = $_FILES["id_verification_video_file"]["size"];
$file_error = $_FILES['id_verification_video_file']['error'];
$file = $_FILES["id_verification_video_file"]["name"];
// in PHP 4, we can do:
$fhandle = finfo_open(FILEINFO_MIME);
$mime_type = finfo_file($fhandle,$file); // e.g. gives "video/mp4"
// in PHP 5, we can do:
$file_info = new finfo(FILEINFO_MIME); // object oriented approach!
$mime_type = $file_info->buffer(file_get_contents($file)); // e.g. gives
"video/mp4"
switch($mime_type) {
case "video/mp4":
// my actions go here...
}
// Let's assume that the name attribute of the file input field I have
used is "id_verification_video_file"
$tempFile = $_FILES['id_verification_video_file']['tmp_name']; // path of
the temp file created by PHP during upload. I MOST LIKELY GOT THIS LINE
WRONG AT THE END PART. HOW TO CORRECT THIS ?
$videoinfo_array = getimagesize($tempFile); // returns a false if not a
valid image file
if ($videoinfo_array !== false) {
$mime_type = $videoinfo_array['mime'];
switch($mime_type) {
case "video/mp4":
// your actions go here...
move_uploaded_file("$file_tmp", "$directory_path" . "$user/" .
"$file_name"); //IS THIS LINE CORRECT ?
//Notify user their Id Verification Video File was uploaded successfully.
echo "Your Video File \"$file_name\" has been uploaded successfully!";
exit();
}
}
else {
echo "This is not a valid video file";
}
}
}
?>
<form METHOD="POST" ACTION="" enctype="multipart/form-data">
<fieldset>
<p align="left"><h3><?php $site_name ?> ID Video Verification Form</h3></p>
<div class="form-group">
<p align="left"<label>Video File: </label>
<input type="file" name="id_verification_video_file"
id="id_verification_video_file" value="uploaded 'Id Verification Video
File.'"></p>
</div>
</fieldset>
<p align="left"><button type="submit" class="btn btn-default"
name="id_verification_video_file_submit">Submit!</button></p>
</form>
</body>
</html>
<?php
include 'footer_account.php'; //Required on all webpages of the Site.
?>
Best I done so far is above. I'd appreciate if you guys can add the correct lines where they should be and add comments so I can easily spot your changes and learn from the corrections.
EDIT:
Folks, I managed to fix a lot of things on my current update. But, one new problem. The move_uploaded_file() is failing. Why is that ? Do have a look. I actually wrote my questions to you in my code's comments in CAPITAL. If you could kindly answer these questions then I'd be grateful and hopefully we could close this thread as SOLVED asap.
<?php
//Required PHP Files.
include 'header_account.php'; //Required on all webpages of the Site.
?>
<?php
if (!$conn)
{
$error = mysqli_connect_error();
$errno = mysqli_connect_errno();
print "$errno: $error\n";
exit();
}
if($_SERVER["REQUEST_METHOD"] == "POST")
{
//Check whether the file was uploaded or not without any errors.
if(!isset($_FILES["id_verification_video_file"]) &&
$_FILES["id_verification_video_file"]["Error"] == 0)
{
$Errors = Array();
$Errors[] = "Error: " . $_FILES["id_verification_video_file"]
["ERROR"];
print_r($_FILES); ?><br><?php
print_r($_ERRORS);
exit();
}
else
{
//Feed Id Verification Video File Upload Directory path.
$directory_path = "uploads/videos/id_verifications";
//Make Directory under $user in
'uploads/videos/id_verifications' Folder if it doesn't exist.
if(!is_dir("$directory_path/$user")) //IS THIS LINE CORRECT ?
{
$mode = "0777";
mkdir("$directory_path/$user", $mode, TRUE); //IS THIS
LINE CORRECT ?
}
//Grab Uploading File details.
$Errors = Array(); //SHOULD I KEEP THIS LINE OR NOT ?
$file_name = $_FILES["id_verification_video_file"]["name"];
$file_tmp = $_FILES["id_verification_video_file"]
["tmp_name"];
$file_type = $_FILES["id_verification_video_file"]["type"];
echo "File Type: $file_type<br>"; //Outputs: "". WHY $file_type SHOWS
BLANK VALUE WHEN UPLOADING VIDEO FILES ? WORKS WITH OTHER FILES, LIKE
JPEG.
$file_size = $_FILES["id_verification_video_file"]["size"];
$file_error = $_FILES['id_verification_video_file']['error'];
echo "File Name: $file_name<br>"; //Outputs: "id_check.mp4"
//Grab Uploading File Extension details.
$file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
echo "File Extension: $file_extension<br>"; //Outputs: "mp4"
if(file_exists($directory_path . "$user/" . $file_name))
//WHICH LINE IS CORRECT ? THIS ONE OR THE NEXT ONE ?
//if(file_exists($directory_path . $user . '/' . $file_name))
//WHICH LINE IS CORRECT ? THIS ONE OR THE PREVIOUS ONE ?
{
$Errors[] = "Error: You have already uploaded a video
file to verify your ID!";
exit();
}
else
{
//Feed allowed File Extensions List.
$allowed_file_extensions = array("video/mp4");
//Feed allowed File Size.
$max_file_size_allowed_in_bytes = 1024*1024*1; //Allowed
limit: 100MB.
$max_file_size_allowed_in_kilobytes = 1024*1;
$max_file_size_allowed_in_megabytes = 1;
$max_file_size_allowed =
"$max_file_size_allowed_in_bytes";
//Create a fileinfo respource.
$finfo = finfo_open(FILEINFO_MIME_TYPE);
//Apply the fileinfo resource and the finfo_file()
function to the uploading given file.
$mime = finfo_file($finfo,$file_name);
//Close the fileinfo resource.
finfo_close($finfo); echo "Mime: $mime<br>"; //exit;
//Outputs: video/mp4
//Verify File Extension.
//if(!in_array($file_extension, $allowed_file_extensions))
die("Error 1: Select a valid video file format. Select an Mp4 file.");
//Verify MIME Type of the File.
if(!in_array($mime, $allowed_file_extensions)) die("Error 2:
Select a valid video file format. Select an Mp4 file.");
elseif(!in_array($file_type, $allowed_file_extensions))
die("Error 3: There was a problem uploading your file $file_name! Make
sure your file is an MP4 video file. You may try again."); //IS THIS LINE
CORRECT ?
//Verify File Size. Allowed Max Limit: 1MB.
if($file_size>$max_file_size_allowed) die("Error 4: Your
Video File Size is larger than the allowed limit of:
$max_file_size_allowed_in_megabytes.");
//Move uploaded File to newly created directory on the
server.
if(!move_uploaded_file($file_tmp,
"$directory_path/$user/$file_name")) die("Error 5: Your file failed to
upload! Try some other time.");
else
{
move_uploaded_file($file_tmp,
"$directory_path/$user/$file_name"); //WHY IS NOT THIS LINE OF CODE
MOVING THE FILE TO DESTINATION ?
//Notify user their Id Verification Video File was
uploaded successfully.
echo "Your Video File \"$file_name\" has been uploaded
successfully!";
exit();
}
}
}
}
?>
<form METHOD="POST" ACTION="" enctype="multipart/form-data">
<fieldset>
<p align="left"><h3><?php $site_name ?> ID Video Verification Form</h3>
</p>
<div class="form-group">
<p align="left"<label>Video File: </label>
<input type="file" name="id_verification_video_file"
id="id_verification_video_file" value="uploaded 'Id Verification Video
File.'"></p>
</div>
</fieldset>
<p align="left"><button type="submit" class="btn btn-default"
name="id_verification_video_file_submit">Submit!</button></p>
</form>
</body>
</html>
<?php
include 'footer_account.php'; //Required on all webpages of the Site.
?>
I get echoed when trying to upload an mp4 file:
Error 3: There was a problem uploading your file id_check.mp4! Make sure your file is an MP4 video file. You may try again.
Should I set the folder permissions to 0644 from 0777 ? I am being told I should not allow any files to be executable in the folder by users (file uploaders) and so I should set it to readable & writeable only to "0644". I need your expert opinion on this.
I want to be able to upload images from my Windows Phone 8 app, to my website.
For this, I followed the tutorial from this website:
https://vortexwolf.wordpress.com/2013/06/04/windows-phone-select-and-upload-image-to-a-website-over-http-post/
It all worked good, on the windows phone app side. But I have problems getting the website upload.php file working. In that tutorial, the author is using http://posttestserver.com/post.php?dir=wp7posttest to get the response of upload. In my case, using that URL for testing was working good, but when I put my website url, I get no response, and a crash in visual studio, with following error:
Additional information: The remote server returned an error: NotFound.
This error happens is thrown on this line:
response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
The upload.php on my website, looks like this:
if(isset($_GET['dir']))
{
$dir = $_GET['dir'];
if($_FILES['photo']['name'])
{
if(!$_FILES['photo']['error'])
{
$new_file_name = strtolower($_FILES['photo']['tmp_name']);
if($_FILES['photo']['size'] > (1024000))
{
$valid_file = false;
$message = 'Oops! Your file\'s size is to large.';
}
if($valid_file)
{
move_uploaded_file($_FILES['photo']['tmp_name'], '../$dir/' . $new_file_name);
$message = 'Congratulations! Your file was accepted.';
}
}
else
{
$message = 'Ooops! Your upload triggered the following error: '.$_FILES['photo']['error'];
}
}
echo $message;
}
I am out of ideas, and stuck on this problem for the second day. Any answers/ideas of how to get the website upload.php file working properly?
Thanks!
I don't know if my code it's correct, but everything indicates success when sending..
My Form
<form action="upload.php" method="POST" enctype="multipart/form-data">
File: <input type="file" name="file" />
<input type="submit" name="submit" value="Go" />
</form>
My Upload File
<?php
if($_FILES['file']['name'])
{
if(!$_FILES['file']['error'])
{
$valid_file = true;
if($_FILES['file']['size'] > (1024000)) //can't be larger than 1 MB
{
$valid_file = false;
$message = 'Oops! Your file\'s size is to large.';
}
if($valid_file)
{
/
if(move_uploaded_file($_FILES['file']['tmp_name'],'/files')){
echo "Sent";
}else{
echo "~Error~";
}
}
}
//if there is an error...
else
{
$message = 'Ooops! Your upload triggered the following error: '.$_FILES['file']['error'];
}
}
?>
The message that I get is "Sent", but when I go to check, the folder files is empty :s
My folder structure is:
/files - Here is directory where the files will come
index.php - My form
upload.php - My Logic
One of the issues that I see in your code is that you do not specify a name for your "moved" file:
This line:
move_uploaded_file($_FILES['file']['tmp_name'],'/files')
Should be changed to:
move_uploaded_file($_FILES['file']['tmp_name'],'/files/'.'sampleName'.$extension);// extension is the extension of the file.
I still assume your '/files' path is correct and does not have permission problem.
Same issue arises if your target folder has no write permission.
Use this command to change that:
chmod 775 [folder-name]
im using this php video upload script. i have set my directory path to a folder called video which i have created with the same directory as the php file. But i can not find the video being uploaded.
It is not going to the directory i have asked it to? Why is this can someone please help me.
I am not receiving any errors.
Thanks.
HTML:
<form action="upload_videos_process.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="uploadFile" id="uploadFile" />
<br />
<input type="submit" name="submit" value="Upload File" />
</form>
php file:
<?php
//This handles the maximum size for the video file in kbs
define ("MAX_SIZE","500");
//This function reads the extension of the file to ensure that it is an video file
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
//This variable handles an error and won't upload the file if there is a problem with it
$errors=0;
//checks if the form has been submitted
if(isset($_POST['Submit']))
{
//reads the name of the file the user submitted for uploading
$video=$_FILES['video']['name'];
//if it is not empty
if ($video)
{
//get the original name of the file from the clients machine
$video_filename = stripslashes($_FILES['video']['name']);
$video_extension = getExtension($filename);
$video_extension = strtolower($extension);
//if it is not a known extension, we will suppose it is an error and will not upload the file, otherwise we will do more tests
if (($video_extension != "mpeg") && ($video_extension != "avi") && ($video_extension != "flv") && ($video_extension != "mov"))
{
echo '<h1>Unknown extension!</h1>';
$errors=1;
}
else
{
//get the size of the video
$size=filesize($_FILES['video']['tmp_name']);
//compare the size with the maxim size we defined and print error if bigger
if ($size > MAX_SIZE*1024)
{
echo '<h1>You have exceeded the size limit!</h1>';
$errors=1;
}
//give the video a unique name in case a video already exists with the name on the server
$video_name=time().'.'.$extension;
//assign a folder to save the video to on your server
$newname="video/".$video_name;
//verify that the video has been loaded
$copied = copy($_FILES['video']['tmp_name'], $newname);
if (!$copied)
{
echo '<h1>Copy unsuccessful!</h1>';
$errors=1;
}}}}
//If no errors registered, print the success message
if(isset($_POST['Submit']) && !$errors)
{
echo "<h1>File Uploaded Successfully! Try again!</h1>";
}
?>
You've blindly assumed everything's working perfectly. Things fail. First step: check if the upload actually did anything:
if ($_FILES['video']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error code " . $_FILES['video']['error']);
}
The error codes are defined here: http://php.net/manual/en/features.file-upload.errors.php
As well, don't use copy() on the upload file, once you've verified the upload succeeded. There's move_uploaded_file() for a reason - it has extra security checks to ensure that the file hasn't been tampered with on the server, and it actually MOVES the file. copy() can kill performance, especially on large files, since you're duplicating the file, instead of just doing some filesystem housekeeping.
You're also trusting the user to not tamper with the filename. There is NOTHING to prevent a malicious user from doing ren nastyvirus.exe cutekittens.avi before uploading, and your script will happily accept that .exe, because its filename has simply been changed. Use server-side mime-detection (e.g http://www.php.net/manual/en/book.fileinfo.phpenter link description here) to get around this. NEVER trust ANYTHING from a user.
It might be because your php configuration does not allow to upload big files. Try setting
upload_max_filesize = 500M
or even larger than 500M in php.ini & also as ppl mention here in comments, enable the errors
ini_set('display_errors', 1);
ini_set('error_reporting', 8191);
I do some form validation to ensure that the file a user uploaded is of the right type. But the upload is optional, so I want to skip the validation if he didn't upload anything and submitted the rest of the form. How can I check whether he uploaded something or not? Will $_FILES['myflie']['size'] <=0 work?
You can use is_uploaded_file():
if(!file_exists($_FILES['myfile']['tmp_name']) || !is_uploaded_file($_FILES['myfile']['tmp_name'])) {
echo 'No upload';
}
From the docs:
Returns TRUE if the file named by
filename was uploaded via HTTP POST.
This is useful to help ensure that a
malicious user hasn't tried to trick
the script into working on files upon
which it should not be working--for
instance, /etc/passwd.
This sort of check is especially
important if there is any chance that
anything done with uploaded files
could reveal their contents to the
user, or even to other users on the
same system.
EDIT: I'm using this in my FileUpload class, in case it helps:
public function fileUploaded()
{
if(empty($_FILES)) {
return false;
}
$this->file = $_FILES[$this->formField];
if(!file_exists($this->file['tmp_name']) || !is_uploaded_file($this->file['tmp_name'])){
$this->errors['FileNotExists'] = true;
return false;
}
return true;
}
This code worked for me. I am using multiple file uploads so I needed to check whether there has been any upload.
HTML part:
<input name="files[]" type="file" multiple="multiple" />
PHP part:
if(isset($_FILES['files']) ){
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
if(!empty($_FILES['files']['tmp_name'][$key])){
// things you want to do
}
}
#karim79 has the right answer, but I had to rewrite his example to suit my purposes. His example assumes that the name of the submitted field is known and can be hard coded in. I took that a step further and made a function that will tell me if any files were uploaded without having to know the name of the upload field.
/**
* Tests all upload fields to determine whether any files were submitted.
*
* #return boolean
*/
function files_uploaded() {
// bail if there were no upload forms
if(empty($_FILES))
return false;
// check for uploaded files
$files = $_FILES['files']['tmp_name'];
foreach( $files as $field_title => $temp_name ){
if( !empty($temp_name) && is_uploaded_file( $temp_name )){
// found one!
return true;
}
}
// return false if no files were found
return false;
}
You should use $_FILES[$form_name]['error']. It returns UPLOAD_ERR_NO_FILE if no file was uploaded. Full list: PHP: Error Messages Explained
function isUploadOkay($form_name, &$error_message) {
if (!isset($_FILES[$form_name])) {
$error_message = "No file upload with name '$form_name' in form.";
return false;
}
$error = $_FILES[$form_name]['error'];
// List at: http://php.net/manual/en/features.file-upload.errors.php
if ($error != UPLOAD_ERR_OK) {
switch ($error) {
case UPLOAD_ERR_INI_SIZE:
$error_message = 'The uploaded file exceeds the upload_max_filesize directive in php.ini.';
break;
case UPLOAD_ERR_FORM_SIZE:
$error_message = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.';
break;
case UPLOAD_ERR_PARTIAL:
$error_message = 'The uploaded file was only partially uploaded.';
break;
case UPLOAD_ERR_NO_FILE:
$error_message = 'No file was uploaded.';
break;
case UPLOAD_ERR_NO_TMP_DIR:
$error_message = 'Missing a temporary folder.';
break;
case UPLOAD_ERR_CANT_WRITE:
$error_message = 'Failed to write file to disk.';
break;
case UPLOAD_ERR_EXTENSION:
$error_message = 'A PHP extension interrupted the upload.';
break;
default:
$error_message = 'Unknown error';
break;
}
return false;
}
$error_message = null;
return true;
}
<!DOCTYPE html>
<html>
<body>
<form action="#" method="post" enctype="multipart/form-data">
Select image to upload:
<input name="my_files[]" type="file" multiple="multiple" />
<input type="submit" value="Upload Image" name="submit">
</form>
<?php
if (isset($_FILES['my_files']))
{
$myFile = $_FILES['my_files'];
$fileCount = count($myFile["name"]);
for ($i = 0; $i <$fileCount; $i++)
{
$error = $myFile["error"][$i];
if ($error == '4') // error 4 is for "no file selected"
{
echo "no file selected";
}
else
{
$name = $myFile["name"][$i];
echo $name;
echo "<br>";
$temporary_file = $myFile["tmp_name"][$i];
echo $temporary_file;
echo "<br>";
$type = $myFile["type"][$i];
echo $type;
echo "<br>";
$size = $myFile["size"][$i];
echo $size;
echo "<br>";
$target_path = "uploads/$name"; //first make a folder named "uploads" where you will upload files
if(move_uploaded_file($temporary_file,$target_path))
{
echo " uploaded";
echo "<br>";
echo "<br>";
}
else
{
echo "no upload ";
}
}
}
}
?>
</body>
</html>
But be alert. User can upload any type of file and also can hack your server or system by uploading a malicious or php file. In this script there should be some validations. Thank you.
is_uploaded_file() is great to use, specially for checking whether it is an uploaded file or a local file (for security purposes).
However, if you want to check whether the user uploaded a file,
use $_FILES['file']['error'] == UPLOAD_ERR_OK.
See the PHP manual on file upload error messages. If you just want to check for no file, use UPLOAD_ERR_NO_FILE.
I checked your code and think you should try this:
if(!file_exists($_FILES['fileupload']['tmp_name']) || !is_uploaded_file($_FILES['fileupload']['tmp_name']))
{
echo 'No upload';
}
else
echo 'upload';
In general when the user upload the file, the PHP server doen't catch any exception mistake or errors, it means that the file is uploaded successfully.
https://www.php.net/manual/en/reserved.variables.files.php#109648
if ( boolval( $_FILES['image']['error'] === 0 ) ) {
// ...
}