55

I'm working on a website and I want the user to be able to upload files. So I'm trying to learn how to do that. I researched and it said that I had to use the function move_uploaded_file(). I wrote the code just like it was on the example (changing the data), but it wouldn't work. Please help me, I'm new at these. Here's what I've done so far:

<!DOCTYPE html>
<html>
   <head>
   </head>
<body>
   <form action="upload_file.php" method="POST" enctype="multipart/form-data">
      <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
      <input type="file"name="file">
      <input type="submit">
   </form>
</body>
<html>

This is the upload_file.php:

<!DOCTYPE html>
<html>
  <head>
  <head>
     <body>
        <?php
          $move = "/Users/George/Desktop/uploads/";
          echo $_FILES["file"]['name']."<br>";
          echo $_FILES["file"]['tmp_name']."<br>";
          echo $_FILES["file"]['size']."<br>";
          echo $_FILES['file']['error']."<br>";
          move_uploaded_file($_FILES['file']['name'], $move);
        ?>
     <body>
<html>
7
  • The solution everybody is posting on the manual, did you check there? php.net/manual/en/function.move-uploaded-file.php
    – elclanrs
    Commented Sep 21, 2013 at 5:20
  • 4
    What are Directory permissions for /Users/George/Desktop/uploads/? That has to be writeable Commented Sep 21, 2013 at 5:23
  • I don't know what Directory Permissions is. Can you explain? Commented Sep 21, 2013 at 5:30
  • 1
    Are you running this website on linux or on windows? Commented Sep 21, 2013 at 5:42
  • I found the error ($move = "/Users/George/Desktop/uploads/"_.$_FILENAME['file']['name']_;). It works now. Thankyou! Commented Sep 21, 2013 at 6:29

18 Answers 18

69
  1. Enable PHP error reporting in order to see the error message from move_uploaded_file() that explains the problem.
  2. Check the $_FILES['image']['error'] variable.

In your case it's a wrong filename. The file will be stored in a temporary location, so use tmp_name instead of name:

move_uploaded_file($_FILES['image']['tmp_name'], __DIR__.'/../../uploads/'. $_FILES["image"]['name']);
// echo "Uploaded";
4
  • 2
    You should also check for return value of the function. What about directory permissions for your destination? Commented Sep 21, 2013 at 5:22
  • 1
    Don't use the given file name directly to store the upload files onto your file system. At least sanitize it.
    – Ja͢ck
    Commented Sep 21, 2013 at 7:15
  • Just to add to the comment by @Ja͢ck, you should also pass the name though basename(), as while PHP protects you at the moment, it's done for compatibility with Internet Explorer. In the future, if that was to be removed, then Evil Hacker ™ could do curl -F '[email protected];filename=../../../example.php' https://example.com/upload/ Commented Feb 19, 2020 at 15:25
  • @CraigFrancis Removing the basename operation from the engine would violate RFC 7578, so I've updated that portion of the code to enforce this idea. Additionally, there's an engine test on it to ensure that it won't be arbitrarily removed from the engine.
    – bishop
    Commented Feb 19, 2020 at 16:44
31

Try using copy() function instead of move_uploaded_file(). It worked for me.

copy($_FILES['file']['tmp_name'], $path);
3
  • This answer must be deleted. Commented Sep 5, 2022 at 14:54
  • @YourCommonSense why? It would be useful to read the reasoning (I'm not disagreeing)
    – Martin
    Commented Sep 5, 2022 at 15:03
  • you will have a tmp folder full of unused files. if you are uploading multiple and big files you will be in trouble Commented Jul 5, 2023 at 9:55
22

This is a working example.

HTML Form :

<form enctype="multipart/form-data" action="upload.php" method="POST">
    <input type="hidden" name="MAX_FILE_SIZE" value="512000" />
    Send this file: <input name="userfile" type="file" />
    <input type="submit" value="Send File" />
</form>

PHP Code :

<?php        
    $uploaddir = '/var/www/uploads/';
    $uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

    echo "<p>";

    if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
        echo "File is valid, and was successfully uploaded.\n";
    } else {
        echo "Upload failed";
    }

    echo "</p>";
    echo '<pre>';
    echo 'Here is some more debugging info:';
    print_r($_FILES);
    print "</pre>";
?>
11
$move = "/Users/George/Desktop/uploads/".$_FILES['file']['name'];

That's one.

move_uploaded_file($_FILES['file']['tmp_name'], $move);

That's two.

Check if the uploads dir is writeable

That's three.

Return Values

Returns TRUE on success.

If filename is not a valid upload file, then no action will occur, and move_uploaded_file() will return FALSE.

If filename is a valid upload file, but cannot be moved for some reason, no action will occur, and move_uploaded_file() will return FALSE. Additionally, a warning will be issued.

Look at return value of the function.

That's it.

1
  • Check if the uploads dir is writeable (very nice !) Commented Aug 28, 2019 at 10:40
6

maybe you need to grant more permissions to your files.

suppose your code are under /var/www/my_project

try chmod -R 777 /var/www/my_project

2
  • 9
    I strongly suggest you be aware of the security risks here. If you really need to do this, add php to the group that owns that folder and use 664 rather than 777
    – Jacksonkr
    Commented Jan 13, 2017 at 18:30
  • I'm doing testing on my local machine and changing the permissions of the upload folder was the fix that solved our teams issues for testing locally. Running sudo chmod 777 ./<uploads folder> allows for writing permissions from any user.
    – Kevin G
    Commented Mar 21, 2022 at 17:06
