简体   繁体   English

如何在php中重命名上传的图像

[英]how to rename uploaded image in php

I got this code from w3schools, and tweaked it based on this one: Rename an uploaded file with PHP but keep the extension 我从w3schools获得了这个代码,并根据这个来调整它: 用PHP重命名上传的文件,但保留扩展名

Please help, what do I do so that the file extension will not be .tmp When I upload it to a folder on the server. 请帮忙,我该怎么办,以便文件扩展名不会是.tmp当我将它上传到服务器上的文件夹时。

   <?php
    $filename=$_FILES["file"]["tmp_name"];
    $extension=end(explode(".", $filename));
    $newfilename=$prod .".".$extension;

    if ((($_FILES["file"]["type"] == "image/gif")
    || ($_FILES["file"]["type"] == "image/jpeg")
    || ($_FILES["file"]["type"] == "image/pjpeg"))
    && ($_FILES["file"]["size"] < 100000))
      {
      if ($_FILES["file"]["error"] > 0)
        {
        echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
        }
      else
        {
        echo "Upload: " . $_FILES["file"]["name"] . "<br />";
        echo "Type: " . $_FILES["file"]["type"] . "<br />";
        echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
        echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

        if (file_exists("../img/user_uploaded/" . $_FILES["file"]["name"]))
          {
          echo $_FILES["file"]["name"] . " already exists. ";
          }
        else
          {
          move_uploaded_file($filename,
          "../img/user_uploaded/" . $newfilename);
          echo "Stored in: " . "../img/user_uploaded/" .$newfilename;
          }
        }
      }
    else
      {
      echo "Invalid file, File must be less than 100Kb in size with .jpg, .jpeg, or .gif file extension";
      }
    ?>
$filename=$_FILES["file"]["tmp_name"];
$extension=end(explode(".", $filename));
$newfilename=$prod .".".$extension;

In the above code you are trying to get the temporary file's extension. 在上面的代码中,您试图获取临时文件的扩展名。 Instead, you can take the extension of the original filename uploaded by the user. 相反,您可以使用用户上传的原始文件名的扩展名。

$filename=$_FILES["file"]["name"];
$extension=end(explode(".", $filename));
$newfilename=$prod .".".$extension;

This will upload your file with the actual file extension. 这将使用实际的文件扩展名上传您的文件。

Try to use this library for image manipulation... maybe is offtopic, but is realy usefull for dealing with images. 尝试使用这个库进行图像处理......可能是offtopic,但对处理图像非常有用。

WideImage: http://wideimage.sourceforge.net/ WideImage: http ://wideimage.sourceforge.net/

For example: 例如:

include('path to WideImage.php');

$filename = $_FILES["file"]["name"];
$ext = strtolower(substr(strrchr($filename, '.'), 1)); //Get extension
$image_name = $name . '.' . $ext; //New image name

$image = WideImage::load($_FILES['file']['tmp_name']); //Get image
$image->saveToFile('path/to/image/' . $image_name); //Save image
rename('path/to/file/file.ext', 'path/to/file/newname.ext');

此功能是复制和取消链接的连接。

This part does rename the file. 这部分重命名该文件。

move_uploaded_file($filename,"../img/user_uploaded/" . $newfilename); move_uploaded_file($ filename,“.. / img / user_uploaded /”。$ newfilename);

So the issue is how to set the value of $newfilename. 所以问题是如何设置$ newfilename的值。 If you have a method to produce this then the issue is solved. 如果你有一个方法来产生这个,那么问题就解决了。

I disagree with the answer of @Alexander.Plutov. 我不同意@ Alexander.Plutov的回答。 You don't have to save a file, then copy it, then unlink it . 您不必保存文件,然后复制它,然后取消链接

Since you specify the destination file name in your code: 由于您在代码中指定了目标文件名:

move_uploaded_file($filename, "../img/user_uploaded/" . $newfilename);
echo "Stored in: " . "../img/user_uploaded/" .$newfilename;

all you have is to specify another name instead of $newfilename . 你所拥有的只是指定另一个名称而不是$newfilename If your goal is to replace .tmp extension by something else, you may remove the last four characters (which are always .tmp, set by PHP), then add your own extension. 如果你的目标是用其他东西替换.tmp扩展名,你可以删除最后四个字符 (总是.tmp,由PHP设置),然后添加你自己的扩展名。

If you just want to keep the extension given by the user, use: 如果您只想保留用户提供的扩展名,请使用:

$friendlyName = $_FILES["file"]["name"];
$extension = substr($friendlyName, strrpos($friendlyName, '.') + 1);

Of course, you have to be aware of the risk of using something posted by the user. 当然,您必须意识到使用用户发布的内容的风险。 What if there is no extension at all, or if it is too long, or if it does not match the real file type (deadly-virus.exe renamed to pretty-image.jpg)? 如果根本没有扩展,或者它太长,或者它与真实文件类型不匹配(deadly-virus.exe重命名为pretty-image.jpg)怎么办?

Small example you can use rand() function to create random file-name. 您可以使用rand()函数创建随机文件名的小示例。

$min_rand=rand(0,1000);
$max_rand=rand(100000000000,10000000000000000);
$name_file=rand($min_rand,$max_rand);//this part is for creating random name for image

$ext=end(explode(".", $_FILES["file"]["name"]));//gets extension

move_uploaded_file($_FILES["file"]["tmp_name"],"/new folder/" . $name_file.".".$ext);//actually reponsible for copying file in new folder

$filenameimage="../upload_image/" . $name_file.".".$ext;
$actualimageurl="../upload_image/" . $_FILES["file"]["name"];

You can add datetime to directory where you uploading it's easier. 您可以将日期时间添加到上载目录的目录更容易。 Example: 例:

$date = date("Y-m-d H:i:s");

../img/user_uploaded/$date

But don't but / in the end becouse it changes directory 但不要/但最终因为它更改目录

Best way used the pathinfo() 最好的方法是使用pathinfo()

$filename=$_FILES["file"]["name"];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$image_name = $yours_new_name.'.'.$ext;

Uninitialized variable $prod! 未初始化的变量$ prod! This is a major security flaw. 这是一个重大的安全漏洞。 Always initialize your variables before using them. 始终在使用变量之前初始化变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM