What I really want to do is check if the same file exists before or after uploading the file, is there a efficient way to do it?
Well, that's it!
Edit: Actually it doesn't matter if its after or before, as long as it can detect dups.
What I really want to do is check if the same file exists before or after uploading the file, is there a efficient way to do it?
Well, that's it!
Edit: Actually it doesn't matter if its after or before, as long as it can detect dups.
EDIT: Sorry didn't realize you said BEFORE... What you could do is use AJAX to query the server before the upload button is enabled.
Script:
function CreateRequest()
{
var xmlhttp = false;
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp=false;
}
}
if (!xmlhttp && window.createRequest) {
try {
xmlhttp = window.createRequest();
} catch (e) {
xmlhttp=false;
}
}
if(!xmlhttp)
{
alert("Could not create XmlHttpRequest. Browser does not support.");
}
return xmlhttp;
}
function validate()
{
xmlhttp = CreateRequest();
xmlhttp.open( "GET", "checkfile.php?file=" + document.getElementById('upload').value );
xmlhttp.send( false );
if( xmlhttp.responseText == "YES" )
alert( "File already exists" );
else
document.getElementById('go').disabled = false;
}
HTML:
<input id="upload" type="file" name="upload" onchange="validate()"/>
<input name="Reset" type="submit" disabled=disabled id="go" value="Go"/>
PHP:
$file = basename( $_GET['file'] );
if( file_exists( "uploads/$file" ) )
echo "YES";
else
echo "NO";
You cannot do that without using AJAX or flash, because PHP is responsible for the upload itself and your script starts at the point where the file has already been uploaded. I'll add the appropriate tags to your answer so someone can help you
You can't check before uploading the file.
Once it's uploaded you could compare the file sizes then the MD5s of the files to check if they are the same.
You only have few choice :
Pick the one you prefer !
Checking before uploading is, as others have pointed out before, not possible. But once the file is uploaded, you should compare the MD5 hash of the files.
Instead of calculating the MD5 hash of a file over and over again, you could consider keeping a little database in which you cache the results. That should be more performant.