Search code examples
phpfilefile-uploadmultipartform-datamultipart

File uploader uploading files but displaying error


My code

I've got this multipart form:

<form action="upload.php" method="post" enctype="multipart/form-data">
<label for="file"><span>Select:</span></label>
<input type="file" name="file" id="file"> 
<br>
Password: <input type="password" name="password"><br>
<input type="submit" name="submit" value="Upload">
</form>

Which points to this file:

<?php
$allowedExts = array("mp4", "avi","mpeg","wmv","swf","3gp","AVI");
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);

if (!in_array($extension, $allowedExts) || $_FILES['file']['error']>0  || file_exists(date("YmdHis").$_FILES["file"]["name"]))
{  
   echo "Error [code: ".$_FILES['file']['error']."]";
} else {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      date("YmdHis").$_FILES["file"]["name"]);
      echo 'file uploaded'; 
}
?>

What it should do

Uploading video files

What's not working

I've tried to upload an .AVI video of about 300kb: it was uploaded, but the error message "Error [code: ]" was shown

Result of error_reporting(E_ALL);

Notice: Undefined index: file in upload.php on line 5
Notice: Undefined index: file in upload.php on line 8

Result of var_dump($_POST,$_FILES); (with "password" field empty)

array(0) { } array(0) { } 

Result of "<pre>"; print_r($_FILES);

Array ( )

Where I tried the code

  • Local server run with easyPHP, php version 5.5.8
  • Shared server, php version 5.3.10

My question

How can I display the success message correctly and solve the problem?


Solution

  • I have run your code on PHP 5.3.18. windows XP. Assuming that upload limits are met. The only issue i can find is that you have missed a 'destination' directory from the 'target file name' when moving the files.

    Tested sample code:

    <?php // http://stackoverflow.com/questions/25115575/file-uploader-uploading-files-but-displaying-error?noredirect=1#comment39103445_25115575
    $destDir = 'P:/temp/';
    $allowedExts = array("mp4", "avi","mpeg","wmv","swf","3gp","avi");
    $extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
    
    if (!in_array($extension, $allowedExts) || $_FILES['file']['error']>0  || file_exists(date("YmdHis").$_FILES["file"]["name"]))
    {
       echo "Error [code: ".$_FILES['file']['error']."]";
    
    } else {
          $newFilename = $destDir . date("YmdHis").$_FILES["file"]["name"];
          move_uploaded_file($_FILES["file"]["tmp_name"],
          $newFilename);
          echo 'file uploaded : ', $newFilename;
    }