syrkull
syrkull

Reputation: 2344

Renaming images by number in php

I am trying to create an option of uploading an avatar to my site. What I am trying to achieve is this :

first avatar : 1.jpg
second avatar : 2.jpg
third avatar : 3.png 
and so on.. 

How can I create an upload counter in php? My current code is this :

if(!empty($_FILES['cover']['tmp_name']))
{
    $uploadfolder =  "avatar/"; 
    $file1 = rands().'.'.end(explode('.',$_FILES['cover']['name'])); 
    $cover = $uploadfolder.$file1;
    move_uploaded_file($_FILES['cover']['tmp_name'],$cover);
}
else 
{
    $cover = ''
}

The function rands() does not do anything, so please use it to demonstrate how I can achieve my goal.

Upvotes: 1

Views: 103

Answers (5)

Ranjith
Ranjith

Reputation: 2819

    /*
     * currentDir - path - eg. c:/xampp/htdocs/movies/uploads (no end slash)
     * $dir - points current working directory.
     * $filename - name of the file.
 */

public static function getFileName($dir, $filename) {

    $filePath = $dir . "/uploads/" . $filename;
    $fileInfo = pathinfo($filePath);
    $i = 1;
    while(file_exists($filePath)) {
        $filePath = $dir . "/uploads/" . $fileInfo['filename'] . "_" . $i . "." . $fileInfo['extension'];
        $i++;

    }
    return $filePath;
}

move_uploaded_file($_FILES['cover']['tmp_name'],$filePath);

if same filename existing in your uploads folder. it will auto generate the

avatar_1.jpg, avatar_2.jpg, avatar_3.jpg, ans so on ..

Upvotes: 1

sandip
sandip

Reputation: 3289

It seem you have problem in genetaing random numbers you can try this:

  $prefix = substr(str_shuffle("0123456789"), 0,3);
  $file1 = $prefix.'.'.end(explode('.',$_FILES['cover']['name']));  

the above $prefix will be like : any random 3 digits

Hope will help it!

Upvotes: 1

Mikhail Vladimirov
Mikhail Vladimirov

Reputation: 13890

If you store your users in database and there is integer user ID, you better use this user ID for file naming rather than separate incrementing counter.

Also you can look at existing files to find maximum existing number like this:

function getNextFileName ()
{
    $a = 0;
    $b = 2147483647;

    while ($a < $b)
    {
        $c = floor (($a + $b) / 2);
        if (file_exists ("$c.jpg")) $a = $c + 1;
        else $b = $c;
    }

    return "$a.jpg";
}

function saveAvatar ($avatar)
{
    for ($i = 0; $i < 16; $i++)
    {
        $name = getNextFileName ();
        $fd = fopen ($name, 'x');
        if ($fd !== FALSE)
        {
            fwrite ($fd, $avatar);
            fclose ($fd);
            return $name;
        }
    }
    return FALSE;
}

for ($i = 0; $i < 20; $i++)
    saveAvatar ("BlahBlahBlah$i");

Upvotes: 1

Zeddy
Zeddy

Reputation: 2089

create an XML file and store the count in there

<? xml version="1.0" ?>
<MyRootNode>
  <count>123</count>
</MyRootNode>

UPDATE

Update added after you added more code to your question.

Function Rands(FileExtension as string) as long
  '1 open xml file 
  '2 read counter in
  '3 increment counter
  '4 save value to back xml file
  '5 return incremented counter with the file extension passed attached on the end
  'This is in case a BMP GIF or PNG has been and not JPG
  ' SAMPLE filename 123.GIF
End Function

Upvotes: 0

kainaw
kainaw

Reputation: 4334

If (and this is a big IF) your server supports file locking, you can reasonably ensure you have a unique incrementing ID with:

function get_avatar_id()
{
    $lockfile = fopen("avatar_id_lock_file","a");
    if(flock($lockfile, LOCK_EX)) // Get an exclusive lock to avoid race conditions
    {
        $avatar_id = intval(file_get_contents("avatar_id"); // Assumes you made it and put a number in it
        $avatar_id++;
        file_put_contents("avatar_id", $avatar_id);
        flock($lockfile, LOCK_UN);
        fclose($lockfile);
        return $avatar_id;
    }
    else
    {
        //What do you want to do if you can't lock the file?
    }
}

Upvotes: 0

Related Questions