PHP表单 - 上传图像以在新闻文章的评论功能上放置头像

时间:2014-03-13 15:22:30

标签: php sql image file

尝试制作一个简单的脚本来评论新闻文章,它正在为文本工作,但我希望用户能够提交图像以用作图标或头像。这是表单字段:

             <form action= "../create_comment.php" method="post" name="comments_form" enctype="multipart/form-data">
            <div>
              <label>Name<span>*</span></label>
              <input name="name" type="text" value=" ">
            </div>
            <div>
              <label>Email<span>*</span></label>
              <input name="email" type="text" value=" ">
            </div>
            <div>
              <label>Your Comment<span>*</span></label>
              <textarea name="comment"> </textarea>
            </div>
            <div>
            <label>Add your avatar<span>*</span></label>
            <input name="file" type="file"  />
            <div>
            <input name="storyid" value="192837465" type="hidden">
            <input name="page_path" value="777776" type="hidden">
            <input type="submit" value="submit">
          </form>

并且表单指向此脚本:

    <?php
    $formats = array("gif", "jpeg", "jpg", "png");
    $temp = explode(".", $_FILES["file"]["name"]);
    $extension = end($temp);
    if ( $_FILES["file"]["size"] < 90000 && in_array($extension, $formats) ) {
        if ($_FILES["file"]["error"] > 0) {
            // something went wrong, display the error using; $_FILES["file"]["error"];
        } else {
            if ( !file_exists("avatars/" . $_FILES["file"]["name"] ) ) {
                move_uploaded_file($_FILES["file"]["tmp_name"], "avatars/" . $_FILES["file"]["name"]);
            }
        }
    }
    $tempLink = "http://www.website.com/avatars/" . $_FILES["file"]["name"];
    $page_path = $_POST['page_path'];
    $con=mysqli_connect
    ("","","","");
     // Check connection
     if (mysqli_connect_errno())
       {
       echo "Failed to connect to MySQL: " . mysqli_connect_error();
       }
     $sql="INSERT INTO comments (name, comment, email, storyid, entry_date)
     VALUES
     ('$_POST[name]','$_POST[comment]','$_POST[email]','$_POST[storyid]',now())";
     if (!mysqli_query($con,$sql))
       {
       die('Error: ' . mysqli_error($con));
       }
    header('Location: http://www.website.com/' . $page_path);
    mysqli_close($con);
    ?>

脚本运行完成但图像未保存到:

www.website.com/avatars/

所有其他表单数据插入SQL就好了。唯一的问题是图像。目标目录是chmod 0777。

1 个答案:

答案 0 :(得分:0)

以表格html添加

<form action="" method="post" enctype="multipart/form-data">