This code ain't working. HELP

by 6 replies
7
Hi,

I have a file upload php script but everytime I hit the upload button on my form, it says that the file I chose isn't allowed. I restricted some file types for security. Here's the code:

Code:
<?php
   
      $allowed_filetypes = array('.jpg','.gif','.bmp','.png','.jar');
      $max_filesize = 524288; 
      $upload_path = './files/'; 
 
   $filename = $_FILES['userfile']['name']; 
   $ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); 
 
   
   if(!in_array($ext,$allowed_filetypes))
      die('The file you attempted to upload is not allowed.');
 
   
   if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
      die('The file you attempted to upload is too large.');
 
   
   if(!is_writable($upload_path))
      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>'; 
      else
         echo 'There was an error during the file upload.  Please try again.'; 
 
?>
Please let me know if you got it to work.

Thanks,
Josh
#programming #code #working
  • I tried that code and it worked. What's the HTML that you're using?
  • Hi Josh

    As a test you could try remarking out the line that tests the file extension and see if it works.

    That would at least narrow down the area you are having trouble with.

    Bill
  • I'd do this for debugging:

    make sure the code is getting the extension correctly...



    that should show you what's going on with the file extension. My guess is something is going wrong with the file upload on the web server. You might also want to take a look at the filename.
  • I think there is a problem with the filetypes check. After removing it, the uploads work well. Hmmm, I'll try to code again.

    Thanks guys
    • [1] reply
    • did you check your permissions? They need to be set to 777
  • Did the filename of the file you tried to upload contain a dot like picture.cool.jpg?
    In that case $ext would contain "cool.jpg" and it therefore wouldn't match.

    This should fix the problem:

    Replace this line:

    $ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);

    with these lines:

    if (preg_match('/\.([^\.]+)$/', $filename, $m)) {
    $ext = $m[1];
    } else {
    $ext = '';
    }

    The problem is that your code searches for the first dot in the filename.

Next Topics on Trending Feed

  • 7

    Hi, I have a file upload php script but everytime I hit the upload button on my form, it says that the file I chose isn't allowed. I restricted some file types for security. Here's the code: