What is the "conventional" way of handling uploaded image names? - php

So im making a website with an image upload functionality and im storing the image name to the database. I took a screenshot of my mac and wanted to upload this photo "Screen shot 2011-02-18 at 6.52.20 PM.png". Well, thats not a nice name to store in mysql! How do people ususally rename photos in such a way that each photo uploaded has a unique name? Also, how would i make sure i keep the file extension in the end when renaming the photo.

I would drop the extension, otherwise Apache (or equivalent) will run a1e99398da6cf1faa3f9a196382f1fadc7bb32fb7.php if requested (which may contain malicious PHP). I would also upload it to above the docroot.
If you need to to make the image accessible above the docroot, you can store a safe copy that is ran through image functions or serve it from some PHP with header('Content-Type: image/jpeg') for example and readfile() (not include because I can embed PHP in a GIF file).
Also, pathinfo($path, PATHINFO_EXTENSION) is the best way to get an extension.
Ensure you have stored a reference to this file with original filename and other meta data in a database.
function getUniqueName($originalFilename) {
return sha1(microtime() . $_SERVER['REMOTE_ADDR'] . $originalFilename);
}
The only way this can generate a duplicate is if one user with the same IP uploads the same filename more than once within a microsecond.
Alternatively, you could just use the basename($_FILES['upload']['tmp_name']) that PHP assigns when you upload an image. I would say it should be unique.

Hash the image name. Could be md5, sha1 or even a unix timestamp.
Here is an (untested) example with a random number (10 to 99)
<?php
function generate_unique_name($file_name)
{
$splitted = split(".", $file_name);
return time() . rand(10,99) . "." . $splitted[count($splitted)-1];
}
?>

You could use an image table like:
id: int
filename: varchar
hash: varchar
format: enum('jpeg', 'png')
The hash can be something like sha1_file($uploaded_file) and used to make sure duplicate images aren't uploaded. (So you could have multiple entries in the image table with the same hash, if you wanted.) The id is useful so you can have integer foreign key links back to the image table.
Next store the images in either:
/image/$id.$format
or
/image/$hash.$format
The second format via the hash would make sure you don't duplicate image data. If you are dealing with lots of images, you may want to do something like:
/image/a/b/c/abcdef12345.jpg
where you use multiple layers of folders to store the images. Many file systems get slowed down with too many files in a single directory.
Now you can link to those files directly, or set up a URL like:
/image/$id/$filename
For example:
/image/12347/foo.jpg
The foo.jpg comes from whatever the user uploaded. It is actually ignored because you look up via the id. However, it makes the image have a nice name if the person chooses to download it. (You may optionally validate that the image filename matches after you look up the id.)
The above path can be translated to image.php via Apache's MultiView or ModRewrite. Then you can readfile() or use X-SendFile (better performance, but not always available) to send the file to the user.
Note that if you don't have X-SendFile and don't want to process things through PHP, you could use a RewriteRule to convert /image/$hash/foo.jpg into /image/a/b/c/$hash.jpg.

Related

PHP - why should I use pathinfo when I can get it through $_File array

why should I use this code to get the name of the file?
$filename = pathinfo($_FILES['file']['name'], PATHINFO_FILENAME)
If I could also get the name through this code:
$filename = $_File['file']['name']
Thank you very much! I'm a beginner in PHP, so sorry if the question is too dumb :D
Because $_File['file']['name'] comes from the user end, and although ordinarily it is just the file name, an ill-intentioned user can actually set it to whatever he wants (example: full path name to overwrite files in the server) and you have to filter it just like every other user input to prevent an attack vector in your system.
Same is true for everything in $_FILE, don't trust the informed MIME type, don't save files without checking if the extension is safe (saving a .php file will be a disaster) etc.
For example, I've seen a system that would trust files of type equal to image/jpeg and other image types, and then saves it without checking the actual file extension. A forged request can inject a .php shell script to this website's upload folder and be used to take control.

How to avoid duplicate file upload but keep the uploader unaware of it?

