How can I rename a file before uploading it to the server?

2

I'm doing a form that processes certain data, I'm using the following code, and I need to know how to rename a selected image, before uploading it to the server.

That is, if when you select the image it is called imagen.png , rename it by $placa in the php

Used PHP Code

$placa = $_POST['placa'];
//UPLOAD FILE
$target_dir = "../../images/profiles/vh/";

$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// 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 . $newfilename)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
    
asked by Andres Arango 05.08.2018 в 00:37
source

2 answers

2

You almost have it ready, the first thing you should know is what type of image is going up ( .jpg , .png , etc). Since the value received by $_POST['placa'] will only have the name I imagine and the type of file, so you should do the following:

$placa       = $_POST['placa'];
$newfilename = $placa . $_FILES["fileToUpload"]["type"]; //concatena el nombre que le pasaste y agregale el tipo de imagen.

Then below you already have it:

if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file . $newfilename)) { ... }

I hope and it works for you

    
answered by 05.08.2018 / 01:44
source
1

Simply concatenate the name here:

$placa = $_POST['placa'];
//UPLOAD FILE
$target_dir = "../../images/profiles/vh/";

$target_file = $target_dir . $placa;
$uploadOk = 1;
    
answered by 05.08.2018 в 01:14