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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3665188/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:37:12  来源:igfitidea点击:

how to rename uploaded image in php

phpupload

提问by user225269

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";
      }
    ?>

回答by Mohamed

$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.

这将上传带有实际文件扩展名的文件。

回答by Wolfy

Try to use this library for image manipulation... maybe is offtopic, but is realy usefull for dealing with images.

尝试使用这个库进行图像处理......也许是题外话,但对于处理图像非常有用。

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

宽图像: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

回答by Alex Pliutau

rename('path/to/file/file.ext', 'path/to/file/newname.ext');

This function is the concatenating of copy and unlink.

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

回答by Babak Bandpay

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. If you have a method to produce this then the issue is solved.

所以问题是如何设置$newfilename 的值。如果你有一种方法来产生这个,那么问题就解决了。

回答by Arseni Mourzenko

I disagree with the answer of @Alexander.Plutov. You don't have to save a file, then copy it, then unlink it.

我不同意@Alexander.Plutov 的回答。您不必保存文件,然后复制它,然后取消链接

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. 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.

您所要做的就是指定另一个名称而不是$newfilename. 如果您的目标是用其他内容替换 .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)怎么办?

回答by Wazy

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"];

回答by Евгений

Best way used the pathinfo()

使用pathinfo() 的最佳方法

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

回答by Forgot Vegas Hero

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

但不要但/最终因为它改变了目录

回答by Inspired Prynce Kaka

Uninitialized variable $prod! This is a major security flaw. Always initialize your variables before using them.

未初始化的变量 $prod! 这是一个主要的安全漏洞。在使用变量之前总是初始化它们。