du_1993 2014-08-27 21:24
浏览 26
已采纳

Php多张照片上传和重命名

My problem recently arose when I tried to change save a picture to a location with a different name. eg. saving a picture called hello.jpg to a location called /sets/1/09092014-1.jpg

Here is my code:

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{
}

not including the DB stuff at the top.

I spent a while on this, and found that i may need to use the rename() method to rename the file before i save it, which I tried, but once again it didnt work.

When run, it adds the info to the database, creates the folder to be put in if not present, but then does not add the files.

Thanks, Waq

  • 写回答

1条回答 默认 最新

  • duanliang8464 2014-08-27 22:34
    关注

    According to your explanation you should not need to use $_SERVER["DOCUMENTE_ROOT"] at all. You just need to pay attention to file structure and your code. Here is corrected code with comments:

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度