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

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
?>

Related

How to make auto updating image gallery?

Well I have a upload script. What I need is how would I go about making it auto upload to a page on my site where it can be displayed as an image gallery?
Code:
<?php
// Configuration - Your Options
$allowed_filetypes = array('.jpg','.gif','.bmp','.png','.jpeg'); // These will be the types of file that will pass the validation.
$max_filesize = 1000000; // Maximum filesize in BYTES (currently 0.5MB).
$upload_path = './images/uploaded_images/'; // The place the files will be uploaded to (currently a 'files' directory).
$filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension).
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Get the extension from the filename.
// 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.');
// 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 upload was successful, view the file here'; // It worked.
else
echo 'There was an error during the file upload. Please try again.'; // It failed :(.
?>
Any Ideas?
One approach would be to scan the directory you are storing the images and write html for each file you encounter. Take a look at the scandir function. Some rudimentary code to get you started:
$upload_path = './images/uploaded_images/';
$files = scandir($upload_path);
foreach($files as $filename) {
if(is_image($filename)) {
echo "<div class='gallery-image'><img src='{$filename}'/></div>";
}
}
function is_image($filename) {
$image_extensions = array('jpg', 'jpeg', 'png', 'gif');
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
return in_array($ext, $image_extensions);
}

move_uploaded_file error 6 php

Attempting to move an uploaded file so that it is saved in the directory, it fails. I use echo ($_FILES['company_logo'] ['error']); to get the error number. The only place I could find with error numbers for this was http://www.htmlgoodies.com/beyond/php/article.php/3472561/PHP-Tutorial-Error-Handling.htm . However, their list only goes up to 4 and I am getting the error number 6. Does anyone know what this error stands for? Here is my code:
$allowed_filetypes = array('.jpg','.jpeg','.gif','.bmp','.png'); // These will be the types of file that will pass the validation.
$max_filesize = 524288; // Maximum filesize in BYTES (currently 0.5MB).
$upload_path = '../images/companies/'; // The place the files will be uploaded to (currently a 'files' directory).
if($_FILES['company_logo']['name'] != "") {
if($row['image'] != ''){
unlink("../".$row['image']);
}
$filename = $_FILES['company_logo']['name']; // Get the name of the file (including file extension).
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Get the extension from the filename.
$ext = strtolower($ext);
// 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.');
// Now check the filesize, if it is too large then DIE and inform the user.
if(filesize($_FILES['company_logo']['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.
$ran = rand();
$filename = $ran.$ext;
if(move_uploaded_file($_FILES['company_logo']['tmp_name'],$upload_path.$filename)){ // This is where it fails
$file = $upload_path.$filename;
$result = mysql_query("UPDATE Companies SET image = 'images/companies/$filename' WHERE id = '$id';");
if($result)
$_SESSION['message'] .= "<p class='copy' style='color:red;'>Your image upload was successful.</p>"; // It worked.
else
$_SESSION['message'] .= "<p class='copy' style='color:red;'>Unable to upload image(s).</p>";
}else{
$_SESSION['message'] .= "<p class='copy' style='color:red;'>Unable to upload image(s).</p>";
echo ($_FILES['company_logo'] ['error']);
die();
}
}
As you can see, I do check for an actual file being uploaded, if the file extension is in a list of file types allowed, if the file exceeds the max file size, and whether the path is even writable. So I don't believe it is any of those things, but I'm not certain. Any help would be appreciated.
PHP manual knows 99,99% answers.
UPLOAD_ERR_NO_TMP_DIR
Value: 6; Missing a temporary folder. Introduced in PHP 4.3.10 and
PHP 5.0.3.
Short answer: here is a list of all file upload errors which can occurs.
Your error is:
Value: 6; Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.

PHP bot assigning upload path

I'm having an issue where the path of my file upload isn't being assigned to the correct folder. It actually amends the file path to the file name of the file being uploaded. Weird right? Here's the code I'm working on...
<?php
$allowed_filetypes = array('.mp4','.gif','.bmp','.png','.html','.psd','.zip','.xml','.css','.js',);
$max_filesize = 5904288;
$upload_path = 'video';
$filename = $_FILES['userfile']['name'];
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
if(!in_array($ext,$allowed_filetypes))
die('Sorry, cannot take files over blankKB.');
if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
die('Sorry, cannot take files over blankKB.');
if(!is_writable($upload_path))
die('We are very sorry, a problem is occurring with the CHMOD of this directory');
if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename))
echo ' Your file was uploaded successfully, view it here';
else
echo 'Sorry, but there was an error during the file upload. Please try again.';
?>
Here's what the file looks like after being uploaded,
videoHello.png
plus it doesn't upload the file to the directory I want it in, located at /video
When you write $upload_path . $filename you are only concatenating the two strings, which does indeed result in videoHello.png;
You should either concatenate your system's directory separator (On Unix based systems it's /)
$upload_path . '/' . $filename
or build the separator into your string $upload_path
$upload_path = 'video/';
Though my final advice would be to use Absolute Paths like this:
$upload_path = dirname(__FILE__) . '/video/';

