Upload Script - Dateinamen numerisch ändern?!

phil-ip

Erfahrenes Mitglied
Guten Abend,
ich habe nun nach etwas längerer Suche endlich ein entsprechendes und fähiges Upload-Script gefunden.

Quelle: http://www.ineedtutorials.com/articles/php-file-upload

PHP:
<form name="upload-form" id="upload-form" method="post" action="./upload.php" enctype="multipart/form-data"> 
  <input type="hidden" name="MAX_FILE_SIZE" value="30000"> 
  <fieldset> 
  <legend>File upload:</legend> 
  <dl> 
    <dt> 
      <label for="file">File:</label> 
    </dt> 
    <dd> 
      <input tabindex="1" accesskey="b" name="file" type="file" id="file" /> 
    </dd> 
  </dl> 
  <input tabindex="2" accesskey="l" type="submit" name="cmdupload" value="Upload" /> 
  </fieldset> 
</form>
PHP:
<?php
$uploaddir = "files/"; //Upload directory: needs write premissions
$log = "uploadlog.txt"; // Upload LOG file
// what file types do you want to disallow?
$blacklist = array(".php", ".phtml", ".php3", ".php4", ".php5", ".exe", ".js",".html", ".htm", ".inc");
 // allowed filetypes       
$allowed_filetypes = array('.jpg','.gif','.bmp','.png');
   
if (!is_dir($uploaddir)) {
    die ("Upload directory does not exists.");
}
if (!is_writable($uploaddir)) {
    die ("Upload directory is not writable.");
}

if ($_POST['cmdupload'])
{
   
$ip = trim($_SERVER['REMOTE_ADDR']);

    if (isset($_FILES['file']))
    {
        if ($_FILES['file']['error'] != 0)
        {
            switch ($_FILES['file']['error'])
            {
                case 1:
                    print 'The file is to big.'; // php installation max file size error
                    exit;
                    break;
                case 2:
                    print 'The file is to big.'; // form max file size error
                    exit;
                    break;
                case 3:
                    print 'Only part of the file was uploaded';
                    exit;
                    break;
                case 4:
                    print 'No file was uploaded</p>';
                    exit;
                    break;
                case 6:
                    print "Missing a temporary folder.";
                    exit;
                    break;
                case 7:
                    print "Failed to write file to disk";
                    exit;
                    break;
                case 8:
                    print "File upload stopped by extension";
                    exit;
                    break;

            }
        } else {
            foreach ($blacklist as $item)
            {
                if (preg_match("/$item\$/i", $_FILES['file']['name']))
                {
                    echo "Invalid filetype !";
                        $date = date("m/d/Y");
                        $time = date("h:i:s A");                 
                        $fp = fopen($log,"ab");
                        fwrite($fp,"$ip | ".$_FILES['file']['name']." | $date | $time | INVALID TYPE"."\r\n");
                        fclose($fp);
                    unset($_FILES['file']['tmp_name']);
                    exit;
                }
            }
            // Get the extension from the filename.
            $ext = substr($_FILES['file']['name'], strpos($_FILES['file']['name'],'.'), strlen($_FILES['file']['name'])-1);
      // Check if the filetype is allowed, if not DIE and inform the user.
      if(!in_array($ext,$allowed_filetypes)){
                        $date = date("m/d/Y");
                        $time = date("h:i:s A");                     
                        $fp = fopen($log,"ab");
                        fwrite($fp,"$ip | ".$_FILES['file']['name']." | $date | $time | INVALID TYPE"."\r\n");
                        fclose($fp);
                die('The file you attempted to upload is not allowed.');
            }
            if (!file_exists($uploaddir . $_FILES["file"]["name"]))
            {
                // Proceed with file upload
                if (is_uploaded_file($_FILES['file']['tmp_name']))
                {
                    //File was uploaded to the temp dir, continue upload process
                    if (move_uploaded_file($_FILES['file']['tmp_name'], $uploaddir . $_FILES['file']['name']))
                    {
                        // uploaded file was moved and renamed succesfuly. Display a message.
                        echo "Upload successful !";
                        // Now log the uploaders IP adress date and time
                        $date = date("m/d/Y");
                        $time = date("h:i:s A");               
                        $fp = fopen($log,"ab");
                        fwrite($fp,"$ip | ".$_FILES['file']['name']." | $date | $time | OK"."\r\n");
                        fclose($fp);
                    } else {
                        echo "Error while uploading the file, Please contact the webmaster.";
                        unset($_FILES['file']['tmp_name']);
                    }
                } else {
                    //File was NOT uploaded to the temp dir
                    switch ($_FILES['file']['error'])
                    {
                        case 1:
                            print 'The file is to big.'; // php installation max file size error
                            break;
                        case 2:
                            print 'The file is to big.'; // form max file size error
                            break;
                        case 3:
                            print 'Only part of the file was uploaded';
                            break;
                        case 4:
                            print 'No file was uploaded</p>';
                            break;
                        case 6:
                            print "Missing a temporary folder.";
                            break;
                        case 7:
                            print "Failed to write file to disk";
                            break;
                        case 8:
                            print "File upload stopped by extension";
                            break;

                    }

                }
            } else {
                echo "Filename already exists, Please rename the file and retry.";
                unset($_FILES['file']['tmp_name']);
            }
        }
    } else {
        // user did not select a file to upload
        echo "Please select a file to upload.";       
    }
} else {
    // upload button was not pressed
    header("Location: uploadform.php");
}
?>
Nun würde ich gerne noch den Dateinamen numerisch ändern lassen. Sprich "Urlaubsphoto92.jpg" (lokal) wird zu "671232.jpg" (Server). Das sollte doch mit Hilfe eines Counters o.Ä. möglich sein. Ausserdem würde ich nach erfolgreichem Upload die Url zum Bild per echo ausgeben lassen. Sollte doch auch mit Variablen möglich sein. Ich habe leider so gut wie keine Ahnung von PHP. Vielleicht kann mir jemand helfen. Danke schon mal! Gruß!

