user4913675
user4913675

Reputation:

Is their anyway I can replace the filename to MD5

I am working on a small upload script. But, when the file is uploaded to the upload directory. The file name is the same name of the file uploaded. Is it possible to rename it to random digits like MD5. Thanks!

<?php

require 'header.php';

?>

<center>
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = 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 not an image.";
      //  $uploadOk = 1;
    }
}
?>
<br>
<?php
// Check if file already exists
if (file_exists($target_file)) {
    echo " Sorry, the file already exists or";
    $uploadOk = 0;
}
?>
<br>
<?php
// Check file size
if ($_FILES["fileToUpload"]["size"] > 5000000) {
    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 "your file was not uploaded correctly. Please try again or contact support!.";
// 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.";
    }
}
?>
</center>

Upvotes: 0

Views: 116

Answers (2)

elixenide
elixenide

Reputation: 44833

Yes. Just use move_uploaded_file() to rename it.

It's hard to give you too much more information, since you haven't posted any code. To generate the file name, you can use uniqid() if you don't need the string to be truly random. If you do need it to be truly random, you need a cryptographically secure function like openssl_random_pseudo_bytes()

Example:

$randomString = openssl_random_pseudo_bytes(20);
$path_parts = pathinfo($tmpFileName);
move_uploaded_file($tmpFileName, $path_parts['filename'] . '-' . $randomString . $path_parts['extension']);

This generates a random string, then rebuilds the file name using that string. If the upload was name, for example, lolcats.gif, your renamed file might be something like lolcats-3hf98jfd89W04kLq9PrR.gif.

Upvotes: 0

Mindastic
Mindastic

Reputation: 4121

Why don't you use uniqid to generate the new file name? That way you will be sure each file uses unique names.

Upvotes: 1

Related Questions