使用uniqid()上传时的唯一文件名

时间:2015-10-11 03:48:47

标签: php mysql file-upload gallery

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

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();

2 个答案:

答案 0 :(得分: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代码,你的代码很快就会完全停止运行。

快乐的编码!

答案 1 :(得分:0)

我假设您发布了工作代码,然后可能因为下面的行,

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

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

$file="images/".$new_image_name;

让我知道问题已解决。