P.S.: Ich glaube, der Begriff "numerisch" passt nicht wirklich, viel mehr "durchnummeriert". :-)

--- EDIT ---

File-URL Ausgabe ohne Ändern des Namens geht mit:

PHP:
// uploaded file was moved and renamed succesfuly. Display a message.
echo "Upload successful !";
echo "<br>";
echo "URL: http://www.xxx.de/upload/files/";
echo $_FILES['file']['name'];
 
Zuletzt bearbeitet:
So, ich habe selbst eine Lösung gefunden. Allerdings wird damit der gesamte Dateiname+Endung (.gif/.jpg/...) zu einer Zahl überschrieben. Wie kann ich die Endung noch mit anhängen?

PHP:
// Count and Rename Filename.
$num = count(glob($uploaddir."/*"))+1;
rename($uploaddir . $_FILES['file']['name'],$uploaddir . $num);
// uploaded file was moved and renamed succesfuly. Display a message.
echo "Upload successful !";
echo "<br>";
// Url to File
echo "URL: http://www.xxx.de/upload/files/";
echo $num;
Ist die Dateiendung noch irgendwo als Variable hinterlegt?!

So jetzt aber gut Nacht! Ein Glück habe ich morgen frei :-)
 
Zum Beispiel:
PHP:
$path = 'test.zip';
$path = explode('.',$path);
$endung = $path[count($path)-1];
Da kommen sicher noch andere vorschläge ;)
 
Danke Loomes! Ich habe deine Variante benutzt. Das ganze war ja irgendwie garnicht so schwer wie erwartet.

Hier jetzt nochmal die neuen Teile des Scripts:

PHP:
// file extension filter
$path = $_FILES['file']['name'];
$path = explode('.',$path);
$endung = $path[count($path)-1];
// Count and Rename Filename.
$num = count(glob($uploaddir."/*"))+1;
rename($uploaddir . $_FILES['file']['name'],$uploaddir . $num . "." . $endung);
// uploaded file was moved and renamed succesfuly. Display a message.
echo "Upload successful !";
echo "<br>";
// Url to File
echo "URL: http://www.xxx.de/upload/files/";
echo $num.".".$endung;
 
Zuletzt bearbeitet:
Zurück