Uploading an image through the form in this way

$file=$_FILES['image']['tmp_name']; $image= addslashes(file_get_contents($_FILES['image']['tmp_name'])); $image_name= addslashes($_FILES['image']['name']); move_uploaded_file($_FILES["image"]["tmp_name"],"rentgen/userphotos/" . $_FILES["image"]["name"]); $location="rentgen/userphotos/" . $_FILES["image"]["name"]; 

Can you please tell me how to dynamically rename an image? I read that there is a uniqid function. How can I use this function in this code?

  • $name = uniqid().'.jpg'; move_uploaded_file($tmp_name, "$uploads_dir/$name"); - Vanya Avchyan

1 answer 1

move_uploaded_file() function takes as its second argument the path to which the file should be moved. At the very end of the path, the file name is specified. In your case, you need to change it.

Solution using the uniqid () function:

Note: This function tries to create a unique identifier, but does not give a 100% guarantee of uniqueness.

 $original_name = $_FILES["image"]["name"]; //ΠŸΠΎΠ»ΡƒΡ‡ΠΈΡ‚ΡŒ Ρ€Π°ΡΡˆΠΈΡ€Π΅Π½ΠΈΠ΅ Ρ„Π°ΠΉΠ»Π° $extension = pathinfo($original_name, PATHINFO_EXTENSION); //ΠŸΡ€ΠΈΠ΄ΡƒΠΌΠ°Ρ‚ΡŒ Π½ΠΎΠ²ΠΎΠ΅ имя Ρ„Π°ΠΉΠ»Π° с Ρ€Π°ΡΡˆΠΈΡ€Π΅Π½ΠΈΠ΅ΠΌ Π·Π°Π³Ρ€ΡƒΠΆΠ°Π΅ΠΌΠΎΠ³ΠΎ Ρ„Π°ΠΉΠ»Π° $new_name = uniqid().'.'.$extension; //ΠΈ Π·Π°Π³Ρ€ΡƒΠΆΠ°Π΅ΠΌ ΡƒΠΆΠ΅ с ΠΈΠ·ΠΌΠ΅Π½Π΅Π½Π½Ρ‹ΠΌ ΠΈΠΌΠ΅Π½Π΅ΠΌ move_uploaded_file($_FILES["image"]["tmp_name"],"rentgen/userphotos/" . $new_name); 

Example move_uploaded_file.

  • one
    Warning This function does not guarantee a unique value. Most operating systems synchronize time with NTP, or its analogs, so that the system time is constantly changing. Therefore, it is possible that this function returns a non-unique identifier for the process / thread. php.net/manual/ru/function.uniqid.php - Visman
  • @Visman Can ΠŸΠΎΠ΄ΡΠΊΠ°ΠΆΠΈΡ‚Π΅ поТалуйста ΠΊΠ°ΠΊ динамичСски ΠΏΠ΅Ρ€Π΅ΠΈΠΌΠ΅Π½ΠΎΠ²Π°Ρ‚ΡŒ ΠΈΠ·ΠΎΠ±Ρ€Π°ΠΆΠ΅Π½ΠΈΠ΅ ? Ρ‡ΠΈΡ‚Π°Π» Ρ‡Ρ‚ΠΎ Π΅ΡΡ‚ΡŒ функция uniqid ΠΊΠ°ΠΊ ΠΌΠΎΠΆΠ½ΠΎ ΠΈΡΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚ΡŒ эту Ρ„ΡƒΠ½ΠΊΡ†ΠΈΡŽ Π² Π΄Π°Π½Π½ΠΎΠΌ ΠΊΠΎΠ΄Π΅ ? me ΠŸΠΎΠ΄ΡΠΊΠ°ΠΆΠΈΡ‚Π΅ поТалуйста ΠΊΠ°ΠΊ динамичСски ΠΏΠ΅Ρ€Π΅ΠΈΠΌΠ΅Π½ΠΎΠ²Π°Ρ‚ΡŒ ΠΈΠ·ΠΎΠ±Ρ€Π°ΠΆΠ΅Π½ΠΈΠ΅ ? Ρ‡ΠΈΡ‚Π°Π» Ρ‡Ρ‚ΠΎ Π΅ΡΡ‚ΡŒ функция uniqid ΠΊΠ°ΠΊ ΠΌΠΎΠΆΠ½ΠΎ ΠΈΡΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚ΡŒ эту Ρ„ΡƒΠ½ΠΊΡ†ΠΈΡŽ Π² Π΄Π°Π½Π½ΠΎΠΌ ΠΊΠΎΠ΄Π΅ ? ΠŸΠΎΠ΄ΡΠΊΠ°ΠΆΠΈΡ‚Π΅ поТалуйста ΠΊΠ°ΠΊ динамичСски ΠΏΠ΅Ρ€Π΅ΠΈΠΌΠ΅Π½ΠΎΠ²Π°Ρ‚ΡŒ ΠΈΠ·ΠΎΠ±Ρ€Π°ΠΆΠ΅Π½ΠΈΠ΅ ? Ρ‡ΠΈΡ‚Π°Π» Ρ‡Ρ‚ΠΎ Π΅ΡΡ‚ΡŒ функция uniqid ΠΊΠ°ΠΊ ΠΌΠΎΠΆΠ½ΠΎ ΠΈΡΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚ΡŒ эту Ρ„ΡƒΠ½ΠΊΡ†ΠΈΡŽ Π² Π΄Π°Π½Π½ΠΎΠΌ ΠΊΠΎΠ΄Π΅ ? Answered this question - Vanya Avchyan
  • So you can answer correctly, even answering this question: R - Visman
  • @Visman read the question more closely. The author wanted to use the uniqid () function and did not ask about uniqueness. - Vanya Avchyan
  • @Visman I quote a question for you ΠŸΠ΅Ρ€Π΅ΠΈΠΌΠ΅Π½ΠΎΠ²Π°Ρ‚ΡŒ ΠΈΠ·ΠΎΠ±Ρ€Π°ΠΆΠ΅Π½ΠΈΠ΅ ΠΏΡ€ΠΈ Π·Π°Π³Ρ€ΡƒΠ·ΠΊΠ΅ Π½Π° сСрвСр Ρ‡Π΅Ρ€Π΅Π· uniqid . - Vanya Avchyan