Fonction File Uploads Php

Résolu
Bonjour,
voila j'ai un probleme je voudrai que quand un personne uploads une images je voudrai que que le fichiers se renommer si elle existe deja est ce que vous pouvez m'aidez svp voici mon code

<?php
$target_path = "uploads/";

$target_path = $target_path . basename( $_FILES['uploadedfile']['name']); 

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
    echo "The file ".  basename( $_FILES['uploadedfile']['name']). 
    " has been uploaded";
} else{
    echo "There was an error uploading the file, please try again!";
}
?>


Merci a vous
Configuration: Windows Vista
Firefox 3.0.11

26 réponses

Résumé de la discussion

Lors du téléversement d'une image, il faut renommer le fichier si le nom existe déjà afin d'éviter les collisions et d'écraser le moins possible sur le serveur. La solution retenue consiste à afficher le nom généré et à vérifier s'il existe déjà, puis à ajouter des chiffres aléatoires jusqu'à obtenir un nom de fichier unique. Le code proposé utilise une boucle while sur file_exists pour itérer jusqu'à ce qu'un nom inoccupé soit trouvé et appelle move_uploaded_file pour le transfert du fichier. D'autres suggèrent d'utiliser pathinfo pour insérer proprement l'extension lors du renommage et d'optimiser la construction du chemin afin d'éviter des erreurs d'encodage ou de délimiteurs.

Bobot (l’IA à votre service)
  1. Contributeur
    fais afficher le nom généré pour le fichier et vérifies si il existe déjà sur ton disque :
    <?php
    $target_path = "uploads/";
    
    $target_path = $target_path . basename( $_FILES['uploadedfile']['name']); 
    
    while(file_exists($target_path))
    	$target_path = $target_path.rand(0, 9);
    	
    var_dump($target_path);
    
    if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
        echo "The file ".  basename( $_FILES['uploadedfile']['name']). 
        " has been uploaded";
    } else{
        echo "There was an error uploading the file, please try again!";
    }
    ?>
    1. Contributeur
      salut,

      de tête, je penserais à :
      <?php
      $target_path = "uploads/";
      
      $target_path = $target_path . basename( $_FILES['uploadedfile']['name']); 
      
      while(file_exists($target_path))
      	$target_path = $target_path.rand(0, 9);
      	
      if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
          echo "The file ".  basename( $_FILES['uploadedfile']['name']). 
          " has been uploaded";
      } else{
          echo "There was an error uploading the file, please try again!";
      }
      ?>
      1. merci sa marche mai le problème sait que le chiffre se mai après l'extension et sa donne ça images.png2
        1. Contributeur
          ah ben oui, qu'est-ce que je suis c** !

          désolé, je réfléchis pas j'applique du code bêtement…
          <?php
          $target_path = "uploads/";
          
          $target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
          while(file_exists($target_path))
          {
          	$name = pathinfo($target_path, 'filename');
          	$ext = pathinfo($target_path, 'extension');
          	$target_path = $name.rand(0, 9).$ext;
          }
          if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
              echo "The file ".  basename( $_FILES['uploadedfile']['name']).
              " has been uploaded";
          } else{
              echo "There was an error uploading the file, please try again!";
          }
          ?>
          
      2. il y a encore un probleme lol :

        Warning: pathinfo() expects parameter 2 to be long, string given in C:\wamp\www\ok.php on line 7
        
        Warning: pathinfo() expects parameter 2 to be long, string given in C:\wamp\www\ok.php on line 8
        The file bouton.png has been uploaded
        1. Contributeur
          ce coup-ci je plaide non coupable !!!
          j'ai pris les arguments dans le manuel PHP (version locale en CHM), "c'est pas d'ma faute m'sieur l'agent !".
          -:oD

          while(file_exists($target_path))
          {
          	$name = pathinfo($target_path, PATHINFO_FILENAME);
          	$ext = pathinfo($target_path, PATHINFO_EXTENSION);
          	$target_path = $name.rand(0, 9).$ext;
          }
          
          1. Contributeur
            grrrr !
            le point bon sang !

            bon ce coup -ci j'ai essayé, ça fonctionne !
            while(file_exists($target_path))
            {
            	$name = pathinfo($target_path, PATHINFO_FILENAME);
            	$ext = pathinfo($target_path, PATHINFO_EXTENSION);
            	$target_path = $name.rand(0, 9).'.'.$ext;
            	var_dump($target_path);
            }
            1. merci mais je sais je suis casse noisette mait il y a encore un probleme cet fois le fichier me vos pas dans le fichier "uploads"
              1. Contributeur
                que t'affiche le "var_dump($target_path);" ?

                ce n'est pas une adresse correcte ?

                as-tu essayé sans le "var_dump($target_path);", ça peut être lui qui empêche la suite du code de s'exécuter correctement.
                1. j'ai enlever le code :

                  var_dump($target_path); 


                  mait la sa copie plus du tous
                  1. Contributeur
                    et quand il y avait le "var_dump($target_path);", il affichait quoi comme erreur ?
                    1. sa m'affiche le mon d'origine de l'images par exemple "images.png"
                      1. Contributeur
                        while(file_exists($target_path))
                        {
                        	$name = pathinfo($target_path, PATHINFO_FILENAME);
                        	$ext = pathinfo($target_path, PATHINFO_EXTENSION);
                        	$target_path = $name.rand(0, 9).'.'.$ext;
                        	var_dump($target_path);
                        }

                        ça ?

                        je viens de le tester avec un "index.php" existant et il me renvoie "index1.php"…
                        1. sa copie et ça renommer bien mai il envoie pas le fichier dans le dossier "uploads" !
                          1. Contributeur
                            ah ben tu vois que tu peux être clair des fois !
                            -:oD

                            je te dirais bien de faire un petit "var_dump($_FILES);" pour savoir ce que le serveur reçoit comme fichier…
                            1. sa renvoie ça :

                              array(1) { ["uploadedfile"]=>  array(5) { ["name"]=>  string(13) "bannieres.png" ["type"]=>  string(9) "image/png" ["tmp_name"]=>  string(23) "C:\wamp\tmp\php9504.tmp" ["error"]=>  int(0) ["size"]=>  int(70830) } } The file bannieres.png has been uploaded
                              1. Contributeur
                                et tu as regardé ailleurs que dans "uploads" ?
                                genre un dossier ou deux au dessus ?

                                parce que le fichier existe bien et il le déplace bien des temporaires vars ailleurs, reste à trouver le ailleurs…
                                • 1
                                • 2