php多张照片上传和重命名

标签 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() 方法重命名文件,我尝试过,但再次不起作用。

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

谢谢, 瓦克

最佳答案

根据您的解释,您根本不需要使用 $_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
}

关于php多张照片上传和重命名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25537173/

相关文章:

php - 如何使用该列上的输入字段更新该列

mysql - Laravel Eloquent 急切加载两个数据透视表

php - 如何使用 file_get_contents ('php://input' 获取文件信息 + 正文)?

php - 一种适合处理大量文件上传的技术

php - 删除网格中的行时出现奇怪的 JSON (Ext-JS 4)

javascript - 后循环中的 JQuery onclick 函数错误

php - 使用 Zend 时在数据库中存储加密电子邮件的最佳实践

php - 这个脚本容易受到 shell 命令绕过的攻击吗?

php - SQL 查询问题

php - 我的变量将在我的数组中得到空值