5

This answer is late but it might help someone like it helped me

Just ensure you have given the user permission for the destination file

sudo chown -R www-data:www-data /Users/George/Desktop/uploads/

3
  • 1
    the same happened to me on Mac. I had to give permissions
    – Glasnhost
    Commented Apr 30, 2020 at 12:34
  • 2
    @Thanks. its help me lot. Commented Jan 26, 2021 at 5:43
  • 1
    How often can I just kick myself. This is one of them. ty Commented May 19, 2021 at 14:18
4

try this

$ImageName = $_FILES['file']['name'];
$fileElementName = 'file';
$path = 'Users/George/Desktop/uploads/'; 
$location = $path . $_FILES['file']['name']; 
move_uploaded_file($_FILES['file']['tmp_name'], $location); 
4

You are not refering to the temporary location where the file is saved.

Use tmp_name to access the file.

You can always see what's getting posted using :

echo "<pre>"; 
print_r($_FILES);

If you see this files array you will have an better understanding and idea of what's going on.

2
  • So what if print_r($_FILES) prints an empty array? I did the same as OP.
    – Lewistrick
    Commented Jan 14, 2016 at 13:56
  • 2
    @Lewistrick it means that you might have forgot to mention the enctype attribute of form. Refer to this question : stackoverflow.com/questions/3586919/…
    – shivgre
    Commented Feb 24, 2016 at 11:44
2

it should like this

move_uploaded_file($_FILES['file']['tmp_name'], $move);

And you cannot move it anywhere in your system .youcan move it in only in your project directory which must be in htdocs or www depends on what you are using wampp ,lampp or vertrgo.

1
  • I'm using mamp and I tried with docs but it's still not working. Thank you. Commented Sep 21, 2013 at 5:25
2

If you are on a windows machine, there won't be any problems with uploading or writing to the specified folder path, except the syntactical errors.

But in case of Linux users, there is a workaround to this problem, even if there are no syntactical errors visible.

First of all, I am assuming that you are using this in a Linux environment and you need to upload something to your project folder in the public directory.

Even if you are having the write and read access to the project folder, PHP is not handled by the end user. It is and can be handled by a www-data user, or group.

So in order to make this www-data get access first type in;

sudo chgrp "www-data" your_project_folder

once its done, if there is no write access to the following as well;

sudo chown g+w your_project_folder

That will do the trick in Linux.

Please, not that this is done in a Linux environment, with phpmyadmin, and mysql running.

1

if files are not moving this could be due to several reasons

  • check permissions that upload directory , make sure its permission is at least 0755.
> find * -type d -print0 | xargs -0 chmod 0755 # for directories find *
> -type f -print0 | xargs -0 chmod 0666 # for files
  • make sure upload directory owner & group is not root , in that case your script will not be able to write anything there, so change it to admin or any non-root user.
chown -R admin:admin public_html      # will restore permission to admin  for folder and files within it 
chown  admin:admin public_html      # will restore permission to admin  for folder only will skip files
  • check your tmp directory that its writable or not so open php.ini and check upload_tmp_dir = your temp directory path , make sure its writable.
  • try copy function instead of move_uploaded_file
1

The mistake that I missed was not putting "enctype=multipart/form-data" as the element of the form. Just wanted to remind people because it might be your mistake

1

always set folder directory properly for image otherwise image will not be upload check my code for image upload if you issue still there let me know will help you

if (move_uploaded_file($_FILES['profile_picture']['tmp_name'],'../images/manager/'. 
    $_FILES["profile_picture"]['name'])) {
      echo "Uploaded";
} else {
      echo "File not uploaded";
}
1

move_uploaded_file($_FILES['file']['tmp_name'], $path) moves the file, which means temp file/buffers will be cleared from original source. move_uploaded_file() is open_basedir aware. However, restrictions are placed only on the to path as to allow the moving of uploaded files in which from path may conflict with such restrictions.

copy($_FILES['file']['tmp_name'], $to_path) When a file is copied, a duplicate is made means temporary buffers(source) is not cleaned. The $to_path should support overwriting of existing files.

0

If move_uploaded_file() is not working for you and you are not getting any errors (like in my case), make sure that the size of the file/image you are uploading is not greater than upload_max_filesize value in php.ini.

My upload_max_filesize value was 2MB on my localhost and I kept trying to upload a 4MB image for countless times while trying to figure out what the issue with move_uploaded_file() is.

0

For me, php.ini "upload_max_filesize" was too small (updated now and it works).

0

if you're working on centos greater than 6, you could check for sestatus....

if setenforce is 'enforcing' this might have repercussions on this PHP function, try with something like is_writeable('upload_dir'); to check if it's a writing permissions matter, and you can edit sestatus with>

setenforce permissive

this is one of many possible situations, like i said.

-1

Easiest Way to Uplaod a file

$FileName = $file_name;
$path = 'Users/Desktop/uploads/images'; 
$location = $path . $data['name']; 
move_uploaded_file($data['temp_name'],$location);

Not the answer you're looking for? Browse other questions tagged or ask your own question.