Kevin Reeves Kevin Reeves - 3 months ago 13
MySQL Question

creating user_id from session on photo upload?

Hi i'm using this php photo upload script that stores an image into my database.

My database has three columns: 'user_id' 'name' 'image'

It all works fine. the image is uploaded but at the moment it doesn't store the user_id and i want to try and make it so that when the user hits upload it uses their sesion id to store their user_id.

I've had a go at it by adding these two functions to the original mysql query:

(user_id, image, name)
'".$_SESSION['user_id']."',


<html>
<head>
<title>Upload Image</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="image">
<input type="submit" value="Upload">
</form>
<?php
include("includes/_config/connection.php");

// file properties
$file = $_FILES ['image'] ['tmp_name'];

if (!isset($file))
echo "";
else {
$image = addslashes (file_get_contents ($_FILES ['image']['tmp_name']));
$image_name = addslashes ($_FILES['image']['name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);

if ($image_size == FALSE)
echo "That's not an image.";
else {
if (!$insert = mysql_query ("INSERT INTO ptb_img_uploads (user_id, image, name) VALUES ('', '".$_SESSION['user_id']."', '$image_name','$image')"))
echo "There was a problem sending the image.";
else
echo "Your image was successfully uploaded.";
}
}
?>
</body>
</html>

Answer

You forgot to start PHP session_start(), which starts the session function. You also have to set the $_SESSION['user_id'] somewhere.

Change to this code:

<?php
session_start();
?>
<html>
<head>
    <title>Upload Image</title>
</head>
<body>

<form method="post" enctype="multipart/form-data">
    <input type="file" name="image">
    <input type="submit" value="Upload">
</form>

<?php
include("includes/_config/connection.php");

// file properties
$file = $_FILES ['image'] ['tmp_name'];

if (!isset($file))
{
    echo "";
}
else
{
    $image = addslashes (file_get_contents ($_FILES ['image']['tmp_name']));
    $image_name = addslashes ($_FILES['image']['name']);
    $image_size = getimagesize($_FILES['image']['tmp_name']);

    if($image_size == FALSE)
    {
        echo "That's not an image.";
    }
    else
    {
        if(!$insert = mysql_query ("INSERT INTO  ptb_img_uploads (user_id, image, name) VALUES ('".$_SESSION['user_id']."', '$image_name','$image')"))
        {
            echo "There was a problem sending the image.";
        }
        else
        {
            echo "Your image was successfully uploaded.";
        }
    }

}
?>
</body>
</html>

If that doesn't work, you could add this right above session_start:

session_save_path("tmp");

Remember to create a folder in your directory named "tmp" with chmod 777.

If you want to test if your session works, do this:

<?php
session_start();

$_SESSION['test_session']="this is a test session";

var_dump($_SESSION);
?>

Hope it helps!