Jump to content

Renaming uploaded image files


lobski

Recommended Posts

I'm looking to find out how to rename uploaded image files, into "img_1" "img_2" and so on.

 

Here is my code:

 

<title>Finished!</title>
<?php
$target_path = "uploads/";

if(getimagesize($_FILES['uploadedfile']['tmp_name'])) {




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

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
    echo "Upload successful. The link to your image is: http://absolutely-corrupt.com/" .$target_path . "<br />" ."<br />". "Signature code: <FONT size=4>[img=http://absolutely-corrupt.com/" . "$target_path" . "<FONT size=4>]";
} else{
    echo "There was an error uploading the file, please try again!";
   }

} else {
  die("You may only upload image files!");
}
?>

Link to comment
https://forums.phpfreaks.com/topic/116369-renaming-uploaded-image-files/
Share on other sites

if you're storing image upload details in a database - you can use AutoIncrement to generate a unique ID for every new record - then use that number as your filename.

 

 

Unfortunately, I am not. What can I do to implement a simple renaming feature to my current code?

 

 

The renaming bit is easy - its how you're going to get a unique ID which is tricky part.  To rename it, simply use $target_path . "/yourfilenamehere.xxx" when using move_uploaded_file.  You could update a 'counter' file or something to store the last ID but DB is safer.

 

Hows about this instead (assuming you'll never remove files from this directory)....

 

$dir = "/myfiledirectory";
$dh  = opendir($dir);
$totalfiles = 0;
while (false !== ($filename = readdir($dh))) {
    if ($filename != "." && $filename != "..")
    {
        $totalfiles++;
    }
}

 

The above will give you the total files (variable $totalfiles) in the directory, which you could use as your ID.  As long as no files are removed, this will work.  DB is still the way to go though.

Hows about this instead (assuming you'll never remove files from this directory)....

 

$dir = "/myfiledirectory";
$dh  = opendir($dir);
$totalfiles = 0;
while (false !== ($filename = readdir($dh))) {
    if ($filename != "." && $filename != "..")
    {
        $totalfiles++;
    }
}

 

The above will give you the total files (variable $totalfiles) in the directory, which you could use as your ID.  As long as no files are removed, this will work.  DB is still the way to go though.

 

Hmm, I'm not quite sure where to insert this into my code.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.