Page 1 of 1

help with uploading files

Posted: Mon Jun 17, 2002 12:05 pm
by chris12295
I need to let a user choose a picture from his/her hard drive and upload it to a folder on my computer; i need to be able to reaname the file to mysql_insert_id() so it is a different name every time but i dont know how to save the file to my folder or rename it without losing the ext. (.gif, .jpg).

How can i do all this and if you could, how can i only allow jpg's and gif's to be uploaded? if you dont understand what im sayong but think u can help, PLEASE email me at chris12295@aol.com.

Posted: Mon Jun 17, 2002 2:37 pm
by Zmodem
Here is a snippet of code taken from the PHP manual. It demonstrates how to upload files:

Code: Select all

if (is_uploaded_file($HTTP_POST_FILESї'userfile']ї'tmp_name']))
{
   copy($HTTP_POST_FILESї'userfile']ї'tmp_name'], "/place/to/put/uploaded/file");
}
else
{
   echo "Possible file upload attack. Filename: " . $HTTP_POST_FILESї'userfile']ї'name'];
}
?>
If you change the "/place/to/put/uploaded/file" string to include the new filename, you could achieve what you want. For instance:

Code: Select all

$filename = mysql_insert_id();
$fullpath = "/place/to/put/uploaded/$filename"
Basically, when you copy a file from one place to another, you can rename it at the same time.
*******************************************************

To get the extension of the file that was just uploaded, you could do this:

Code: Select all

$file_length = strlen($filename);
$ext = substr($filename, $file_length, -3);
In a nutshell, this code will start at the end of the filename string, and count backwards 3 chars. $ext will now equal whatever the extension was.

Hope that helps

Posted: Mon Jun 17, 2002 3:41 pm
by e+
Not meaning to rain on anyone’s parade but there is also the .jpeg extension that would be missed by this method. You might want to do a check of the last three or four letters and try to match them against the file types you will allow (you might not want to clutter your file space with bmp or have people upload malicious bits of code). You could either use the same bit of code that zmodem suggested or if you are feeling risky you could play with a

Code: Select all

if (ereg('(.gif|.jpeg|.jpg)$', $file)) {
     // if file is gif or jpeg 
} else {
    // if file isn't
}
sort of thing to test for file extension.