Prevent Duplicate File Upload to Database | andi setiawan's blog

Answering the question sent by vineet (view live here),

sir i am a new in php , if i am able to insert a file in database but the problem is that if i insert same file again then it insert. i want a code if i insert a same again it should not be inserted…
please help

That’s mean that Vineet want to keep the database size optimalized by preventing duplicate files inserted onto database (waste of storage). Actually you can do the same thing for files submitted to host storage. But, the more files uploaded, the more time you need to check and compare the files.

So here’s how we handle it:

in this case, you have to check wether the submitted file is exist in database or not. To do that we need to compare it.

You can compare it by the file name, or the size, but the best way to compare is by the md5 hash.

Here is a simple code to compare file:

<?

$filehash=md5($_FILES[file1]);
$dothis=mysql_query(‘select * from table’);
while($dothat=mysql_fetch_array($dothis)){
if(md5($dothat[insertedfiled])==$filehash){
//this mean that a same file exist in the table, you can put error message, or just do something ELSE .
//we put the checker here
$issame=1;
} // end if
} // end while

if($issame!=1){
// do the file insert, :-)

// example: see “Storing Images/Binary Files to mySQL in PHP
}

So, have a try!

But, i have one more algorithm for best practice! You do the scripting!

My algorithm:

you know, uploading to database will waste your database storage in which the size of database usually limited to couple MB’s. In my opinion, we have to upload the file in an usual way.

Upload your file (form) -> insert the file properties to database, put the files on the server (processing script)

so inside the processing script, you will check the file name, file type, md5 hash of the files, the size, maybe author, and of course the file path on the server for direct access (creating the link).

while before the file uploaded to the server, it has to pas the checker, quite similar to the code i wrote above.

when the file submitted, the script has to check the md5 hash of the submitted files, and compare it to all rows inside the database (md5 hash column). It will saves much more time than checking all the md5 hash of the files on the server.

Hope you understand my algorithm. 😀


Posted in programming, Tips n Trik |

2 thoughts on “Prevent Duplicate File Upload to Database

  1. Pingback: Otakbali

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: