【问题标题】:how to change name of uploaded file in php in the script below如何在下面的脚本中更改 php 中上传文件的名称
【发布时间】:2018-04-17 08:17:55
【问题描述】:

我从 w3schools 复制了 php 上传脚本,并做了一些更改以更改文件名。

我唯一能做的就是在文件名的第一个添加一个随机名称,但我需要从上传的文件中删除它的原始名称。

例如我有一个名为“abc.jpg”的文件

上传此文件后,我可以将其更改为随机名称+原始名称,例如“2716c3f3e9d6dd0a2b89f047b938750520aaa.jpg”

如何在此代码中删除上传文件名末尾的原始名称“aaa”?

$rand = md5(md5(time()).md5(microtime())).rand(10,25);
$target_dir = "images/futsal/";
$file = $rand . basename($_FILES['fileperson']["name"]);
$target_file = $target_dir . $rand . basename($_FILES['fileperson']["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
    $check = getimagesize($_FILES['fileperson']["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES['fileperson']["size"] > 50000000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES['fileperson']["tmp_name"], $target_file)) {
        echo "file ". $file . " uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}

【问题讨论】:

    标签: php file-upload upload


    【解决方案1】:

    替换这一行:

    $target_file = $target_dir . $rand . basename($_FILES['fileperson']["name"]);
    

    以下内容:

    $extension = preg_replace('/.+?(\.[^.]+)$/', '$1', $_FILES['fileperson']['name']);
    $extension = $extension ? $extension : '.unknown';
    $target_file = $target_dir . $rand . $extension;
    

    【讨论】:

      【解决方案2】:

      您正在将上传的文件名添加到 $target_file 变量的末尾。

      更新代码以删除$target_file 中的$_FILES['fileperson']["name"]

      $rand = md5(md5(time()).md5(microtime())).rand(10,25);
      $target_dir = "images/futsal/";
      $imageFileType = pathinfo($_FILES['fileperson']["name"],PATHINFO_EXTENSION);
      $file = $rand . $imageFileType;
      $target_file = $target_dir . $file;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-12-25
        • 2011-09-18
        • 2013-02-14
        • 1970-01-01
        • 1970-01-01
        • 2011-08-09
        • 2011-08-31
        • 2015-01-09
        相关资源
        最近更新 更多