Asked  2 Years ago    Answers:  13   Viewed   85 times

If I want to change my filename before it goes to the server for its permanent location, not its temporary Location how could I do this.

The code is as followed:

<form action="upload_file.php" method="post"
<label for="file">Filename:</label>
<input type="file" name="file" id="file" /> 
<br />
<input type="submit" name="submit" value="Submit" />

if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
  if ($_FILES["file"]["error"] > 0)
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

    if (file_exists("upload/" . $_FILES["file"]["name"]))
      echo $_FILES["file"]["name"] . " already exists. ";
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
  echo "Invalid file";



I'm not sure if I understand what you mean. If you just want to rename the file when storing it in the "upload" directory, do so when using move_uploaded_file():

$destination = "upload/" . $new_filename;
if (file_exists($destination)) {
    echo 'File ', $destination, ' already exists!';
} else {
    move_uploaded_file($temp_filename, $destination);

You could also let the user define $new_filename by providing an additional "rename" text field in your HTML form.

EDIT: Code could be something like that:


<form action="upload_file.php" method="post"
<label for="file">Filename:</label>
<input type="file" name="file" id="file" /> 
<br />

<!-- NEW TEXTBOX -->
<label for="newname">Rename to (optional):</label>
<input type="text" name="newname" id="newname" /> 
<br />

<input type="submit" name="submit" value="Submit" />


$upload_dir = realpath('upload') . DIRECTORY_SEPARATOR;
$file_info = $_FILES['file'];

// Check if the user requested to rename the uploaded file
if (!empty($_POST['newname'])) {
    $new_filename = $_POST['newname'];
} else {
    $new_filename = $file_info['name'];

// Make sure that the file name is valid.
if (strpos($new_filename, '/') !== false || strpos($new_filename, '\') !== false) {
    // We *have* to make sure that the user cannot save the file outside
    // of $upload_dir, so we don't allow slashes.
    // ATTENTION: You should do more serious checks here!
    die("Invalid filename");

$destination = $upload_dir . $new_filename;
// ... if (file_exists(... move_uploaded_file(...
Tuesday, August 30, 2022

How to do file uploads is explained in the PHP Manual:

  • POST method uploads
  • Error Messages Explained
  • Common Pitfalls
  • Uploading multiple files
  • PUT method support

Please go through these chapters to learn how to do uploads.

If you want to know how File Uploads are implemented in the PHP core, check out


Afaik, this is the module that handles this.

If none of the above do give you the information you are looking for, please refine your question to indicate what is missing.

Thursday, December 15, 2022

You have to create the directory you're trying to move the file to, it won't automatically get created by move_uploaded_file.

Use mkdir(),, to create the directory and then move the file.

Here's an alternative ending to your script, which should do

// Create directory if it does not exist
if(!is_dir("Proposals/". $_SESSION["FirstName"] ."/")) {
    mkdir("Proposals/". $_SESSION["FirstName"] ."/");

// Move the uploaded file
move_uploaded_file($_FILES["upload"]["tmp_name"], "Proposals/". $_SESSION["FirstName"] ."/". $_FILES["upload"]["name"]);

// Output location
echo "Stored in: " . "Proposals/". $_SESSION["FirstName"] ."/". $_FILES["upload"]["name"];
Wednesday, October 19, 2022

This is what I use, you can customize it to suit your script:

Simply change the *path and *variables.

// Configuration - Your Options
$allowed_filetypes = array('.mov','.mp3','.mp4','.flv'); // These will be the types of file that will pass the validation.
$max_filesize = 524288; // Maximum filesize in BYTES (currently 0.5MB).
$upload_path = './files/'; // 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.
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.
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 <a href="' . $upload_path . $filename . '" title="Your File">here</a>'; // It worked.
echo 'There was an error during the file upload. Please try again.'; // It failed :(.

Sunday, November 6, 2022

Unix does not keep track of when a file was created, only when it was changed, modified, and accessed. You can use filectime, filemtime, and fileatime, respectively to do this. If you are dealing with uploaded files, it is probably incredibly rare that you would alter the file at any time, so filemtime() is likely to give you the creation time.

Monday, November 28, 2022

That depends where you store the filename. If you store the name in a database, in strictly typed variable, then HTML encode before you display it on a web page, there won't be any issues.

Wednesday, August 31, 2022

The problem is how you're uploading it. data: contactForm.serialize() just won't work with files. You've got the correct form, but by replacing it with a jQuery AJAX request, you completely change the request.

It is possible to use AJAX to upload files in HTML5, and you don't need the form:

document.querySelector('#resume-file').addEventListener('change', function(e) {
    var file = this.files[0];
    var fd = new FormData();
    fd.append("resume", file);
    var xhr = new XMLHttpRequest();'POST', url, true);

    xhr.onload = function() {
        if (this.status == 200) {
            // success!!!


For more information see: MDN - Using FormData objects


Here's how to do it in jQuery too (taken from MDN docs):

var fd = new FormData(document.getElementById("fileinfo"));
fd.append("CustomField", "This is some extra data");
  url: "stash.php",
  type: "POST",
  data: fd,
  processData: false,  // tell jQuery not to process the data
  contentType: false   // tell jQuery not to set contentType
Wednesday, October 26, 2022

$_FILES['files']['error'] returns error code along with the file array. There are different type of error codes, all codes are mentioned in following link with details:

Please check by


and see what are you getting in response.

As you posted your array response, you can get error code by $_FILES['files']['error'][0] or use switch case as mentioned in following link.

See here for more details:

Also regarding debugging, always debug code step by step from top to bottom. Check $_POST, $_FILES, $_SERVER etc details if you get some problem particular related to data process.

Tuesday, September 20, 2022

This should work:

if(move_uploaded_file($_FILES['file']['tmp_name'], basename($_FILES['file']['name'])))
    die('Success! File Uploaded.');
    die('error uploading File!');

Edit: I've changed the destination argument - now uploaded file will appear next to your php file. Remember about target folder permissions.

Sunday, August 21, 2022

In your php.ini

; Maximum allowed size for uploaded files.
upload_max_filesize = 2M

and (added after suggestions from others below)

; Maximum size of POST data that PHP will accept.
post_max_size = 8M
Saturday, December 17, 2022

Your MIME type check is excluding some valid types for zip files. It varies by browser, but the most common types are:


You should allow all of those in your check. To match the rest of your code, make it something like:

$allowedCompressedTypes = array("application/x-rar-compressed", "application/zip", "application/x-zip", "application/octet-stream", "application/x-zip-compressed");

else if (in_array($_FILES["fajl"]["type"], $allowedCompressedTypes)
    && ($_FILES["fajl"]["size"] < 25000000)
    && in_array($extension1, $allowedExts1)) {
Wednesday, September 7, 2022

OK, the answer was simple. I was adding permissions for user: IIS_USRS, when it should have been just user: USRS.

Saturday, October 22, 2022

Look at your php.ini file for these 2 parameters, WAMPServer comes configured with

upload_max_filesize = 2M
post_max_size = 8M

Increase the upload_max_filesize to a little bigger that the largest file you want to allow to be unloaded. Or a lot larger if you intend to upload more than one file at a time.

Then increase post_max_size to a number LARGER that you set upload_max_filesize to so for example

upload_max_filesize = 80M
post_max_size = 85M

post_max_size must be larger that upload_max_filesize as the file is transported in the POST buffer as well as all other fields that may exist on your form

NOTE use the wampmanager icon to get to edit php.ini and that will ensure you edit the correct php.ini there are 2.

wampmanager -> php -> php.ini

Also remember to restart Apache once you have edited and saved php.ini

wampmanager -> Apache -> Service administration 'wampapache' -> Restart Service
Monday, August 29, 2022

PHP does read the file in chunks but it doesn't write them to individual files and then recombine them, it keeps writing them to the same temporary file which is the one you get in $_FILES.

It's the same for mod_php and CGI.

Here's the responsible code:

Tuesday, October 18, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :

Browse Other Code Languages