First of all, I apologize if the question is not clear, I'm explaining it below.
For every file uploaded, I'm renaming the file and recording the hash values (using sha1_files function, please suggest if there are some better or faster hashing techniques for the file in php) in a separate DB table and checking the hash of every new file to avoid duplicate files.
In this manner, the one uploading a duplicate file will get an error msg and the file won't be uploaded.
My question is, is there any techniques or algorithm by which I can prevent duplicate file upload but the duplicate file uploader will be unaware of it and will find the file in his/her account with a different name than the one already present. However, users won't be able to upload banned files by any means.
Yes, you should use xxhash which is much faster than sha1.
According to their benchmarks:
The benchmark uses SMHasher speed test, compiled with Visual 2010 on a
Windows Seven 32-bits box. The reference system uses a Core 2 Duo
#3GHz
SHA1-32 is 0.28 GB/s fast, and xxHash is 5.4 GB/s.
The PHP library is only getting a string as input, so you should use the binary library, and have something like this in your PHP:
list($hash) = explode(" ", shell_exec("/path/to/xxHash/xxhsum " . escapeshellarg($filePath)));
echo $hash;
Installing xxhash:
$ wget https://codeload.github.com/Cyan4973/xxHash/tar.gz/v0.6.3 -O xx.tar.gz
$ tar xvzf xx.tar.gz
$ cd xxHash-0.6.3; make
Just add some extra logic in your code possibly using an extra table or extra fields in the existing table (it is up to you, there is more than one way to do it) that saves the file to an alternate location should you discover it is a duplicate rather than sending an error. Not sure, though, if what you are doing is a good idea from the UI design point of view, as you are doing something different with the user input in a way that the user will notice without telling the user why.
Use an example like this to generate your sha1 hash client side before upload.
Save all your uploaded files with their hash as the filename, or have a database table which contains the hash and your local filename for each file, also save file size and content type.
Before upload submit hash from client side to your server and check for hash in database. If its not present then commence file upload. If present then fake the upload client side or whatever you want to do so the user thinks they have uploaded their file.
Create a column in your users table for files uploaded. Store a serialised associative array in this column with hash => users_file_name as key=>value pairs. Unserialize and display to each user to maintain their own file names then use readfile to serve them the file with the correct name, selecting it server side using the hash
As for your URL question. Create a page for the downloads but include the user in the url as well, so mysite.com/image.php?user=NewBee&image=filename.jpg
Query the database for files uploaded by NewBee and unserialize the array. Then:
$upload = $_GET['image'];
foreach($array as $hash => $filename){
if($filename == $upload)
$file = $hash;
}
Seach database for the path to your copy of that file, then using readfile you can output the same file with whatever namme you want.
header("Content-Description: File Transfer");
header("Content-type: {$contenttype}");
header("Content-Disposition: attachment; filename=\"{$filename}\"");
header("Content-Length: " . filesize($file));
header('Pragma: public');
header("Expires: 0");
readfile($file);
You could create an extra table which links files uploaded (so entries in your table with file hashes) with useraccounts. This table can contain an individual file name for every file belonging to a specific user (so the same file can have a different name per user). With current technologies you could also think about creating the file hash in the browser via javascript and then upload the file only if there isn't already a file with that hash in your database if it is you can instead just link this user to the file.
Addition because of comment:
If you want the same file to be accessible through multiple urls you can use something like apache's mod_ rewrite. I'm no expert with that but you can look here for a first idea. You could update the .htaccess dynamically with your upload script.

How to make file_get_contents return an unique result

I am new to php and would like to ask you for some help returning an unique result from file_get_contents(). The reason is I want to give each photo an unique name, so that later it will be possible to delete just one of them and not all.
$file =addslashes(file_get_contents($_FILES['image']['tmp_name'][$key]));
Unfortunately time() and microtime() doesn't help in this situation.
Maybe this will help you: http://php.net/manual/en/function.uniqid.php
uniqid();
$imageName = $imageName . '_' . uniqid();
Why not just generate the SHA-1 of the content and use that as the file name (sort of like how git stores objects in a repository's loose object database)? I typically don't like to insert blobs into the RDBMS; it's a little clunky and you have to make sure the blob field has enough space for the kind of file sizes you're expecting to work with. Plus, the filesystem is optimized to handle, well, files. So it makes sense to keep a special directory on the server to which the Web server has write access. Then you write the files there and store references to them in the database. Here's an example:
// Read the contents of the file and create a SHA-1 hash signature.
$tmpPath = $_FILES['image']['tmp_name'];
$blob = file_get_contents($tmpPath);
$name = sha1($blob) . '.img'; // e.g. b99c6e26c3775fca9918ad614b7be7fe4fd7bee3.img
// Save the file to your server somewhere.
$dstPath = "/path/to/imgdb/$name";
move_uploaded_file($tmpPath,$dstPath);
// TODO: insert reference (i.e. $name) into database somehow...
And yes, researches have broken SHA-1, but you could easily write some safeguards against that if you're paranoid enough (e.g. check for an existing upload with the same hash; it the content differs, just mutate/append to the name a little to change it). You aren't identifying the image on the backend by its content: you just need a unique name. Once you have that, you just look it up from the DB to figure out the file path on disk corresponding to the actual image data.
If you expect the image files to be pretty large, you could limit how much you read into memory using the 4th parameter to file_get_contents().

Website upload prevent hacking

There's an upload form on my website. I'm actually not really including or excluding file types.
Instead I'm using this:
$fileUploadName = $target_dir.md5(uniqid($target_file.rand(),true)).".".$imageFileType;
That will keep the file type but change the file name to some random cryptic like 790cd5a974bf570ff6a303c3dc5be90f.
This way a hacker cannot upload a hack.php file and the open it with www.example.com/uploaded_files/hack.php because it has changed to e.g. 790cd5a974bf570ff6a303c3dc5be90f.php. In my view it's completely safe this way. Am I right that it's safe this way?
I think only a self-executing-file could be a problem. Do self-executing-files even exist?
You should also eighter check the mime type of the file uploaded and the extension (although that can easily be faked on upload).
If you expect only images, you could also check for image width and length parameters by executing a script like this:
$size = getimagesize($target_file);
If this does not return proper values, it's no image file.
You might want to inform yourself about dangerous graphics like Gifar too.
Put uploaded files in there own folder like /etc/web/uploads/<Random> (../uploads) while the website root is at /etc/web/public/ or if you can use .htaccess create one in the uploads folder and put Deny from all
Also uniqid and rand does not generate cryptographically secure values I would also check that the uploaded file is an image anyway Link to someones isimage function http://php.net/manual/en/function.uniqid.php http://php.net/manual/en/function.rand.php
Use file_get_contents to get the users image

How can i avoid same image name at the point of upload to filesystem

I have a form whereby Users upload pictures as part of their registration process. But my issue is that, users that save the names of their image with the same name might cause some issues when they view the profile pictures. How can i make the picture name unique at the point of uploading to the filesystem..
Thanks.
I would suggest using one of the following schemes:
make the filename a function of the username/userid
make the filename a random value
make the filename a function of the file content (e.g. an MD5 checksum)
If this helps
$t = uniqid();
$filename='user-'.$t;
echo $filename; // user-1335601088 (always a different name)

Categories