Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/91.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用uniqid函数更改文件名,然后返回_Php_Html_Image_Image Uploading - Fatal编程技术网

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

Php 使用uniqid函数更改文件名,然后返回,php,html,image,image-uploading,Php,Html,Image,Image Uploading,如何将uniqid函数构建到这个上传脚本中 我的目标是将一个图像上传到服务器,并将图像重命名为随机字符,然后在上传后将图像的链接回显 下面是我对它的描述: 上传image.png> 脚本处理image.png并使用uniqid函数为其指定一个随机名称,如3ia8d3awd.png> 然后脚本回显新图像名称,并在图像上传到目录后将其链接到标记中 以下是脚本: <?php $target_dir = "..img/"; $target_file = $target_dir . basename

如何将uniqid函数构建到这个上传脚本中

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

下面是我对它的描述: 上传image.png> 脚本处理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.";
    }
}
?>

我知道这个脚本是要采取的图像名称是,并上传他们,但如果你能帮我修改这个。我想这应该是uniqid函数,但我可能错了。我还是PHP新手,花了整整两个小时试图弄明白这一点;多谢各位


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

在代码顶部尝试以下操作:

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

这将为文件分配一个新的唯一名称。当然,我没有测试它是否会干扰文件扩展名,但请告诉我它是如何工作的。

这是修改后的脚本,只需插入用户定义的函数,即可生成一个随机且最可能唯一的名称。名称有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.";
    }
}
?>

原版的修改版和未经测试的版本,它有一个小的实用功能,可以帮助为上传的文件生成随机(希望是唯一的)名称

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


“警告此函数不保证返回值的唯一性。由于大多数系统通过NTP或类似方式调整系统时钟,系统时间会不断变化。因此,此函数可能不会返回进程/线程的唯一ID。请使用更多的熵来增加唯一性的可能性。”-最好使用UUID.PHP致命错误:未捕获错误:调用第3行目录中未定义的函数unique_id()。这是顶部编辑的部分,我想我做对了:对不起,我的意思是
uniqueid()
不是
unique\id()
。答案已被编辑。相同错误:PHP致命错误:未捕获错误:调用第3行目录中未定义的函数uniqueid()。我尝试了uniqid(),但我的文件大小检查出现了另一个错误,但当它在未定义的文件大小上失败时,它没有创建崩溃日志。请在没有内部内容的情况下尝试。只要
uniqueid()
而不是
uniqueid(“”,TRUE)
看看这是否有帮助。不过这不要紧。尝试了
uniqueid()
而不是
uniqueid(“”,TRUE)
并得到了对未定义函数uniqueid()的相同调用。