Hello,

I have been trying to set up this script for a charity website (animal sanctuary) in which members can upload a photo of their pets to the members log in area.

I have so far managed to get the basic script working but would like to give each image uploaded a unique ID.

Does anyone know how to do this?

This is my script that processes the upload:

<?php 

$rank_check = 1;

$page_title = "User Profile";

include "header.inc.php";

print"$openHTML";

//This is the directory where images will be saved 
$target = "photos/"; 
$target = $target . basename( $_FILES['photo']['name']); 

//This gets all the other information from the form 
$name=$_POST['name']; 
$email=$_POST['email']; 
$phone=$_POST['phone']; 
$pic=($_FILES['photo']['name']); 
$user_id=$_POST['user_id']; 
$profile_id=$_POST['profile_id']; 
$selected=$_POST['selected']; 



//Writes the information to the database 
mysql_query("INSERT INTO `employees` VALUES ('$name', '$user_id', '$profile_id', '$selected','$email', '$phone', '$pic')") ; 

//Writes the photo to the server 
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)) 
{ 

//Tells you if its all ok 
echo "<center>The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory.<p><center>Please click <a href=$base_url/user_photogallery.php?game=$game&user=$username>here</a> to go back to your photo edit page!"; 
} 
else { 

//Gives an error if its not 
echo "Sorry, there was a problem uploading your file."; 
} 
?>

Would be grateful for any advice or help

Thank you

Hi.

I see two simple ways to do that.

First, you could simply use the time() function to get the current time stamp and add that to the image name. You could even prefix it with a random number to reduce the chance of a collision.

Or, you could simply use the mysql_insert_id function to get the ID of the database row you store the image in. That should always be unique for each image.

thank you atli!

Where exactly would I add this within the code?

:>/

Thanks

You could change this line:

$target = $target . basename( $_FILES['photo']['name']);

To look like this:

$target = $target . time() "-". basename( $_FILES['photo']['name']);

Then you would get a file named something like 1234567-filename.jpg The number, generated by time() is a Unix time-stamp, which is the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).
Meaning that it will change ever second.

You could also use microtime() which also returns a Unix time-stamp, but includes microseconds, making it more unique.

add this before you upload your image into a folder...

$name=time();
$target = "photos/"; 
$target = $target .$name. basename( $_FILES['photo']['name']);

Hi.. can you please explain how to use the row ID approach for this? Thank you very much

Sure.

You simply move the $target assignment after the INSER query and use the ID from the mysql_insert_id function instead of time() in my previous example.

Like, for example:

mysql_query("INSERT INTO ...");
$target = 'uploads/' . mysql_insert_id() . "-" . $_FILE['field']['name'];
move_uploaded_file($_FILE['field']['tmp_name'], $target);

You would of course want to add a little validation/error-handling to that, but you get the idea.

This would give you files that started with a unique ID (the row's PK from the database) followed by the actual name of the image. E.g: 123-image_no_123.png .

Edited 6 Years Ago by Atli: Syntax errors. (Watching football while typing == syntax erros! xD)

That's perfect! Thank you very much.. Now I'll try the next step, try to retrieve the image when searching a column from that row. ;)

I'm sorry to bother again but I'm having difficulties making this piece of code correct. So here is my HMTL:

<form enctype="multipart/form-data" action="UT11.php" method="POST">
<input type="file" name="photo"/>
<input type="submit" value="Add"/>
</form>

And the php file:

<?php 
// Connect to Database 
mysql_connect(localhost, user, pass) or die(mysql_error()) ; 
mysql_select_db("thenNnow") or die(mysql_error()) ; 

// Writes information on the database 
mysql_query("INSERT INTO `thenNnow`.`User_Pic` ( `UP_ID`, `UPic`, `P_ID`, `O_ID`, `D_ID`, `K_ID`, `C_ID`) VALUES (  NULL , '$pic', NULL , NULL , NULL , NULL , NULL) ") ;

$target = "images/". mysql_insert_id() . ".jpg"; 
$pic=mysql_insert_id();
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)) 
{ 
echo "Your file ". $_FILES['photo']['name']. " has been uploaded!"; 
} 
else { 
echo "Sorry, there was a problem uploading your file."; 
} 
?>

