1

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(); ?>
0

3 Answers 3

2
$filename = $_POST['attach']; 

should be

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

http://www.php.net//manual/en/features.file-upload.post-method.php

Sign up to request clarification or add additional context in comments.

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

4 Comments

can this be causing the error? get_header(); i have it above the code I posted in my question.
I think get_header() is a wordpress function: codex.wordpress.org/Function_Reference/get_header That includes a header of a theme. This isn't the same as the HTTP header. Or did you mean get_headers() (with an S)?
no. the wordpress function get_header() that s what I have above the code. i just added all the code ... can you see something that can be changed?
I added a precision to my post. Check the error message to find out where the output was done (what sent the header to the browser) and what tried to change the header after PHP sent it.
0

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! :)

1 Comment

I find it really weird that your answer and mine were downvoted without any "comment" nor explanation. :|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.