54

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>
Vikas Arora
  • 1,666
  • 2
  • 17
  • 38
user2480054
  • 527
  • 1
  • 4
  • 6

18 Answers18

68
  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";
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Vlad Miller
  • 2,255
  • 1
  • 20
  • 38
  • 2
    You should also check for return value of the function. What about directory permissions for your destination? – Hanky Panky Sep 21 '13 at 05: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 Sep 21 '13 at 07: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 'file=@example.php;filename=../../../example.php' https://example.com/upload/` – Craig Francis Feb 19 '20 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](https://github.com/php/php-src/blob/master/tests/basic/rfc1867_max_file_size.phpt#L24) on it to ensure that it won't be arbitrarily removed from the engine. – bishop Feb 19 '20 at 16:44
29

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

copy($_FILES['file']['tmp_name'], $path);
Shahzad Barkati
  • 2,532
  • 6
  • 25
  • 33
user3502785
  • 299
  • 3
  • 3
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>";
?>
ROOT
  • 11,363
  • 5
  • 30
  • 45
Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
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.

Hanky Panky
  • 46,730
  • 8
  • 72
  • 95
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

Joe Cheng
  • 8,804
  • 3
  • 26
  • 25
  • 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 Jan 13 '17 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 ./` allows for writing permissions from any user. – Kevin G Mar 21 '22 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/

King Of The Jungle
  • 735
  • 1
  • 11
  • 17
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); 
chirag ode
  • 950
  • 7
  • 15
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.

mcls
  • 9,071
  • 2
  • 29
  • 28
shivgre
  • 1,163
  • 2
  • 13
  • 29
  • So what if print_r($_FILES) prints an empty array? I did the same as OP. – Lewistrick Jan 14 '16 at 13:56
  • 2
    @Lewistrick it means that you might have forgot to mention the enctype attribute of form. Refer to this question : http://stackoverflow.com/questions/3586919/why-would-files-be-empty-when-uploading-files-to-php – shivgre Feb 24 '16 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.

Garry
  • 595
  • 4
  • 19
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.

HexaCrop
  • 3,863
  • 2
  • 23
  • 50
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
user889030
  • 4,353
  • 3
  • 48
  • 51
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

VOIZ
  • 11
  • 1
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";
}
abubakkar tahir
  • 737
  • 1
  • 11
  • 13
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.

yenren
  • 450
  • 9
  • 20
0

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.

Syed Waqas Bukhary
  • 5,130
  • 5
  • 47
  • 59
0

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

codr
  • 889
  • 3
  • 13
  • 22
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.

Pablo Contreras
  • 558
  • 6
  • 11
-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);
Love Kumar
  • 1,056
  • 9
  • 10