PHP move_uploaded_file更改存储文件的名称?

时间:2016-05-18 20:29:11

标签: php

我从here

获得了一些代码

虽然此代码有效,但它会将原始文件名上传到服务器。我有一个随机字符串生成器,我想用以下命名文件:

function generateRandomString($length = 10) {
    $characters =     '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
   return $randomString;
}

所以,

<?php 
session_start();

$picName = generateRandomString();
$_SESSION['picName'] = $picName;
?>

$ picName将被发送到数据库,我们将在upload2.php文件中使用$ _SESSION [&#39; picName&#39;]。

这是html:

<form method="post" action="upload2.php" enctype="multipart/form-data" > 
<input type="file" name="img" />
</form>

这是upload2.php:

<?php
session_start();

$picName = $_SESSION['picName'];
$target_path = "files/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);  


if(move_uploaded_file($_FILES['img']['tmp_name'], $target_path)) {
echo "The file has been uploaded";
} else{
echo "There was an error uploading the drivers licence picture, please try again!";
}
?>

所以问题是,在upload2.php中我需要设置新名称($ picname)来更改文件的最终名称吗?

3 个答案:

答案 0 :(得分:2)

见这一行,

if(move_uploaded_file($_FILES['img']['tmp_name'], $target_path)) {...

$target_path"files/" . basename( $_FILES['uploadedfile']['name']);

错误很少:

  • $_FILES['uploadedfile']['name']错了。您已将输入字段命名为img,因此它应为$_FILES['img']['name']
  • 查看您的$target_path,您正在使用相同的文件名上传文件。

要上传带有新文件名的文件,请执行以下操作:

$target_path = "files/";
$target_path = $target_path . $picName . "." . strtolower(pathinfo($_FILES['img']['name'], PATHINFO_EXTENSION));  

答案 1 :(得分:0)

您的$target_path变量只需要包含要用于文件的完整文件路径和名称。 SO代码非常简单:

$target_path = 'files/' . $whatever_random_string;

答案 2 :(得分:0)

我已经实现了这个示例并且工作正常。

获取原始图像的扩展名,并更改名称。

$ImageName = basename($_FILES["img"]["name"]);
$Last4 = substr($ImageName, -4);//Get only last 4 caracter of string.
$extention = str_replace("jpeg",".jpeg", $Last4);//We have jpg, jpeg, gif, png , so the only problem is jpeg so we replace jpeg for .jpeg :)

$picName = $_SESSION['picName'];
$target_path = "./files/";    

//Load image on server.
move_uploaded_file($_FILES["img"]["tmp_name"], $target_path . $picName . $extention);