Getting errors after form submit – WordPress

I have a simple form that adds a new post and sets a featured image. I am trying to clear the form using this: header("Location: $_SERVER[PHP_SELF]"); but I get a “headers already sent” error message and an “undefined index” after the page reloads.

Notice: Undefined index: attach in /var/www/vhosts/smoige.com/jobs/wp-content/themes/twentyfourteen/page-templates/upload.php on line 20 Warning: Cannot modify header information - headers already sent by (output started at /var/www/vhosts/smoige.com/jobs/wp-includes/post-template.php:478) in /var/www/vhosts/smoige.com/jobs/wp-content/themes/twentyfourteen/page-templates/upload.php on line 53

 <?php
/**
 * Template Name: Submit
 *
 * @package WordPress
 * @subpackage Twenty_Fourteen
 * @since Twenty Fourteen 1.0
 */
get_header(); ?>

   <div id="nav-submit-form" style="margin: 0 0 0 333px;">
<span class="nav-submit-form">
    <?php 
    if ( is_user_logged_in() ) {

    $current_user = wp_get_current_user();

      if(isset($_POST['submit'])) {

              $filename = $_FILES['attach']['name'];

              $new_post = array(
                  'ID' => '',
                  'post_author' => $current_user->ID, 
                  //'post_category' => array(3322),
            'tags_input' => "",
                  'post_title' => wp_strip_all_tags( $_POST['post_title'] ),
                  'post_status' => 'publish'
                );

                $post_id = wp_insert_post($new_post);
                $post = get_post($post_id);
                $new_post = $post->ID;

             if (!function_exists('wp_generate_attachment_metadata')) {
                    require_once(ABSPATH . "wp-admin" . '/includes/image.php');
                    require_once(ABSPATH . "wp-admin" . '/includes/file.php');
                    require_once(ABSPATH . "wp-admin" . '/includes/media.php');
             }
                     if ($_FILES) {
                          foreach ($_FILES as $file => $array) {
                              if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) {
                                  return "upload error : " . $_FILES[$file]['error'];
                              }
                              $attach_id = media_handle_upload( $file, $new_post );
                          }

                    }
                    if ($attach_id > 0){
                        //and if you want to set that image as Post  then use:
                        update_post_meta($new_post,'_thumbnail_id',$attach_id);
                    }
              header("Location: $_SERVER[PHP_SELF]");
        }

?>
      <form method="post" enctype="multipart/form-data" action="" id="upload-form">
          <input type="text" name="post_title" value="Image Name" size="45" id="input-title"/>
          <input type="file" name="attach" id="image" />
          <input id="submitButton" class="subput" type="submit" name="submit" value="Add"/>
      </form>

<?php } else {
        echo 'Welcome, visitor!';
    }

?>
</span>
 </div><!-- #nav-submit-form -->

<?php get_sidebar(); get_footer(); ?>

Related posts

Leave a Reply

3 comments

  1. Header already sent:

    For the “header already sent” error, you cannot modify the header if any input was already sent to the browser (an HTML tag, something with header(), a space at the beginning of the file)…

    So, lets say that you output something to the user with echo(‘hello there’). Then, try to redirect the user with header(‘Location: …’), it won’t work.

    The function header has to modify the HTTP header to redirect the user.

    The “echo” sent the word “hello there” to the user along with the HTTP header. nothing can leave the server to a browser if it doesn’t have that HTTP header, so PHP just added one.

    After that, you try to modify it with header(‘Location’);. Well PHP will tell you “I’m sorry, but you ask me to modify the header and I already sent it for the page… too bad”.

    I wrote an article about it just last week: http://www.mogosselin.com/warning-cannot-modify-header-information-headers-already-sent-by/ if you need more information.

    To find where the problem is about the Header already sent

    Check the error message

    Headers already sent by (output started at
    /var/www/vhosts/smoige.com/jobs/wp-includes/post-template.php:478)
    in
    /var/www/vhosts/smoige.com/jobs/wp-content/themes/twentyfourteen/page-templates/upload.php
    on line 53

    Something in the script post-template.php @ line 478 tried to output something but the headers were already sent.

    The header was sent by the line #53 in upload.php.

    Undefined Index:

    For the undefined index, it means that the INDEX you try to use in an array doesn’t exists. for example:
    $_POST[‘NAME’];
    NAME is the INDEX.

    If you try this:
    $var = $_POST[‘FDASFSDA’];
    You’ll get an “undefined index” because FDASFSDA wasn’t set in $_POST

  2. I used your code, and this works with add of this row at start of file (maybe your path is different):

    include("../../../wp-load.php");
    

    The complete code:

    <?php
    include("../../../wp-load.php");
    
    if ( is_user_logged_in() ) {
    
        $current_user = wp_get_current_user();
    
          if(isset($_POST['submit'])) {
    
                  //$filename = $_POST['attach'];
                  $filename = '';
                  if(isset($_FILES['attach'])) {
                                    $filename = $_FILES['attach']['name'];
                                }
    
                  $new_post = array(
                      'ID' => '',
                      'post_author' => $current_user->ID,
                      //'post_category' => array(3322),
                'tags_input' => "",
                      'post_title' => wp_strip_all_tags( $_POST['post_title'] ),
                      'post_status' => 'publish'
                    );
    
                    $post_id = wp_insert_post($new_post);
                    $post = get_post($post_id);
                    $new_post = $post->ID;
    
                 if (!function_exists('wp_generate_attachment_metadata')) {
                        require_once(ABSPATH . "wp-admin" . '/includes/image.php');
                        require_once(ABSPATH . "wp-admin" . '/includes/file.php');
                        require_once(ABSPATH . "wp-admin" . '/includes/media.php');
                 }
                         if ($_FILES) {
                              foreach ($_FILES as $file => $array) {
                                  if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) {
                                      return "upload error : " . $_FILES[$file]['error'];
                                  }
                                  $attach_id = media_handle_upload( $file, $new_post );
                              }
    
                        }
                        if ($attach_id > 0){
                            //and if you want to set that image as Post  then use:
                            update_post_meta($new_post,'_thumbnail_id',$attach_id);
                        }
                  header("Location: $_SERVER[PHP_SELF]");
            }
    
    ?>
          <form method="post" enctype="multipart/form-data" action="" id="upload-form">
              <input type="text" name="post_title" value="Image Name" size="45" id="input-title"/>
              <input type="file" name="attach" id="image" />
              <input id="submitButton" class="subput" type="submit" name="submit" value="Add"/>
          </form>
    
    <?php } else {
            echo 'Welcome, visitor!';
        }
    
    ?>
    

    Enjoy your code! 🙂