Why this php file upload validation script not working?

Dear friends, this is a script which simply upload file and insert filename into database, why is this not working ? It's just upload the file and send filename to db even after validation . Please help
<?php
//file validation starts
//split filename into array and substract full stop from the last part
$tmp = explode('.', $_FILES['photo']['name']);
$fileext= $tmp[count($tmp)-1];
//read the extension of the file that was uploaded
$allowedexts = array("png");
if(in_array($fileext, $allowedexts)){
return true;
}else{
$form_error= "Upload file was not supported<br />";
header('Location: apply.php?form_error=' .urlencode($form_error));
}
//file validation ends
//upload dir for pics
$uploaddir = './uploads/';
//upload file in folder
$uploadfile = $uploaddir. basename($_FILES['photo']['name']);
//insert filename in mysql db
$upload_filename = basename($_FILES['photo']['name']);
//upload the file now
move_uploaded_file($_FILES['photo']['tmp_name'], $uploadfile);
// $photo value is goin to db
$photo = $upload_filename;
function send_error($error = 'Unknown error accured')
{
header('Location: apply.php?form_error=' .urlencode($error));
exit; //!!!!!!
}
//file validation starts
//split filename into array and substract full stop from the last part
$fileext = end(explode('.', $_FILES['photo']['name'])); //Ricky Dang | end()
//read the extension of the file that was uploaded
$allowedexts = array("png");
if(!in_array($fileext, $allowedexts))
{
}
//upload dir for pics
$uploaddir = './uploads/';
if(!is_dir($uploaddir))
{
send_error("Upload Directory Error");
}
//upload file in folder
$uploadfile = $uploaddir. basename($_FILES['photo']['name']);
if(!file_exists($uploadfile ))
{
send_error("File already exists!");
}
//insert filename in mysql db
$upload_filename = basename($_FILES['photo']['name']);
//upload the file now
if(move_uploaded_file($_FILES['photo']['tmp_name'], $uploadfile))
{
send_error('Upload Failed, cannot move file!');
}
// $photo value is goin to db
$photo = $upload_filename;
This is a cleared up version to yours, give that a go and see if you get any errors
You can find the extension of file by using this code also.
$tmp = end(explode('.', $_FILES['photo']['name']));
now $tmp got the extension of file.
Why not use PHP's built-in functions to extract the extension from the filename?
$fileext = pathinfo($_FILES['photo']['name'],PATHINFO_EXTENSION);
And if the file extension is valid, you're returning from the function without doing anything further, if it's invalid you're setting the header, but the code logic will continue to your file processing
You blindly assume the file upload succeeded, but there's many reasons for it to fail, which is why PHP provides ['error'] in the $_FILES array:
if ($_FILES['photo']['error'] === UPLOAD_ERR_OK) {
// uploaded properly, handle it here...
} else {
die("File upload error, code #" . $_FILES['photo']['error']);
}
The error codes are defined here.

