0

Here's my code: I need to give a random name to the photos when they are being uploaded, but i don't know how, please help.

<?php



if (isset($_POST['submit'])) {

    $validextensions = array("jpeg", "jpg", "png");

    $temporary = explode(".", $_FILES["file"]["name"]);

    $file_extension = end($temporary);



    if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")

            ) && ($_FILES["file"]["size"] < 1000000000000000000000000000000000000000000000000000000)//Approx. 100kb files can be uploaded.

            && in_array($file_extension, $validextensions)) {



        if ($_FILES["file"]["error"] > 0) {

            echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";

        } else {



            echo "<span>Vasa Slika je uspesno prikacena...!!</span><br/>";

            echo "<br/><b>Ime od vasa slika:</b> " . $_FILES["file"]["name"] . "<br>";

            echo "<b>Tip:</b> " . $_FILES["file"]["type"] . "<br>";

            echo "<b>Velicina:</b> " . ($_FILES["file"]["size"] / 1024) . " kB<br>";






            if (file_exists("upload/" . $_FILES["file"]["name"])) {

                echo $_FILES["file"]["name"] . " <b>vec postoji.</b> ";

            } else {

                move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);

                $imgFullpath = "http://".$_SERVER['SERVER_NAME'].dirname($_SERVER["REQUEST_URI"].'?').'/'. "upload/" . $_FILES["file"]["name"];

                echo "<b>Link ka vasu sliku:</b><a href = '$imgFullpath' target='_blank'> " .$imgFullpath.'<a>';



            }



        }

    } else {

        echo "<span>***Niste odabrali sliku !!!***<span>";

    }

}

?>

The question is: How can i give a unique random name of the pictures when they are being uploaded ? as the tittle says.

Thanks.

darknet
  • 47
  • 5

2 Answers2

1

you should create a random characters first :

$random_chars = sha1(time().uniqid());

then append the file extention :

$new_filename = $random_chars.'.'.$your_extention;

in the end :

move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $new_filename);
0

First, read this: https://stackoverflow.com/a/2562877/2266583

Then with that information in mind:

echo md5($path_parts['filename'] . time()) . $path_parts['extension']
Community
  • 1
  • 1
zanderwar
  • 3,440
  • 3
  • 28
  • 46