Php多张照片上传和重命名

时间:2014-08-27 21:24:15

标签: php mysql file-upload

当我尝试将图片保存到具有不同名称的位置时,我的问题最近出现了。例如。将名为hello.jpg的图片保存到名为/sets/1/09092014-1.jpg

的位置

这是我的代码:

if(isset($_FILES['files'])){
$errors= array();
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['files']['name'][$key];
$file_size =$_FILES['files']['size'][$key];
$file_tmp =$_FILES['files']['tmp_name'][$key];
$file_type=$_FILES['files']['type'][$key];
$today = date("dmY");
$Title =  $today."-".$x.".jpg";
$x ++;
$url = "/Sets/".$desired_dir."/".$Title;

$query = "INSERT INTO photo(name, url, album) VALUES('$Title', '$url', '$set')";
$result = mysql_query($query) OR DIE(mysql_error());


if($file_size > 10485760){
$errors[]='File size must be less than 2 MB';
}
if(empty($errors)==true){
if(is_dir("Sets/"."$desired_dir")==false){
mkdir("Sets/"."$desired_dir", 0700);
}
if(is_dir("Sets/"."$desired_dir/".$Title)==false){
rename ($file_tmp ,  $Title );
move_uploaded_file($file_tmp, "/Sets/$desired_dir/$file_tmp");
}else{
}

不包括顶部的数据库内容。

我花了一些时间在这上面,发现我可能需要使用rename()方法重命名文件,然后保存它,我试过了,但是再一次它没有用。

运行时,它会将信息添加到数据库,如果不存在则创建要放入的文件夹,但不添加文件。

谢谢, WAQ

1 个答案:

答案 0 :(得分:1)

根据您的解释,您根本不需要使用$ _SERVER [“DOCUMENTE_ROOT”]。您只需要注意文件结构和代码。以下是带有注释的更正代码:

if(empty($errors)==true){
// $desired_dir didn't need parenthesis, buts its ok to use them
// Remember directories and file names are case sensitive: Sets is != to sets
if(is_dir("Sets/".$desired_dir)==false){
// If your server is picky you can try 0755 here and change it lower later
mkdir("Sets/".$desired_dir, 0700);
}
// ERROR your if test is supplying a file but you were testing for directory
// $Title is a file not a directory
if(is_file("Sets/".$desired_dir."/".$Title)==false){
rename ($file_tmp,$Title);
// You just renamed $file_tmp so change the blow code to use the right file
// Because of the rename $file_tmp no longer exists
move_uploaded_file($Title,"Sets/$desired_dir/$Title");
}else{
// It already exists, handle it
}