Hello, I currently have a script that Uploads an image, resizes and saves successfully. I am having trubble understanding how I would rename the uploaded image according to the other image names in the directory. For example there are 3 images in the directory (Image1.png, Image2.gif and Image3.jpg) How would I be able to rename the next image that is uploaded to Image4.png or Image4.jpg or Image4.gif (depending on upload extention) automaticly without having to change the name before upload, and so on for later uploads (Image5, 6, 7, etc.)? Here is my code:

<?php 
error_reporting(0);

$change="";
$abc="";


 define ("MAX_SIZE","999999");
 function getExtension($str) {
         $i = strrpos($str,".");
         if (!$i) { return ""; }
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
 }

 $errors=0;

 if($_SERVER["REQUEST_METHOD"] == "POST")
 {
    $image =$_FILES["file"]["name"];
    $uploadedfile = $_FILES['file']['tmp_name'];


    if ($image) 
    {

        $filename = stripslashes($_FILES['file']['name']);

        $extension = getExtension($filename);
        $extension = strtolower($extension);


 if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) 
        {

            $change='<h2>Unknown Image extension</h2>';
            $errors=1;
        }
        else
        {

 $size=filesize($_FILES['file']['tmp_name']);


if ($size > MAX_SIZE*1024)
{
    $change='<h2>You have exceeded the size limit!</h2>';
    $errors=1;
}


if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);

}
else if($extension=="png")
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);

}
else 
{
$src = imagecreatefromgif($uploadedfile);
}

echo $scr;

list($width,$height)=getimagesize($uploadedfile);


$newheight=90;
$newwidth=($width/$height)*$newheight;
$tmp=imagecreatetruecolor($newwidth,$newheight);


imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);


$filename = "images/". $_FILES['file']['name'];



imagejpeg($tmp,$filename,100);

imagedestroy($src);
imagedestroy($tmp);
}}

}

//If no errors registred, print the success message
 if(isset($_POST['Submit']) && !$errors) 
 {

   // mysql_query("update {$prefix}users set img='$big',img_small='$small' where user_id='$user'");
    $change='<h2>Image Uploaded Successfully!</h2>' . 
    "Upload: " . $_FILES["file"]["name"] . "<br />" .
    "Type: " . $_FILES["file"]["type"] . "<br />" .
    "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />" .
    "Stored in: <a href=\"images/" . $_FILES["file"]["name"] . "\">" . $_FILES["file"]["name"] . "</a><br />" .
    "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />" .
    "Old Demintions: " . $width . " x " . $height . "<br />" .
    "New Demintions: " . $newwidth . " x " . $newheight . "<br /><br />";
 }

?>
<head>
    <link rel="stylesheet" href="../css/main.css"  type="text/css" />
</head>
    <?php echo $change; ?>
                    <img src="<?php echo $filename . "\" alt=\"PNG Upload\"  title=\"" . $filename . "\"/>"; ?>
                        <form method="post" action="" enctype="multipart/form-data" name="form2"><br />
                <input size="25" name="file" type="file" class="box"/><br /><br />
                    <input type="submit" id="mybut" value="       Upload        " name="Submit"/>
                    </form>

Thanks in advance!

Something like this will work:

    <?php
    $file = $_FILES['file']['name'];
    $a = pathinfo($file);

    $basename = $a['basename'];
    $filename = $a['filename'];
    $extension = $a['extension'];

    $path = $_SERVER['DOCUMENT_ROOT'].'/up/images/'; # set upload directory
    $dest = $path.$basename;

    if(file_exists($dest))
    {
        $b = count(glob($path.$filename.'*.'.$extension))+1; # all matches + 1
        for($i = 1; $i < $b; $i++)
        {
            if(!file_exists($path.$filename.$i.'.'.$extension))
            {
                move_uploaded_file($_FILES['file']['tmp_name'],$path.$filename.$i.'.'.$extension);
            }
        }
    }
    else
    {
        move_uploaded_file($_FILES['file']['tmp_name'],$dest);
    }
    ?>

If the file exists then the script does a glob() in the destination directory in search of the filename (without the number) and counts all the matches, we add 1 to the result and go to loop until a free combination is find. This is just an interpretation of a function used in CodeIgniter framework that you can find in System/Libraries/Upload.php at line 390~ the difference is that in CI that function is limitated to 100 loops. Bye.

Thanks! :)

You're welcome, if your problem is solved please mark the thread as solved, bye :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.