> 
> I got a bit frustrated with image upload stuff with different 
> image name problems. So I created a system that gives the 
> uploaded imaged a random numeric name between 1-10 000 000 
> and saves the file to a server folder and the image name to mysql DB.
> 
> Is there a so sort of a problem here that I am not thinking 
> of? I only can imagine problem that the rand() gives the same 
> value twice. But I cant see this as a major problem because 
> there would be maybe not more than 1000 uploaded pictures. So 
> the chance is at worst something like 1:10 000 that same name 
> is created to the image.
> 
> Anyway if same name is created what's the best way to check 
> that? I was thinking of putting the image name field in DB as 
> a unique field. That would do it? Right?


Append a datetime to the filenames, or use a folder per date?

If want to create a unique filename, and are using PHP4.3.2 or better, use 
fopen() with the 'x' or 'x+' mode, rather than
file_exists().

Something like the function below, 
        The filename parameter is passed by reference, so you can retrieve the 
filename the function actually created.
        Returns a FALSE, or a standard file handle which can fwrite() etc. 

function createFileWithUniqueName(&$filename)
{
        $f = @fopen($filename, 'x');
        if ($f === FALSE)
        {
                $pathInfo = pathinfo($filename);

                $dirname = $pathInfo['dirname'];
                $basename = $pathInfo['basename'];
                $extension = $pathInfo['extension'];

                if (!empty($dirname))
                        $dirname .= DIRECTORY_SEPARATOR;

                if (!empty($extension))
                {
                        $extension = '.'.$extension;
                        $basename = substr($basename, 0, -strlen($extension)); 
// Remove extension from basename
                }
                $prefix = $dirname.$basename.'_';

                /* Keep trying to create new files ... The $n < 100 is just to 
prevent any extreme situations happening */
                for ($n = 1; $f === FALSE && $n < 100; ++$n)
                {
                        $name = $prefix.$n.$extension;
                        $f = @fopen($name, 'x');
                }

                if ($f !== FALSE)
                        $filename = $name;
        }
        return $f;
}

        $basename = 'test.txt';

        $n = $basename;

        $f = createFileWithUniqueName($n);
        if ($f !== FALSE)
        {
                fwrite($f, 'test '.$n);
                fclose($f);
        }

        $n = $basename;
        $f = createFileWithUniqueName($n);
        if ($f !== FALSE)
        {
                fwrite($f, 'test '.$n);
                fclose($f);
        }


Jared

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to