Rename uploaded file (php)

2019-01-29 14:25发布

问题:

I'm trying to rename a file I'm uploading.

I will be uploading a xml or pdf file, and I want it to be in a folder called "files/orderid/" and the filename should also be orderid.extension

The file uploads fine, and the folder id created with the correct name, but all the ways I have tried to rename it fails.

Below is my code.

// include database connection
 include 'config/database.php';

// get passed parameter value, in this case, the record ID
 $id=isset($_GET['orderid']) ? $_GET['orderid'] : die('FEJL: Ordren kunne ikke findes.');

// page header
 $page_title="Upload pdf og/eller xml fil";
 include_once "layout_head.php";

 echo "Ordrenummeret er ";
 echo $id;
 echo "<br>";

 if($_POST){

mkdir("files/$id");
$target_dir = "files/$id/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);


// Check if file already exists
if (file_exists($target_file)) {
    echo "Filen eksisterer allerede.";
    $uploadOk = 0;
}


// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Filen er for stor.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "xml" && $imageFileType != "pdf") {
    echo "Kun xml og pdf filer kan uploades.";
    $uploadOk = 0;
}


// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Filen blev ikke uploaded.";

// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "Filen ". basename( $_FILES["fileToUpload"]["name"]). " er uploaded.";
    } else {
        echo "Der skete en fejl ved upload, prøv igen.";
    }
}
}
?>

 <!DOCTYPE html>
 <html>
 <body>

 <form action="upload_files.php?orderid=<?php echo htmlspecialchars($id); ?>" method="post" enctype="multipart/form-data">
Vælg xml eller pdf fil:
<input type="file" name="fileToUpload" id="<?php echo htmlspecialchars($id); ?>">
<input type="submit" value="Upload fil" name="submit">
 </form>

 </body>
 </html>

回答1:

Rename the file as below

$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$target_file = $target_dir . $id . '.' . $imageFileType;

And then

move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);


回答2:

You set the target file to be the name of the file. You should be setting a different name.

Try this:

$target_dir = "files/$id/";
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$target_file = "{$target_dir}{$id}.{$imageFileType};


回答3:

Thanks guy, it all helped.

My solution was to make a variable with the extension, and then use that through out the file.

//Check file extension
$path = $_FILES["fileToUpload"]["name"];
$ext = pathinfo($path, PATHINFO_EXTENSION);

and then

move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], "files/$id/$id.$ext"