pro78 pro78 - 3 years ago 152
PHP Question

PHP CMS - Add image is not working

I am creating a simple CMS and I would like the users to be able to upload an image in their posts. The form is working properly besides the image. For some reason I get this message 'Notice: Undefined index: post_img'. Can someone help me solve this?

Thanks.

Code:

<form method="post" action="add_post.php">
<?php
if(isset($_POST['add_post'])) {

$add_title = $_POST['post_title'];

$post_img = $_FILES['post_img']['name'];
$post_img_temp = $_FILES['post_img']['tmp_name'];


$add_content = $_POST['post_content'];

move_uploaded_file($post_img_temp, "images/$post_img");

$add_post_query = "INSERT INTO posts (post_title, post_img, post_content) ";
$add_post_query .= "VALUES ('$add_title', '$post_img', '$add_content') ";

mysqli_query($connection, $add_post_query);
}

?>


<div class="form-group">
<label for="post-title">Title</label>
<input type="text" name="post_title" class="form-control">
</div>
<div class="form-group">
<label for="post-img">Image</label>
<input type="file" name="post_img" class="form-control">
</div>
<div class="form-group">
<label for="post-content">Content</label>
<textarea name="post_content" class="form-control"></textarea>
</div>
<div class="form-group">
<input type="submit" name="add_post" class="btn btn-primary" value="Add Post">
</div>
</form>

Answer Source

You need to properly place your form tag. Also you need to set the form to accept files by adding the enctype attribute to the form tag

 <form method="post" enctype="multipart/form-data">
<div class="form-group">
            <label for="post-title">Title</label>
            <input type="text" name="post_title" class="form-control">
        </div>
        <div class="form-group">
            <label for="post-img">Image</label>
            <input type="file" name="post_img" class="form-control">
        </div>
        <div class="form-group">
            <label for="post-content">Content</label>
            <textarea name="post_content" class="form-control"></textarea>
        </div>
        <div class="form-group">
            <input type="submit" name="add_post" class="btn btn-primary" value="Add Post">
        </div>
    </form>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download