Why does my PHP file download code not work?

advertisements

I am trying to make a simple file upload form using PHP. Here's my code:

<?php
    $uploads_dir = '/uploads';

    if(isset($_FILES['thefile'])){
      $errors= array();
      $file_name = $_FILES['thefile']['name'];
      $file_size =$_FILES['thefile']['size'];
      $file_tmp =$_FILES['thefile']['tmp_name'];
      $file_type=$_FILES['thefile']['type'];
      $tmp_name = $_FILES['thefile']["tmp_name"];

      if($file_size > 2097152){
         $errors[]='File size must be less than 2 MB';
      }
      if(empty($errors)==true){
         move_uploaded_file($tmp_name, "$uploads_dir/$file_name");
         echo "Success";
      }
      else{
         print_r($errors);
      }
   }
?>
<!DOCTYPE html>
<html>
<head>
    <title>Simple File Upload</title>
</head>
<body>

<form action="" method="POST" enctype="multipart/form-data">
    <input type="file" name="thefile" />
    <input type="submit"/>
</form>

</body>
</html>

I realize that I'm not limiting file types, but I'll worry about that once I can get a simple .jpg or .zip file uploaded. Using the above code, I go to the page on my local server located at

C:\wamp\www\simpleupload  (this contains index.php, the file posted above)

When I select a small image file and click submit, I'm presented with the following errors:

Warning: move_uploaded_file(/uploads/session_timeout_formatting_bug.png): failed to open stream: No such file or directory in C:\wamp\www\project_fileshare\index.php on line 18

and

Warning: move_uploaded_file(): Unable to move 'C:\wamp\tmp\phpEFDE.tmp' to '/uploads/session_timeout_formatting_bug.png' in C:\wamp\www\project_fileshare\index.php on line 18

Line 18 is the line that calls the move_uploaded_file() function.

How do I fix this error? I have an 'uploads_dir' folder located in the same folder as my index.php file. (reference the file path above). What am I doing wrong here? I must be misunderstanding some small part of this process and have put my directory in the wrong place, or I'm doing something wrong in the code.

Can someone spot my mistake and tell me what I need to do to fix it?


You are working on windows and you've told PHP a location that is inaccessible (i.e. /uploads linux path).

Since you are working in windows and your document root is C:\wamp\www\simpleupload

Which means, your files are located like this:

  • C:\wamp\www\simpleupload\index.php (your upload script)
  • C:\wamp\www\simpleupload\uploads (where the files should be uploaded)

Why don't you use absolute path like this:

$uploads_dir = getcwd() . DIRECTORY_SEPARATOR . 'uploads';

The getcwd() function will return the current working directory for the executing PHP script (in your case index.php), so the $uploads_dir will now look like this: C:\wamp\www\simpleupload\uploads

Try this.