Search code examples
phphtmlfile-uploadfilenames

Cant keep original FileName after Upload


I am currently using PHP to create a file upload system. I took help from internet and successfully made the project.

But problem was that after upload the FileName would change to something complicated. Eg: 5987fff5b3dd83.21913884.

Is there a way to retain the original name after upload. Currently location is in Localhost but later I have to upload it to my website.

Code for index.php

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>

<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit" name="submit">UPLOAD</button>
</form>

</body>
</html>

Code for upload.php

<?php
if (isset($_POST['submit'])) {
$file = $_FILES['file'];

$fileName = $file['name'];
$fileTmpName = $file['tmp_name'];
$fileSize = $file['size'];
$fileError = $file['error'];
$fileType = $file['type'];

$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));

$allowed = array('jpg', 'jpeg', 'png', 'pdf');

if (in_array($fileActualExt, $allowed)) {
    if ($fileError === 0) {
        if ($fileSize < 1000000) {
            $fileNameNew = uniqid('', true).".".$fileActualExt;
            $fileDestination = 'uploads/'.$fileNameNew;
            move_uploaded_file($fileTmpName, $fileDestination);
            echo "OK";
            header("Location: ab.html");
        } else {
            echo "Your file is too big!";
        }
    } else {
        echo "There was an error uploading your file!";
    }
} else {
    echo "You cannot upload files of this type!";
}
}

Kindly suggest possible way to solve the problem.

Regards

Harsh Bansal


Solution

  • what you are doing is assigning random value to name

     $fileNameNew = uniqid('', true).".".$fileActualExt;
    

    do this

     $fileNameNew = $fileName;