PHP不上传图像,但mySQL查询更新

时间:2013-01-21 04:01:45

标签: php mysql

我正在创建一个基本上有图片上传的博客。

这是我的add_post函数:

function add_post($title, $txt_content, $img_content, $tags, $file_temp, $file_extn){
    $title = mysql_real_escape_string($title);
    $txt_content = mysql_real_escape_string($txt_content);
    $tags = mysql_real_escape_string($tags);
    $file_path = 'simpleblog/resources/images/'.  substr(md5(time()), 0, 20) . '.' . $file_extn;
    move_uploaded_file($file_temp, $file_path);

    mysql_query("INSERT INTO `posts` SET
                        `tag_id` = '$tags',
                        `title` = '$title',
                        `txt_content` = '$txt_content',
                        `img_content` = '". mysql_real_escape_string($file_path) ."',
                        `date_posted` = NOW()");
}

这是add_post.php

的php脚本
<?php
include 'resources/init.php';

    if (isset($_FILES['img_content']) === true){
    if(empty($_FILES['img_content']['name']) === true){
        echo '<script type = "text/javascript">window.alert("Please pick a file!");</script>';
    }   else    {
        $allowed = array('jpg','jpeg','gif','png');
        $file_size = $_FILES['img_content']['size'];
        $file_name = $_FILES['img_content']['name'];
        $file_extension= explode('.', $file_name); 
        $file_extn= strtolower(end($file_extension));
        $file_temp = $_FILES['img_content']['tmp_name'];

        $title = $_POST['title'];
        $txt_content = $_POST['txt_content'];
        $tags = $_POST['tags'];

        if(in_array($file_extn, $allowed) === true && isset($_POST['txt_content']) === true){
            add_post($title, $txt_content, $tags, $file_temp, $file_extn);

            $post_id = mysql_insert_id();
            header("Location: index.php?post_id=" . $post_id);
            exit();
        }else if (in_array($file_extn, $allowed)=== false){
            echo '<script type = "text/javascript">window.alert("The only file type allowed are .jpg, .gif, .png");</script>';
        }
    }
}
?>

使用图像文件的名称更新mySQL数据库。但是,它没有将上传的文件移动到simpleblog/resources/images/ 有什么问题?

1 个答案:

答案 0 :(得分:0)

首先,这种类型检查不对:

 $file_name = $_FILES['img_content']['name'];
 $file_extension= explode('.', $file_name); 
 file_extn= strtolower(end($file_extension));

如果我上传名为image.php.jpg的文件,您的支票会说这是一张图片,但我发送了php文件,可以将此文件作为php文件请求。

在第二个,你的函数add_post有参数$img_content,但在函数调用中你忽略它:

 add_post($title, $txt_content, $tags, $file_temp, $file_extn);

move_uploaded_file 函数中的文件路径必须包含您的站点根路径