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.
help with uploading files
Moderator: General Moderators
-
chris12295
- Forum Contributor
- Posts: 113
- Joined: Sun Jun 09, 2002 10:28 pm
- Location: USA
- Contact:
Here is a snippet of code taken from the PHP manual. It demonstrates how to upload files:
If you change the "/place/to/put/uploaded/file" string to include the new filename, you could achieve what you want. For instance:
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:
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
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'];
}
?>Code: Select all
$filename = mysql_insert_id();
$fullpath = "/place/to/put/uploaded/$filename"*******************************************************
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);Hope that helps
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
sort of thing to test for file extension.
Code: Select all
if (ereg('(.gif|.jpeg|.jpg)$', $file)) {
// if file is gif or jpeg
} else {
// if file isn't
}