未定义索引:图像和getimagesize:读取错误!在PHP中

时间:2014-06-29 14:11:05

标签: php

这是我将图像上传到数据库的代码。

的index.php:

<html>
<head>
<title>upload images to database</title>
</head>
<body>
<form action="index.php" method = "POST" enctype = "multipart/form-data">
File:
<input type= "file" name= "image">
<input type= "submit" value= "upload">
</form>
<?php
//connect to database
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("image") or die(mysql_error());
$file = '';
 $file= $_FILES['image']['tmp_name'];
 if(!isset($file))
 {
 echo "please select an image";
 }
 else
 {
$image = file_get_contents($_FILES['image']['tmp_name']);
$image_name = $_FILES['image']['name'];
$image_size = getimagesize($_FILES['image']['tmp_name']);
if($image_size ==FALSE)
{
echo "That's not an image";
}
else
    {
    if(!$insert = "INSERT INTO upload VALUES('','$image_name','$image')")
    {
    echo "Problem uploading image";
    }
    else{

    $lastid = mysql_insert_id();
    echo "Image upload.<p/>Your Image</p><img src=get.php?id=$lastid>";

    }
} 
 }

?>
</body>
</html>

get.php:

<?php
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("image") or die(mysql_error());
$id = addslashes($_REQUEST['id']);
$image = mysql_query("SELECT * FROM upload WHERE id=$id");
$image = mysql_fetch_assoc($image);
$image = $image['image'];
header("content-type: image/ipeg");
echo $image;
?>

我何时运行此代码,它显示为http://imgur.com/FGWTY23,在上传图像之前显示未定义索引:图像...

任何人都可以帮忙解决我的问题吗?

感谢!!!

1 个答案:

答案 0 :(得分:1)

您需要在最初显示表单或提交表单时测试脚本是否正在运行:

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    ... all the code that processes the form
}
?>

此外,您需要在将用户输入插入查询时转义用户输入:

$image = mysql_real_escape_string(file_get_contents($_FILES['image']['tmp_name']));
$image_name = mysql_real_escape_string($_FILES['image']['name']);

这对$image尤为重要,因为它是二进制数据。

您错过了对mysql_query()的调用以执行INSERT。它应该是:

if(!$insert = mysql_query("INSERT INTO upload VALUES('','$image_name','$image')"))
{
    echo "Problem uploading image: ".mysql_error();
}
else{

    $lastid = mysql_insert_id();
    echo "Image upload.<p/>Your Image</p><img src=get.php?id=$lastid>";

}

如果你切换到PDO或mysqli扩展,并使用准备好的查询会更好。不推荐使用mysql扩展。