Find out what files are in a directory that are "not" listed in the database
I have a small gallery website but the amount of images in directory differs from that accounted for in databa开发者_开发百科se by around 150 so I was wondering if there is a way to find out/list what files are in a directory that are "not" in the database (or vice versa).
basic db structure:
- images
- id
- images
image names are stored in db as "imagename.jpg"
and the images themselves are stored in images directory
images/
Put file names from server in one array and files from database in another. Use array_diff() to get result.
Example (PHP):
$files_db = array("car.jpg", "bike.jpg", "plane.jpg", "ship.jpg", "tank.jpg");
$files_server = array("car.jpg", "bike.jpg", "ship.jpg", "rocket.jpg");
Use
print_r(array_diff($files_db, $files_server));
Output
Array
(
[2] => plane.jpg
[4] => tank.jpg
)
Or (vice versa)
print_r(array_diff($files_server, $files_db));
Output
Array
(
[3] => rocket.jpg
)
If this is likely a one-off problem, I'd solve this with a half-assed solution, using first a little SQL script:
SELECT filename FROM images;
and ask the database client mysql
or psql
or whatever to dump the output as plain text to a file. (Shell redirection may do the job if you can't easily find your database client's 'dump to file' command.)
Then I'd get the directory listing:
ls /path/to/images/ > ls_files
Sort both:
sort db_files > db_files.sorted
sort ls_files > ls_files.sorted
Then run diff(1)
to see which files are referenced where:
diff -u ls_files.sorted db_files.sorted
Lines prefixed with a +
or -
are in one but not the other.
You might need edit the SQL output or the ls
output to get one to match the other. If your editor has a tool like vim
's ^V
block select, some of those editing tasks can be simplified, but sometimes just running ls
from another directory can help prepend the right directory structure in front of every filename.
精彩评论