Uploading a file and saving filename in MySQL database

时间:2017-07-12 08:13:07

标签: php mysql file pdo save

I am currently uploading a set of files via the web browser to a PHP script. The PHP script will then save the files to a local directory and store the filename in the database using PDO. I am able to do both successfully. However, I am worried about the potential of one of these processes failing and the other one succeeding.

Depending which of these two operations I do first, I end up in a bad situation:

Method 1:

I first create the database entry. It is successful. I then proceed with attempting to save the file, but the file fails to save. In this scenario I end up with a broken link.

Proposed solution: On failure to save I issue a second command to delete the database entry and hope it works.

Method 2:

I first save the file. It is successful. I then proceed with attempting to create a database entry for it, but the entry fails. In this scenario I end up with orphan files on my system that the database knows nothing about.

Proposed solution: On failure to write to the database, I issue a command to unlink the file and hope it works.

Am I on the right track with either of these options? Would one of these two methods be less error-prone or more efficient than the other? Is there another way to go about this that I have not thought of?

1 个答案:

答案 0 :(得分:0)

Out ot curiosity, why would it fail?

However, the second method is safer: It is way simplier and faster to unlink a file you already know than to make a database request to delete the filename from it. So the scenario would go like this (in pseudo PHP)

$file = 'path/to/file.pdf';
$destination = '/path/to/upload/dir';

if(move_uploaded_file($file, $destination) {
    echo 'Success';
} 
else {
    unlink($file);
}

As you can see, this is pretty straight forward, I hope this helps