Loading an image with PHP - renaming without losing the extension?

I currently have:

$file_name = $HTTP_POST_FILES['uid']['name'];
$random_digit=rand(0000,9999);
$new_file_name=$random_digit.$file_name;
$path= "uploads/images/users/".$new_file_name;
if($ufile !=none)
{
    if(copy($HTTP_POST_FILES['uid']['tmp_name'], $path))
    {
        echo "Successful<BR/>"; 
        echo "File Name :".$new_file_name."<BR/>"; 
        echo "File Size :".$HTTP_POST_FILES['uid']['size']."<BR/>"; 
        echo "File Type :".$HTTP_POST_FILES['uid']['type']."<BR/>"; 
    }
    else
    {
        echo "Error";
    }
}

this generates a random number before the current file name, i.e. 4593example.jpg but I just would like to rewrite the entire file name to 4593.jpg, deleting the ucrrent name (example). When I tried to do this, I lost the extension (.jpg) any help is appreciated.

+3
source share
4 answers
$ext = pathinfo($filename, PATHINFO_EXTENSION);

$newFilename = $random_digit . '.' . $ext;

By the way, what happens if a random number collides (what could happen next or in 10 years)?

There are many better ways to name them - for example, a hash of a file name and time()should theoretically never collide (although hash collisions occur in practice).

+3
source

, getimagesize() , .

, , ( ).

:

$extensions = array(
  IMAGETYPE_JPG => "jpg",
  IMAGETYPE_GIF => "gif",
  IMAGETYPE_PNG => "png",
  IMAGETYPE_JPEG2000 => "jpg",
  /* ...... several more at http://php.net/manual/en/image.constants.php 
            I'm too lazy to type them up */

 );

$info = getimagesize($_FILES['uid']['tmp_name']); 
$type = $info[2];

$extension = $extensions[$type];

if (!$extension) die ("Unknown file type");

move_uploaded_file($_FILES['uid']['tmp_name'], $path.".".$extension);

` :

+4

, :

$extension = strrchr($HTTP_POST_FILES['uid']['tmp_name'], '.');

$new_file_name :

$new_file_name = $random_digit . $file_name . '.' . $extension;

+3

:

$file_name = $HTTP_POST_FILES['uid']['name']; $random_digit=rand(0000,9999); 
$extension= end(explode(".", $HTTP_POST_FILES['uid']['name']));
$new_file_name=$random_digit.'.'.$extension; $path= "uploads/images/users/".$new_file_name; if($ufile !=none) { if(copy($HTTP_POST_FILES['uid']['tmp_name'], $path)) { echo "Successful
"; echo "File Name :".$new_file_name."
"; echo "File Size :".$HTTP_POST_FILES['uid']['size']."
"; echo "File Type :".$HTTP_POST_FILES['uid']['type']."
"; } else { echo "Error"; } }

!!!!!!!!!

+1

Source: https://habr.com/ru/post/1795196/


All Articles