使用uniqid函数更改文件名,然后回显

时间:2017-07-31 05:03:50

标签: php html image image-uploading

我如何在这个上传脚本中构建uniqid函数?

我的目标是将图片上传到服务器,并将图片重命名为随机字符,然后在图片上传后,将图片链接回显。

所以这就是我想象的方式: 上传image.png> script processes image.png并使用uniqid函数给它一个随机名称,如3ia8d3awd.png> 然后脚本回显新图像名称,并在图像上传到目录后将其链接到标记中。

这是脚本:

<?php
$target_dir = "..img/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = 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.";
    }
}
?>

我知道这个脚本是为了按原样拍摄图像名称并上传它们,但如果你能帮我修改一下。我认为这将是unqid功能,但我可能是错的。我还是PHP新手,花了两个小时试图弄清楚这个;谢谢。

编辑:被告知more_entropy函数将提供更多唯一名称。

3 个答案:

答案 0 :(得分:0)

在代码顶部试试这个:

$newFileName = uniqueid('',TRUE);
$_FILES["fileToUpload"]["name"] = $newFileName;

这应该为文件指定一个新的唯一名称。当然,我没有测试它是否会干扰文件扩展名,但让我知道它是如何工作的。

答案 1 :(得分:0)

这是修改过的脚本,只是插入了用户定义的函数来生成随机且最可能唯一的名称,有4个名称段,每个段长度为6个字符,您可以在函数uniqueName中自定义这些设置

<?php

function genName($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

function uniqueName()
{
   $temp = '';
   for($i = 0;$i<4;$i++) //number of random segments
      $temp .= '_'.genName(6); // length of each segment

  return $temp;
}

$_FILES["fileToUpload"]["name"] = uniqueName();

$target_dir = "..img/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = 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.";
    }
}
?>

答案 2 :(得分:0)

原始版本的经过修改和未经测试的版本,具有较小的实用程序功能,可帮助为上传的文件生成随机(并且希望是唯一的)名称。

<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_FILES ) ){
        /*
            generate a random name for new files
        */
        function createname( $prefix='',$name, $length=16 ){
            /* random chars with optional prefix & length */
            return $prefix.substr( sha1( $name . uniqid( $prefix, true ) . time() ), 0, $length );
        }

        try{
            /* Only permit these file extensions */
            $allowed=array('jpg','jpeg','png','gif');
            /* Do not allow files larger than this */
            $maxsize=500000;
            /* optional prefix to generated file name - can be '' */
            $prefix='img_';

            $target_dir = "..img/";

            /* Get reference to file as object for convenience */
            $file=(object)$_FILES['fileToUpload'];

            $name=$file->name;
            $size=$file->size;
            $tmp=$file->tmp_name;
            $type=$file->type;
            $error=$file->error;



            /* File extension */
            $ext=pathinfo( $name, PATHINFO_EXTENSION );
            $filename=pathinfo( $name, PATHINFO_FILENAME );

            /* target will be similar to "..img/img_a7119f62b2810c68.jpg" */
            $targetfile=createname( $prefix, $filename ) . '.' . $ext;
            $targetpath=$target_dir . $targetfile;

            if( $error==UPLOAD_ERR_OK && is_uploaded_file( $tmp ) ){

                /* Is the file an image? */
                list( $w, $h, $t, $a ) = getimagesize( $tmp );
                if( !$w or !$h ) throw new Exception('File is not an image');

                /* Correct file extension? */
                if( !in_array( $ext, $allowed ) ) throw new Exception('Incorrect file extension - only '.implode(', ',$allowed).' are permitted');


                /* Does file already exist ( unlikely if using unique random names ) */
                if( realpath( $targetpath ) ) throw nex Exception('File already exists');

                /* Is file too large? */
                if( $size > $maxsize )throw new Exception('File is too large');

                /* save the file */
                $status=move_uploaded_file( $tmp, $targetpath );
                echo $status ? "The file has been saved: <a href='$targetpath' target='_blank'>{$targetfile}</a>" : "Sorry - there was a problem saving the file. Check permissions on folder.";


            } else {
                throw new Exception('upload failed');
            }
        }catch( Exception $e ){
            exit( $e->getMessage() );
        }
    }
?>