如何在php上传唯一命名的图像?

时间:2016-10-07 00:59:14

标签: php file-upload upload

您好我有以下代码。我正在尝试使用tempnam函数上传具有唯一名称的图片。

$upfile = tempnam('client_images', '');
unlink($upfile);
//move_uploaded_file($_FILES['userfile']['tmp_name'], $upfile);

if($_FILES["userfile"]["type"] != "image/gif" && $_FILES["userfile"]["type"] != "image/pjpeg" && $_FILES["userfile"]["type"] != "image/png" && $_FILES["userfile"]["type"] != "image/jpeg") 
{ 
    echo "ERROR: You may only upload .jpg or .gif or .png files"; 
} 
else 
{ 
     if(!move_uploaded_file($_FILES["userfile"]["tmp_name"],$upfile)) 
     { 
     echo "ERROR: Could Not Move File into Directory"; 
     } 
     else 
     { 
     echo "Temporary File Name: " .$_FILES["userfile"]["tmp_name"]."<br />"; 
     echo "File Name: " .$_FILES["userfile"]["name"]."<br />"; 
     echo "File Size: " .$_FILES["userfile"]["size"]."<br />"; 
     echo "File Type: " .$_FILES["userfile"]["type"]."<br />"; 
     } 
    } 
    ?>

但由于某种原因,我无法在client_images文件夹中看到这些图像。

输出如下:

Temporary File Name: C:\Windows\Temp\phpA9F3.tmp
File Name: client.png

为什么Temp将其保存为.tmp而不是.png? 我能做些什么呢?

1 个答案:

答案 0 :(得分:1)

替换

if(!move_uploaded_file($_FILES["userfile"]["tmp_name"], $upfile)) {
    //take care of error
}

使用

$nameyouwant = "sample"; //we'll use the extension from the source filename
$temp = explode(".", $_FILES["userfile"]["name"]);
$newfilename = $nameyouwant. '.' . end($temp); //add file extension
if(!move_uploaded_file($_FILES["userfile"]["tmp_name"],$upfile . $newfilename)) {
    //take care of error
}
else{
    //save success
}