user3720747
user3720747

Reputation: 55

How to rename a uploaded pdf via PHP. With this specific code

How can I use the code below and rename the pdf before moving the file to a directory?

<?php
session_start();

$full = $_SESSION['full'];

mkdir('pictures/'.$full.'_uploads', 0777, true);
chmod('pictures', 0777);
chmod('pictures/'.$full.'_uploads', 0777);


$target_dir = 'pictures/'.$full.'_uploads/';
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);


// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {

    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file )) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?> 

I prefer name the file a specific name, not a random name.

Upvotes: 0

Views: 1919

Answers (3)

Harish Lalwani
Harish Lalwani

Reputation: 774

This can be done using rename function

rename — Renames a file or directory

rename ("/folder/file.ext", "/folder/newfile.ext");

Though @disha's approach is better.

Upvotes: 1

Disha V.
Disha V.

Reputation: 1864

You need to put your desired name after target dir in targe filename like below. And rest is the same of your code.

$target_file = $target_dir ."myfavoritename.pdf";
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file )) { 

Upvotes: 2

Happy Coding
Happy Coding

Reputation: 2525

Simply change your target file variable :

$target_file = $target_dir.mktime(date("h"),date("i"),date("s"),date("m"),date("d"),date("y")).basename($_FILES["fileToUpload"]["name"]);

I have renamed the current pdf name with current time. You can use it accordingly.

Upvotes: 0

Related Questions