Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php check if file exist

Tags:

php

can someone guide me on how to do checking to tell if file already exist in database or not before we upload it?

i wanna upload a file into database, but before it save, i want to check whther file already exist first. if yes then dont do the insert execution.

i used this reference on uplaoding a files.

thank you very much.

like image 380
user147685 Avatar asked Nov 29 '22 19:11

user147685


2 Answers

I'm not sure if this is what you're asking, but have you used PHP's built in function, file_exists(ABSOLUTE-PATH-TO-FILE)?

$exists = file_exists('myfile.doc');
if(!$exists) {
// do your processing
}

http://php.net/manual/en/function.file-exists.php

If you're checking the database, then just query whatever column might hold your file, for example:

SELECT * FROM my-table WHERE my-column = 'my-uploaded-file-name';
like image 151
jbnunn Avatar answered Dec 06 '22 16:12

jbnunn


Judging from the article you linked to, a file is considered as "uploaded to the database" when this query has been executed :

$query = "INSERT INTO upload (name, size, type, content ) ".
"VALUES ('$fileName', '$fileSize', '$fileType', '$content')";

Which means a way to check if a file "has been uploaded to the database" would be to check, when a file is being uploaded, if there is already an entry in the DB with the same name, file, type, and content that the current one.

I suppose such an entry could be fetched using a query like this one :

select *
from upload
where name = '$fileName'
    and size = '$fileSize'
    and type = '$fileType'
    and content = '$content'

If that query returns a result, your file probably already is "in the database".


BTW : To avoid checking the content of the whole file, a solution might be to add a new column to your upload table, to store some kind of hash of the file (see md5 and/or sha1 for instance).


BTW 2 : you should read a bit about SQL Injections, before using the code presented in this article without really understanding it : the following portion of code, copy/pasted from the "code for downloading files" section, is quite frightening, for instance :

$id    = $_GET['id'];
$query = "SELECT name, type, size, content " .
         "FROM upload WHERE id = '$id'";
like image 23
Pascal MARTIN Avatar answered Dec 06 '22 16:12

Pascal MARTIN