Page 1 of 1

PHP Upload.....File types....

Posted: Thu Aug 13, 2009 5:49 am
by gibry21
Hi people,

First of all I am very new to php and this forum so excuse my stupidy if this is simple.

I found a tutorial for a simple PHP uploader, my site needs peopl to upload, jpeg, gif, doc, pdf and maybe even eps.

I found a tutorial and got this working....from a security aspect I'm not sure its great but its not running on my server and it works on my shared hosting so I hoping its ok.

My problem is the script I got only shows how to upload jpeg's of a certain size, I need to simple know how to edit the php to add the above file types and increase the size.

Changing the error messages etc I think I can work out for myself.

Here is the upload.php:

Code: Select all

 
<?php
//?heck that we have a file
if((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) {
  //Check if the file is JPEG image and it's size is less than 350Kb
  $filename = basename($_FILES['uploaded_file']['name']);
  $ext = substr($filename, strrpos($filename, '.') + 1);
  if (($ext == "jpg") && ($_FILES["uploaded_file"]["type"] == "image/jpeg") && 
    ($_FILES["uploaded_file"]["size"] < 10000000)) {
    //Determine the path to which we want to save this file
      $newname = dirname(__FILE__).'/file_store/'.$filename;
      //Check if the file with the same name is already exists on the server
      if (!file_exists($newname)) {
        //Attempt to move the uploaded file to it's new place
        if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname))) {
           echo "It's done! The file has been saved as: ".$newname;
        } else {
           echo "Error: A problem occurred during file upload!";
        }
      } else {
         echo "Error: File ".$_FILES["uploaded_file"]["name"]." already exists";
      }
  } else {
     echo "Error: Only .jpg images under 350Kb are accepted for upload";
  }
} else {
 echo "Error: No file uploaded";
}
?>
 
Probably no relevant but here is the seperate form code:

Code: Select all

 
 <form enctype="multipart/form-data" action="upload.php" method="post">
    <input type="hidden" name="MAX_FILE_SIZE" value="10000000" />
    Choose a file to upload: <input name="uploaded_file" type="file" style="width:360px; "   />
    <input type="submit" value="Upload" />
  </form>
 
Thanks in advance.

Ryan

Re: PHP Upload.....File types....

Posted: Thu Aug 13, 2009 9:43 am
by neuroxik
Didn't test it, I just wrote, try it out (although it should work)

Replace with this: (I re-indented for my ease to edit)

Code: Select all

<?php
// set what you want
$ftypes = array(
    'jpg' => 'image/jpeg', // add or delete lines here according to file extensions you want
    'png' => 'image/png',
    'gif' => 'image/gif',
    'doc' => 'application/msword',
    'pdf' => 'application/pdf',
    'eps' => 'application/postscript',
);
$fsize_limit = '10485760'; // that would be 10 MB's, change to what you want
 
//?heck that we have a file
if((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) {
    //Check if the file is JPEG image and it's size is less than 350Kb
    $filename = basename($_FILES['uploaded_file']['name']);
    $ext = substr($filename, strrpos($filename, '.') + 1);
 
    if ($_FILES["uploaded_file"]["size"] < $fsize_limit) {
        if(array_key_exists($ext,$ftypes) && $ftypes[$ext] == $_FILES["uploaded_file"]["type"]) {
            //Determine the path to which we want to save this file
            $newname = dirname(__FILE__).'/file_store/'.$filename;
            //Check if the file with the same name is already exists on the server
            if (!file_exists($newname)) {
                //Attempt to move the uploaded file to it's new place
                if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname))) {
                    echo "It's done! The file has been saved as: ".$newname;
                } 
                else {
                    echo "Error: A problem occurred during file upload!";
                }
            } 
            else {
                echo "Error: File ".$_FILES["uploaded_file"]["name"]." already exists";
            }
        }
        else {
            echo "Error: You can only upload files with the following extensions: ";
            $i = 1; 
            $ext_str = '';
            foreach($ftypes as $k => $v) {
                // I'm not using implode because we don't want the values but the keys
                if($i>1) $ext_str .= ", ";
                $ext_str .= $k;
                $i++;
            }
            echo $ext_str.".";
        }
    } 
    else {
        echo "Error: Your file size must not exceed ".(($fsize_limit / 1024) / 1024)." MB's";
    }
} 
else {
    echo "Error: No file uploaded";
}
?>
Because we're no longer only checking jpg's, I didn't want to unnecessarily loop the filesize check, so I added an if/else for filesizenear the top that you can change. Also change it to the same thing in you form on the other page, where you have the input MAX_FILE_SIZE.

What I basically did is do an associative array so that it's easier to edit, and we can loop through that for giving the user the filetypes allowed on error, and to have an easy check by using array_key_exists(). The security is exactly the same, I just rewrote some parts to be more flexible.

UPDATE: I just re-skimmed the code quickly and you (just an advice) shouldn't give out an error such as: "File already exists". If you specifically want to see if the file is duplicate, you cannot rely on the filename itself, but would have to do something like compare an md5 of both. Here's why: suppose I upload a pic named "0001.jpg" or "me.jpg", then people will fall on that error if they upload a file named the same. Or maybe it's a doc named "curriculum.doc" or whatever common thing. Users don't like to have to get errors, then have to change the name of the file, etc, it shouldn't be done clientside. You could (if file already exists) append some unique string, say a timestamp or whatever, and just tell your user: Your file has been renamed to "me_6544123.jpg" or whatever. Also, saying a file already exists raises some security issues. Say the user uploads a file named: "emails.doc" (or anything more private people wouldn't want to be accessed by otehr people), and he gets a message saying it already exists, the person might want to look into that already existing file. That, considering the site might not be 100% secure... avoid anything embarassing is what I mean.

Re: PHP Upload.....File types....

Posted: Fri Aug 14, 2009 3:47 am
by gibry21
Hey,

Thanks for having a look at my problem....

I am getting a parse error now on your script:

Parse error: syntax error, unexpected T_DNUMBER in /home/prm09/public_html/download/reliance/upload.php on line 7

Something to do with the .doc file type?

ANy ideas?

Thanks in advance,
Ryan

Re: PHP Upload.....File types....

Posted: Fri Aug 14, 2009 4:33 am
by gibry21
Hi again,

Sorry, I figured it out ....I copied and pasted your code wrongly because I am stupid! ha, ha.

Thanks again for you help.

Don't mean to be a pain but I am wondering if you know how to add multiple uploads? So, say I wanted 5 upload forms/browse buttons, with a combined totally size of no more than say 70meg , then they all upload at once with the upload button?

Thanks in advance.

Ryan

Re: PHP Upload.....File types....

Posted: Fri Aug 14, 2009 8:11 am
by neuroxik
I'm happy it helped out.

I don't wanna sound like a pain either, but maybe I'll pass this on to someone else, maybe create a new thread for it since now it's no longer a filetype issue?

But anyway, here's basically how you'd do it:

Add more input on your first page, each baring a different name. You can add brackets so that they'll incremetally add up into an array (well, not the files themselves but they'll each have their array key), like this: "uploaded_file[]" .

You'd also have to loop the filetype checks as to see if all files are the correct format, do not exceed limit, etc (You can loop all files using foreach() )