Restrict file upload to just jpegs with php

Please can someone help? I have the following code which uploads a file to my server and renames it to whoever the logged in user is. For example the user 'coca-cola-lover' uploads a jpeg - the script would also rename the jpeg 'coca-cola-lover.jpg'.
My problem is that I need it to limit the upload to just jpegs - and also limit the file size to 2mb.
Please help - I was trying to find a solution all night.
Thanks in advance
// Your file name you are uploading
$file_name = $HTTP_POST_FILES['ufile']['name'];
$username = $row_Recordset1['username'];
$ext = end(explode('.', $file_name));
$renamed_file_name = $username;
$new_file_name=$renamed_file_name.'.'.$ext;
//set where you want to store files
//in this example we keep file in folder upload
//$new_file_name = new upload file name
//for example upload file name cartoon.gif . $path will be upload/cartoon.gif
$path= "../sites/images/users/".$new_file_name;
if($ufile !=none)
{
if(copy($HTTP_POST_FILES['ufile']['tmp_name'], $path))
{
echo "Successful<BR/>";
//$new_file_name = new file name
//$HTTP_POST_FILES['ufile']['size'] = file size
//$HTTP_POST_FILES['ufile']['type'] = type of file
echo "File Name :".$new_file_name."<BR/>";
echo "File Size :".$HTTP_POST_FILES['ufile']['size']."<BR/>";
echo "File Type :".$HTTP_POST_FILES['ufile']['type']."<BR/>";
}
else
{
echo "Error";
}
}
getimagesize tells you what format the file is in
as per bgy's comment, you should also force the file extension to be what you want:
$new_file_name=$renamed_file_name.'.'.$ext; // wrong, uses data from the client
$new_file_name=$renamed_file_name.'.jpg'; // ok, just what we want
never trust and never use filenames provided by the client.
I would recommend exif_imagetype:
<?php
if (exif_imagetype('image.gif') != IMAGETYPE_GIF) {
die(The picture is not a gif');
}
For details see here: http://php.net/manual/en/function.exif-imagetype.php
You can use any of the four to detect a mimetype of the file:
finfo_open (by default enabled as of 5.3)
getimagesize (requires enabled GD)
exif_imagetype (requires enabled Exif)
mime_content_type (deprecated as of 5.3)
You can also limit the MimeType from the FileUpload element, but since this is client-side code, it can easily be removed by malicious users (and it's also buggy across browsers):
<input type="file" name="picture" id="picture" accept="image/jpeg"/>
For further information on how to handle file uploads with PHP (including limiting file size), check the manual.
There is also a lot of very similar questions on Stack Overflow already, one being:
Check picture file type and size before file upload in php
You restrict the size via the normal mechanisms, but you'll need to use the fileinfo functions to determine the filetype after uploading.
A few advices for the current code
Use $_FILES instead of $HTTP_POST_FILES.
If you need to get file extensions use $extension = pathinfo($filename, PATHINFO_EXTENSION);.
Use is_uploaded_file and move_uploaded_file.
Don't relay on $_FILES['file']['type'] - it can be modified by user.
Indent your code.
If you want to limit file upload to the following requirements:
Filesize: max 2mb.
File type: image/jpeg
Do something like that:
$tmpName = $_FILES['file']['tmp_name'];
if (file_is_uploaded($tmpName) {
$filesize = fielsize($tmpName);
$mimeType = exif_imagetype('image.gif');
if ($filesize <= 2 * 1024 * 1024 && $mimeType == IMAGETYPE_JPEG) {
$filename = $USERNAME . '.jpg';
if (move_uploaded_file($tmpName, $filename) == false) {
// sth goes wrong
}
} else {
die('Invalid.');
}
}

Categories