从照片上传会话创建user_id?

时间:2012-12-16 14:07:01

标签: php mysql image upload

我正在使用这个php照片上传脚本将图像存储到我的数据库中。

我的数据库有三列:'user_id''name''image'

一切正常。图像已上传,但目前它没有存储user_id,我想尝试制作它,以便当用户点击上传时,它会使用会话ID来存储他们的user_id。

我通过将这两个函数添加到原始的mysql查询中来实现它:

(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>

3 个答案:

答案 0 :(得分:0)

您忘记启动PHP session_start(),它启动会话功能。你还必须在某处设置$ _SESSION ['user_id']。

更改为此代码:

<?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>

如果这不起作用,您可以将其添加到session_start:

上方
session_save_path("tmp");

请记住使用chmod 777在名为“tmp”的目录中创建一个文件夹。

如果您想测试会话是否有效,请执行以下操作:

<?php
session_start();

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

var_dump($_SESSION);
?>

希望它有所帮助!

答案 1 :(得分:0)

if(!$insert = mysql_query ("INSERT INTO  ptb_img_uploads (user_id, image, name) VALUES ('".$_SESSION['user_id']."', '$image', '$image_name')"))

答案 2 :(得分:0)

您必须先启动会话。在session_start();.之后回显$ insert;并将查询粘贴到mysql中并检查错误。