Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change file name to uniqid in PHP

Tags:

file

php

I am looking to modify my code below to accept a randomly generated unique id to replace the name using php uniqid function. I have tried a couple ways with no success.

 move_uploaded_file($_FILES["file"]["tmp_name"],
 "upload/" . $_FILES["file"]["name"]);
 $ipath = "upload/";
 $ipath .= $_FILES["file"]["name"];

Does anyone know how I can accomplish this?

Edit: I am asking where to put the uniqid function so that the file is stored with the uniqid.extension in the folder on my server.

like image 253
user981053 Avatar asked Jan 10 '12 21:01

user981053


People also ask

How to change the file name in PHP?

PHP rename() Function rename("/test/file1. txt","/home/docs/my_file. txt");

How can we assign a unique identifier in PHP?

A unique user ID can be created in PHP using the uniqid () function. This function has two parameters you can set. The first is the prefix, which is what will be appended to the beginning of each ID. The second is more_entropy.


1 Answers

move_uploaded_file($_FILES["file"]["tmp_name"],
    "upload/" . uniqid());

or, if you want to keep the file extension:

$fileInfo = pathinfo($_FILES["file"]["name"]);

move_uploaded_file($_FILES["file"]["tmp_name"],
    "upload/" . uniqid() . '.' . $fileInfo['extension']);

\\edit: to use the $ipath variable...

$fileInfo = pathinfo($_FILES["file"]["name"]);
$ipath = "upload/" . uniqid() . '.' . $fileInfo['extension'];
move_uploaded_file($_FILES["file"]["tmp_name"], $ipath);
like image 103
Constantin Groß Avatar answered Sep 30 '22 05:09

Constantin Groß