Justin Justin - 1 year ago 43
PHP Question

PHP move_uploaded_file changing the name of the stored file?

I got some code from here

While this code works, it uploads the original file name to the server. I have a random string generator that i want to name the files with:

function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
return $randomString;



$picName = generateRandomString();
$_SESSION['picName'] = $picName;

Where $picName is getting sent to the database, and we will use the $_SESSION['picName'] on the upload2.php file.

Here is the html:

<form method="post" action="upload2.php" enctype="multipart/form-data" >
<input type="file" name="img" />

And here is upload2.php:


$picName = $_SESSION['picName'];
$target_path = "files/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);

if(move_uploaded_file($_FILES['img']['tmp_name'], $target_path)) {
echo "The file has been uploaded";
} else{
echo "There was an error uploading the drivers licence picture, please try again!";

So the question is, where in upload2.php do I need to set the new name ($picname) to change the final name of the file?


See this line,

if(move_uploaded_file($_FILES['img']['tmp_name'], $target_path)) {...

Where $target_path is "files/" . basename( $_FILES['uploadedfile']['name']);.

Few errors:

  • $_FILES['uploadedfile']['name'] is wrong. You've named the input field as img, so it should be $_FILES['img']['name']
  • Look at your $target_path, you're uploading the file with same file name.

To upload a file with a new file name, do this:

$target_path = "files/";
$target_path = $target_path . $picName . "." . strtolower(pathinfo($_FILES['img']['name'], PATHINFO_EXTENSION));