如何随机上传图片的名称

时间:2018-10-21 18:40:06

标签: sql image

if( isset($_POST["Headline"]) && isset( $_POST["Summary"]) && isset( $_POST["Description"])&& isset( $_POST["submit"]) )  {
    $Headline = $_POST['Headline'];

    $Summary = $_POST['Summary'];
    $Description= $_POST['Description'];

    $image_file = $_FILES["txt_file"]["name"];
    $type  = $_FILES["txt_file"]["type"]; //file name "txt_file" 
    $size  = $_FILES["txt_file"]["size"];
    $temp  = $_FILES["txt_file"]["tmp_name"];

    $path="Images/".$image_file; //set upload folder path

    if(empty($Headline )) {
            echo '<script language="javascript">';
            echo 'alert("Please Enter a Headline")';
            echo '</script>';
    }
    else if(empty($Summary)) {
            echo '<script language="javascript">';
            echo 'alert("Please Enter a Summary")';
            echo '</script>';
    }
    else if(empty($Description)) {
            echo '<script language="javascript">';
            echo 'alert("Please Enter a Description")';
            echo '</script>';
    }        
    else if(empty($image_file)) {
            echo '<script language="javascript">';
            echo 'alert("Please upload an image")';
            echo '</script>';
    }
    else if ($type=="image/jpg" || $type=='image/jpeg' || $type=='image/png' || $type=='image/gif') {
             if(!file_exists($path)) //check file not exist in your upload folder path
                   {
                    move_uploaded_file($temp, "Images/" .$image_file);
                 in here is where the image gets sent to the folder but how do i make it so it is randomized    

                    $query = $con-> prepare("
        INSERT INTO News ( Headline, Summary,Description, Image,Date)
        VALUES ( :Headline, :Summary,:Description, '".$_FILES['txt_file']['name']."'  , NOW() )

        ");

    $success = $query-> execute ([
            'Headline' => $Headline,
            'Description' => $Description,
            'Summary' => $Summary,
        ]);
}

我希望图像的名称每次都可以不同,因此当用户上传具有相同名称的图像时,不会覆盖已经存在的图像

2 个答案:

答案 0 :(得分:0)

GUID生成器呢?对于MS SQL,它将为select cast(newId() as nvarchar(128))

答案 1 :(得分:0)

在PHP上,您可以使用此功能。

mt_rand

com_create_guid

<?php

function GUID()
{
    if (function_exists('com_create_guid') === true)
    {
        return trim(com_create_guid(), '{}');
    }

    return sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535));
}

echo 'Image name: ' . GUID();
?>