Add rows to database based on images in folder
This follows on from a question I had earlier about cleaning up my database which you can see here: Remove row from database if image not on server
I have a mysql database with a table in the following format:
ID: 1
Date: 2010-12-19 Ima开发者_如何学Cge: 5d61240f-7aca-d34b-19-12-10-15-36.jpg Caption: Merry XmasI now want to create a php script which checks through my /gallery/ folder on my server and for every image in the gallery folder that isn't already listed in my database I want to create a new row with it's filename in the image column. The ID is sequential, the date needs to be the last modified date of the file using filetime() and needs to be in the YYYY-MM-DD format. The caption column can be blank for these files we're adding. Any help with a script to do this would be greatly appreciated.
Thanks!
// list of allowed image extensions
$image_exts=array('png','jpg','ico','gif','bmp'); // ...
// function to store image file to db
function db_add_image($image){
$name=mysql_real_escape_string(basename($image));
mysql_query("INSERT INTO `table` (`ID`,`Date`,`Image`,`Caption`)
VALUES (NULL,'".date('Y-m-d',filemtime($image))."','".$name."','')
WHERE NOT EXISTS (SELECT `ID` FROM `table` WHERE `Image`='".$name."')");
}
// loop in your folder (glob returns an array of files matching a wildcard)
foreach(glob('gallery/*.*') as $file)
// if the file is an image...
if(in_array(strtolower(pathinfo($file,PATHINFO_EXTENSION)),$image_exts))
// add image to database
db_add_image($file);
Secure, clean, commented and ready for shipping. That's $20 in all, please pay at the counter. :D
Edit: Thanks to the two guys below, +1 to both.
if (!empty($_FILES["photo_name"]["name"]) && file_exists($_FILES["photo_name"]["tmp_name"]))
// Image is empty
// photo_name is image box name
{
if (strtolower($_FILES["photo_name".$i]["type"])!="image/jpg" && strtolower($_FILES["photo_name".$i]["type"])!="image/pjpeg" && strtolower($_FILES["photo_name".$i]["type"])!="image/jpeg") //Image is not jpg or gif
{
$_MSG[] = " The Image Must be JPG/JPEG.";
$error = 1;
}
}
if (empty($error))
{
if (!empty($_FILES["photo_name"]["name"]) && file_exists($_FILES["photo_name"]["tmp_name"])) // Image is exist
{
if(!$_POST["hidImage"])
{
$original = rand(1,9).date("Hismdy").".jpg"; //Make file name as timestampe
$_POST["hidImage"]=$original;
}
else
$original = $_POST["hidImage"];
chmod($_DIR['inc']['regi_images'],0777);
//regi_images is folder name
$image = $_FILES["photo_name"]["tmp_name"];
$arr = getimagesize($image);
if($arr[0]>400)
{
setsize("400x400");
// Size Width x Height
resize($newwidth,$newheight,$_DIR['inc']['regi_images'].$original);
} else
copy($image,$_DIR['inc']['regi_images'].$original);
chmod($_DIR['inc']['regi_images'],0755);
} else
$original = $_POST["hidImage"];
}
精彩评论