1

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 :(.

?>
6
  • what error are you getting? Commented Nov 27, 2013 at 23:29
  • On my website, when I click the "Submit" button, the error says "There was a problem uploading your file. Please try again later." Commented Nov 27, 2013 at 23:31
  • is $upload_path a server path or relative? $_SERVER['DOCUMENT_ROOT'].'/uploads/filename.ext'; for example Commented Nov 27, 2013 at 23:36
  • It would be a server path. The variable is set to 'uploads' which is a directory on the server. Commented Nov 27, 2013 at 23:46
  • ok but is uploads in the same directory as uploader.php? Commented Nov 28, 2013 at 0:02

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Erased the last $filename variable. Still no luck, same error.
0

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 

?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.