【问题标题】:PHP upload (w3schools script) with custom name使用自定义名称的 PHP 上传(w3schools 脚本)
【发布时间】:2018-04-13 05:58:20
【问题描述】:

我使用 w3schools 的预制 php 上传脚本,但我不知道如何修改代码以使用唯一 id 而不是原始文件名上传文件。

上传.php

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["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["fileToUpload"]["size"] > 500000) {
    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["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

【问题讨论】:

    标签: php html upload


    【解决方案1】:

    这是一个示例,它还为您提供了文件名使用多少字符的灵活性。

    function generateRandomString($length = 10) {
      return substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 
                    ceil($length/strlen($x)) )),1,$length);
    }
    
    $org_filename=basename($_FILES["fileToUpload"]["name"]);   
    $ext = pathinfo($org_filename, PATHINFO_EXTENSION);
    
    $target_file = $target_dir . generateRandomString(20) . '.' . $ext ;
    

    【讨论】:

    • 我已经制作了 id 生成器,但你的意思是我只需要在目标文件末尾有 id 变量?
    【解决方案2】:

    要生成唯一的 id,您可以使用 php md5() 和 date() 函数。您可以在其中传递当前日期时间,以便对其进行加密并生成一个唯一的字符串。

    参考这个 - $target_file = $target_dir .md5(date('d-m-y h:i:s')). $ext;

    【讨论】:

      猜你喜欢
      • 2014-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-22
      • 2019-06-19
      • 2021-05-18
      • 2021-12-28
      • 1970-01-01
      相关资源
      最近更新 更多