Louis Shiggy Lombardi Louis Shiggy Lombardi - 2 months ago 17
PHP Question

PHP - Rename and upload a file if it exists

I have recently been learning to build an image gallery uploader in PHP. I can't seem to work out how i actually rename my file before uploading it to my uploads folder. Can anyone help me please?

Heres what i have so far.

if(isset($_POST['submit'])) {
$allowedExts = array("gif", "jpeg", "jpg", "png","GIF","JPEG","JPG","PNG");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& in_array($extension, $allowedExts)) {

if ($_FILES["file"]["error"] > 0) {
echo "Invalid File Type";
} else {

$target = "../upload/";
$name = addslashes($_FILES['file']["name"]);

if(file_exists('../upload/' . $name)) {
$explode = explode('.', $name);
$img = $explode[0];
$ex = $explode[1];
$i = 1;
$new = $img . '_' . $i . '.' . $ex;

while (file_exists('../upload/' . $new)) {
$new = $img . '_' . $i . '.' . $ex;


move_uploaded_file($_FILES["file"]["tmp_name"], $target. $_FILES["file"]["name"]);

} else {
echo "Error uploading image";


So right after my while loop is where i want to rename the file then use the move_uploaded_file()function to move it into my "upload" directory. Whats the best way i can achieve this?



When you call move_file_upload you can simply give the new file its name as the second parameter, I understand the documentation doesn't make this clear but it works.

move_uploaded_file($_FILES["file"]["tmp_name"], $target. $_FILES["file"]["name"]);

So you would do something like

move_uploaded_file($_FILES["file"]["tmp_name"], $target. $_FILES["file"]["name"] . "Some random string to be added to the filename");

Or if you want to disregard the previous filename all together just remove it from your second parameter.

move_uploaded_file($_FILES["file"]["tmp_name"], $target. "new file name here");