【问题标题】:Unique file name when uploading using uniqid()使用 uniqid() 上传时的唯一文件名
【发布时间】:2016-01-08 18:18:50
【问题描述】:

我正在尝试从手机上传图像并将其显示在图库页面上。我需要每个文件名都是唯一的,否则图像会覆盖自己。我有以下代码,其中 $new_image_name 是从 this topic 建议的,但我似乎无法让它工作:

if ($_FILES["image"]["error"] > 0) {

    //Bad Output for form results red text
    echo "<font size = '5'><font color=\"#e31919\">Error: NO CHOSEN FILE <br />";
    echo"<p><font size = '5'><font color=\"#e31919\">INSERT TO DATABASE FAILED";

} else {
    $new_image_name = 'image_' . date('Y-m-d-H-i-s') . '_' . uniqid() . '.jpg';
    move_uploaded_file($_FILES["image"]["tmp_name"],"images/".$new_image_name);
    $file="images/".$new_image_name);
    $image_title = addslashes($_REQUEST['image_title']);
    $sql="INSERT INTO images (name, image, description) VALUES ('','$file','$image_title')";
    if (!mysql_query($sql)) {
        die('Error: ' . mysql_error());
    }

    //Good Output for form results green text   
    echo '
     <form enctype="multipart/form-data" action="insert_image.php" method="post" name="changer">
        <div style="padding:10px;">
            <h2 style="font-size: 28px;">Success!</h2>
            <p style="font-size: 18px;">Your file has been successfully uploaded!</p>
        </div>     
    </form>';
}
mysql_close();

这是我在添加 uniqid() 之前的代码,除了图像相互覆盖之外,它运行良好

    } else {

    move_uploaded_file($_FILES["image"]["tmp_name"],"images/" . $_FILES["image"]["name"]);
    $file="images/".$_FILES["image"]["name"];
    $image_title = addslashes($_REQUEST['image_title']);
    $sql="INSERT INTO images (name, image, description) VALUES ('','$file','$image_title')";
    if (!mysql_query($sql)) {
        die('Error: ' . mysql_error());
    }

    //Good Output for form results green text   
    echo '
     <form enctype="multipart/form-data" action="insert_image.php" method="post" name="changer">
        <div style="padding:10px;">
            <h2 style="font-size: 28px;">Success!</h2>
            <p style="font-size: 18px;">Your file has been successfully uploaded!</p>
        </div>     
    </form>';
}
mysql_close();

【问题讨论】:

  • 你遇到了什么错误?
  • 我只是得到一个空白屏幕。根本没有消息。
  • 我这样做了 - 我在文档的最开头添加了 error_reporting(E_ALL); ini_set('display_errors', 'On');,但在页面加载时仍然不显示任何内容。

标签: php mysql file-upload gallery


【解决方案1】:

您应该真正养成使用错误检查的习惯。由于您的代码现在存在,我可以上传 ANYTHING,您的代码会将其保存为 jpg 图像。

首先检查用户是否选择了要上传的文件。

然后将文件类型与预先确定的允许文件类型列表进行比较。

然后将其保存为上传的文件类型。 可能并不总是 jpg。由于您的代码现在就在,如果我上传gifpng 文件...它将保存为jpg。从而使图像无用,因为它不是jpg

带有错误检查的上传过程...

<?php
$FormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $FormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if(isset($_POST["upload"]) && $_POST["upload"] == 'changer') {

// set some basic variables
$fileName = $_FILES["image"]["name"]; // The file name
$fileTempLoc = $_FILES["image"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["image"]["type"]; // The type of file it is
$fileSize = $_FILES["image"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["image"]["error"]; // 0 for false... and 1 for true
$type = strtolower(substr(strrchr($fileName,"."),1));
if($type == 'jpeg' || $type == 'jpe') { $type = 'jprg'; } // make a jpeg or jpe file a jpg file

if (!$fileTempLoc) { // if no file selected
    die ('<div align="center" style="color:#ff0000;"><br /><h3>ERROR: Please select an image before clicking the upload button.<br /><br /><a href="javascript:history.go(-1);">Try again</a></h3></div>');
} else {

// This is the allowed list (images only)
$acceptable = array(
        'image/jpeg',
        'image/jpg',
        'image/jpe',
        'image/gif',
        'image/png'
);

// check to see if the file being uploaded is in our allowed list
if(!in_array($_FILES['image']['type'], $acceptable) && !empty($_FILES["image"]["type"])) { // Is file type in the allowed list
        die ('<div align="center" style="color:#ff0000;"><br /><h3>Invalid file type. Only JPEG, JPG, JPE, GIF and PNG types are allowed.<br /><br /><a href="javascript:history.go(-1);">Try again</a></h3></div>');

} else {

if ($_FILES["image"]["error"] > 0) {

    //Bad Output for form results red text
    echo "<font size = '5'><font color=\"#e31919\">Error: NO CHOSEN FILE <br />";
    echo"<p><font size = '5'><font color=\"#e31919\">INSERT TO DATABASE FAILED";

} else {
    $new_image_name = 'image_' . date('Y-m-d-H-i-s') . '_' . uniqid() . '.'.$type;
    move_uploaded_file($_FILES["image"]["tmp_name"],"images/".$new_image_name);
    $file="images/".$new_image_name;
    $image_title = addslashes($_REQUEST['image_title']);
    $sql="INSERT INTO images (name, image, description) VALUES ('','$file','$image_title')";
    if (!mysql_query($sql)) {
        die('Error: ' . mysql_error());
    }

    //Good Output for form results green text   
    echo '
        <div style="padding:10px;">
        <h2 style="font-size: 28px;">Success!</h2>
        <p style="font-size: 18px;">Your file has been successfully uploaded!</p>
        </div>';
mysql_close();
} // end if no errors
} // end if in allowed list
} // end if no file selected
} // end if form submitted
?>

表格...

<form enctype="multipart/form-data" action="<?php echo $FormAction ?>" method="post" name="changer">
<input type="file" name="image" id="image" />
<input name="submit" type="submit" value="Upload">
<input type="hidden" name="upload" id="upload" value="changer" />
</form>

最后一点...帮自己一个忙,停止使用mysql。开始改用pdo_mysql。 mysql 在 PHP 5.5 中已被弃用,并在 PHP 7 中完全删除。如果您使用的是 mysql 代码,您的代码将很快完全停止运行。

【讨论】:

    【解决方案2】:

    我假设您发布的工作代码,那么可能是因为下面的行,

    $file="images/".$new_image_name);
    

    您添加了额外的 ')' 删除该行,它可能工作正常。

    $file="images/".$new_image_name;
    

    让我知道问题已解决。

    【讨论】:

    • 很遗憾没有。我用添加 uniqid() 之前的代码更新了我的问题,除了图像相互覆盖之外,它工作得很好。
    猜你喜欢
    • 2012-01-23
    • 2016-08-28
    • 1970-01-01
    • 2013-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-21
    相关资源
    最近更新 更多