Upload file and rename it

0

Good afternoon. I want to upload a file to my server but it will be renamed with the name of a variable that comes by method GET , that is, the address would be localhost/fotos/subir.php?nuevonombre=juan , and if the file is called Felipe.jpg , I want it to be renamed and it's called juan.jpg .

Here I attach the code

    <!DOCTYPE html>
    <html lang="es">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
    <title>Subir archivos al servidor</title>
    <meta name ="author" content ="Norfi Carrodeguas">
    <style type="text/css" media="screen">
    body{font-size:1.2em;}
    </style>
    </head>
    <body>
    <form enctype='multipart/form-data' action='' method='post'>
    <input name='uploadedfile' type='file'><br>
    <input type='submit' value='Subir archivo'>
    </form>
    <?php 
    $target_path = "uploads/";
    $target_path = $target_path . basename( $_FILES['uploadedfile']['name']); 
    if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) 
    { 
    echo "<span style='color:green;'>El archivo ". basename(             
    $_FILES['uploadedfile']['name']). " ha sido subido</span><br>";
    }else{
    echo "Ha ocurrido un error, trate de nuevo!";
    } 
    ?>

    </body>
    </html>

Thank you very much.

    
asked by Fredy Aristizábal Aristizábal 22.11.2017 в 22:18
source

1 answer

3

One option to rename would be to first obtain the file extension by using explode () , with the difference that you will access name and not% tmp_name since the extension of tmp_name is tmp .

 $parts = explode(".",$_FILES['uploadedfile']['name']);
 end($parts) // Obtiene el ultimo elemento del array devuelto por explode.

To then simply concatenate the name you receive. Keep in mind that a hidden field (hidden) would be better in the dom with the new name and not perform _GET Y _POST at the same time.

<form enctype='multipart/form-data' action='' method='post'>
  <input type="hidden" name="nuevonombre" value="juan">
  <input name='uploadedfile' type='file'><br>
  <input type='submit' value='Subir archivo'>
</form>

<?php
  $target_path = "uploads/";
  $parts = explode(".",$_FILES['uploadedfile']['name']);
  //construimos el nuevo nombre con lo que viene por post nuevonombre
 // con el final del explode que sería la extensión de la imagen
  $target_path = $target_path . $_POST['nuevonombre'] .".". end($parts);

  if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) 
  { 
    echo "<span style='color:green;'>El archivo ". basename(             
    $_FILES['uploadedfile']['name']). " ha sido subido</span><br>";
  }
   else{
    echo "Ha ocurrido un error, trate de nuevo!";
  } 
    
answered by 22.11.2017 / 23:03
source