0

嘿伙计们,我想知道如何在将文件上传到服务器文件夹之前专门重命名文件,以避免上传时文件名相同,并用它重写同名文件。我倾向于使用 school_id 作为图像的文件名。这是php代码

include_once('DBconnect.php');

session_start();
$school_id = $_SESSION['school_id'];


$name = $_FILES['file_path'] ['name'];
$size = $_FILES['file_path'] ['size'];
$type = $_FILES['file_path'] ['type'];

$extension = substr($name, strpos($name, '.')+1);

$max_size =3145728;

$temp_file = $_FILES['file_path'] ['tmp_name'];

if(isset($name)){

    if(!empty($name)){

        if(($extension == 'jpg' || $extension == 'jpeg') && ($type ==  'image/jpeg' || $type == 'image/jpg') && $size <= $max_size  ){



         if($school_id == 0){

            $location = 'uploads_images/super_admin/';





                                  move_uploaded_file($temp_file,$location.$name);

                     $insert_path = "INSERT INTO image_upload  (school_id,path_name) 
                                                     VALUES('$school_id','$name')";

                                $result2 = mysql_query($insert_path);
                                              if(@!$result2){
                                                    die('error header'.mysql_error());
                                                  }



                    echo "Success in uploading";


            }
            else{

                $location = 'uploads_images/schools/';




                                 move_uploaded_file($temp_file,$location.$name);

                     $insert_path = "INSERT INTO image_upload (school_id,path_name) 
                                        VALUES('$school_id','$name')";

                                        $result = mysql_query($insert_path);
                                          if(@!$result){
                                               die('error header'.mysql_error());
                                             }

                    echo "Success in uploading";





            }



        }
        else{

            echo "File type is too big or Incorrect file type";
        }


    }
    else{

            echo "Please Choose A JPEG File";
        }

}


?>
4

2 回答 2

1

不要信任客户端文件名。

您可以将新文件名传递给move_uploaded_file函数。我建议你做这样的事情:

$name=uniqid($school_id, true).$extension;
move_uploaded_file($temp_file,$location.$name);

uniqid内置php函数http://php.net/manual/en/function.uniqid.php

我希望这是有帮助的

于 2012-12-25T11:28:49.780 回答
0

您可以在移动之前使用 file_exists 确定是否存在潜在的命名冲突。 http://php.net/manual/en/function.file-exists.php

一种选择是将某种时间戳附加到文件名,以保证唯一性。

于 2012-12-25T11:21:00.977 回答