The code is actually uploading a picture to the server with the name I desire. For example: A picture that will be place in the row ID number 5 is uploaded to the server with the name 5.jpg

My issue is, There's no record in the database, no name at all. I wrote

$pic=mysql_insert_id();

so the name in the Database is the same as the ID..

Anyway, another thing that I'm no able to do is allowing other formats besides .jpg

Can you please help with this? I've been around it for so long and I'm such a newbie in PHP... Thank you in advance

Can anyone help me with this ?

My issue is that I need the name of the uploaded picture and the reference to that picture in the database to be the same as the ID of that row.

In my particular example previously posted: I want the variable $pic to be the ID of the row.

If I place it before the INSERT there's no chance of retrieving the Id.
If I place it after the INSERT the variable $pic inserted will be blank.

My issue is that I need the name of the uploaded picture and the reference to that picture in the database to be the same as the ID of that row.

That doesn't really make sense. You want three fields in the same row to have the same value? That's pointless.
Surely I am misunderstanding you?

Anyways, this is how you would generally upload a picture to the file-system and store it's data in the database:

<?php
if(isset($_FILES['myfile']))
{
    if($_FILES['myfile']['error'] == 0)
    {
        // Fetch file info
        $name = mysql_real_escape_string($_FILES['myfile']['name']);
        $type = mysql_real_escape_string($_FILES['myfile']['type']);
        $size = (int)$_FILES['myfile']['size'];
        $tmp  = $_FILES['myfile']['tmp_name']; // No need to escape. Not going into the DB.
        
        // Create a list of valid file types, along with their extensions.
        $types = array( 'image/jpeg' => 'jpeg', 
                        'image/jpg' => 'jpg', 
                        'image/png' => 'png', 
                        'image/gif' => 'gif');
                        
        // Make sure the file is a valid type.
        if(in_array($type, array_keys($types))) 
        {
            // Insert into the database
            $sql = "INSERT INTO `mytable` (`name`, `type`, `size`)
                    VALUES ('{$name}', '{$type}', {$size})";
            $result = mysql_query($sql) or trigger_error(mysql_error(), E_USER_ERROR);
            
            // Verify that the query was successful
            if($result && mysql_affected_rows($result) == 1)
            {
                // Move the file into it's new location
                $newLocation = 'images/uploaded/' . mysql_insert_id() . '.' . $types[$type];
                if(move_uploaded_file($tmp, $newLocation))
                {
                    echo "File successfully uploaded to '{$newLocation}'";
                }
                else
                {
                    echo 'Failed to move the file to it\'s new location. Make sure PHP has proper file permissions.';
                }
                
            }
            else
            {
                echo 'Failed to insert into the database. Unkown error.';
            }
        }
        else
        {
            echo 'Invalid file type!';
        }
    }
    else
    {
        echo 'Upload failed. Error #' . $_FILES['myfile']['error'};
    }
}
else
{
    echo 'No file was uploaded.'
}
?>

Then you can display the images like so:

<?php
// Fetch the data for the last 10 pictures uploaded.
$sql = "SELECT `id`, `name`, `type`
        FROM `upload_table`
        ORDER BY `id` DESC
        LIMIT 10";
$result = mysql_query($sql) or trigger_error(mysql_query(), E_USER_ERROR);

// Display each picture
while($row = mysql_fetch_assoc($row))
{
    $extension = str_replace('image/', '', $row['type']);
    $src = "images/uploaded/{$row['id']}.{$extension}";
    
    echo "<img src="{$src}" alt="{$row['name']}" title="{$row['name']}"><br>"
}
?>

Hope that points you in the right direction.

for random name you can use rand function:

replace this line in your code :
$target = $target . basename( $_FILES);
with this :
$target = $target . basename( rand(1, 999).rand(1000,9999 ).rand(1, 999)."_".$_FILES);

and you can change this random values as you like in the same way you can use id or time() function.
Good Luck

This article has been dead for over six months. Start a new discussion instead.