Header already sent after form redirect - php

Header already sent after form submission, I'm using a redirect to take my form elements to a new page to process them, but i'm getting the header Headers ALready Sent error and I cannot see why.
Is there an better cleaner way to do this?
if(isset($_POST["associate"])) {
$partner = $_POST['partner'];
$location = $_POST['location'];
$redirect = plugins_url() . "/myremovalsquote/inc/associate.php?partner=" . $partner . "&location=" . $location . "";
header('Location: '.$redirect);
} else {
echo 'Failed';
}

Are you using wordpress? Than the problem is maybe caused by plugins_url (). When the error still occurs please double check that there is no data sent to the client (e.g <html> or even a whitespace) before header () is used.

Related

will header () works inside function after HTML

I understand that there needs to be no output before header () even a space.
I have the below code to get the current URL:
$url = 'https://' . $_GET['SERVER_NAME'] . $_GET['REQUEST_URI']
If I use header ( "Location: $url" ) on the first line of the page, I think it might cause an infinity redirecting loop?
But what if I put it in a function and call it when a form is submitted like the below?
<form><input type="submit"></form>
<?php
$url = 'https://' . $_GET['SERVER_NAME'] . $_GET['REQUEST_URI']
function send () {
header ( "Location: $url" );
}
?>
Note that the function is after the HTML but header () is in a function. Remember there needs to be no output before header (), so will this work, and does it cause an error?
Because if it's not in a function, assume it looks like this, for sure it gonna cause an error, right?
<form><input type="submit"></form>
<?php
$url = 'https://' . $_GET['SERVER_NAME'] . $_GET['REQUEST_URI']
header ( "Location: $url" );
?>
This will fail, because the header() command does not run when you submit the form, even if you place it inside a JavaScript function.
PHP always runs on the server, not in the client. Everything it does happens before the client sees the response.
Header() must come first because it is a function like echo() that adds to the response that is sent to the client. Think of header ( "Location: $url" ); as being similar to echo "Header: Location: $url"; that just adds on to whatever else you have already written out for the page. (It isn't really an echo since it writes headers outside of the page body)
Note that you can have php code that does not generate output before a header() command. This is fine:
<?php
$person = "Tad Person";
$address = "100 Place Lane";
if ($person == "Tad Person")
{
header('Location: tads_own_page.php');
exit;
}
// else: the page for everyone except tad
....

PHP $_SESSION not working in function

Firstly, I have searched many threads and topics and they all keep saying its function placement but thus far I do not see a issue with my placement. I am desperate to get this is working because I am SICK of looking at 50+ extra lines of repetitive code.
resetpassword.php (RELEVANT CODE):
<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/php/security/sslcheck.php';
$ResetID = $_GET["ID"];
session_start();
require_once $_SERVER['DOCUMENT_ROOT'] . '/php/functionality/error.php';
print_r(array_values($_SESSION));
if(empty($ResetID) && !isset($_SESSION["ERR"]) && !isset($_SESSION["ERR_MSG"])) {
$ResetPassword = "REQUEST";
if(isset($_POST["email-search"]) && !empty($_POST["email-search"])) {
require_once $_SERVER['DOCUMENT_ROOT'] . '/php/functionality/users/request.php';
// Start Request Process
$Request = RequestPasswordReset($_POST["email-search"]);
if($Request === "USER_NOT_FOUND") {
DisplayError("Password Reset Request Failed", "The specified email is not tied to any accounts in our system.", "/account/resetpassword.php");
} else if ($Request === "MAIL_FAILURE") {
DisplayError("Password Reset Request Failed", "Failed to email you the password reset email.", "/account/resetpassword.php");
} else {
DisplayError("Password Reset Request Success", "We have sent a email that contains a link to reset your password.", "/account/resetpassword.php");
}
}
More Relevant Code
<?php
if (isset($_SESSION["ERR"]) && isset($_SESSION["ERR_MSG"])) {
echo '<div id="resetPasswordStatus">';
echo '<h4>' . $_SESSION["ERR"] . '</h4>';
echo '<p>' . $_SESSION["ERR_MSG"] . '</p>';
echo '</div>';
session_destroy();
}
?>
error.php (ALL CODE):
<?php
session_start();
function DisplayError($title, $body, $returnlink) {
$_SESSION["ERR"] = $title;
$_SESSION["ERR_MSG"] = $body;
header("Location: " . $returnlink);
}
?>
I have experiment in many ways with my placement of require_once of error.php, but have found no luck. I understand $_SESSION is a superglobal and require or require_once copy the code right into place where required. However even copying error.php manually into resetpassword.php I was unable to get the function to work. Thank you guys for your help as it really means a lot!
The expected output is after the callback after the request for a password reset, is the alert to display. Code for this alert can be seen under More Relevant Code.
Solution:
In the error.php if you add exit(); after the header redirect it allows for PHP to pause execution while the redirect occurs which prevents the error displaying code from running its code and then wiping the session which leaves the redirect empty in terms of sessions.
You are calling the function after the if statement empty($ResetID)
Your function isn't running if the $_GET['ID'] is not empty so change it to !empty($ResetID)

PHP Unable to handle request

Here is my code, not too sure why it doesn't work but it cannot be processed. I can process phpinfo() correctly.
<?php
include("tools.php");
$username = $_POST["uname"];
$email = $_POST["email"];
$pasword = $_POST["pword"];
if(isset($username) and isset($email) and isset($password)){
if(add_user_database($username, $email, $password) == TRUE){
echo "You've been added!!!";
header("location:login.php");
}else{
echo "<script>alert('Error has occurd please contact " .
"support or try again later');</script>";
header("location:register.php");
}
}else{
echo "<script>alert('Please fill in all forms');</script>";
header("location:register.php");
}
?>
From the php docs,
"Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file."
You shouldn't need the echo things there, if you really wanted those messages, you could set them as $_SESSION('statusMessage'); and then on the redirect page check if it is set, echo out something to show it, and set them to undefined.
Also, please please please make sure that input gets sanitised in add_user_database()!!
EDIT:
Helpful hints
In the check login script:
if(add_user_database()){
$_SESSION['addUserStatus'] = "Success, you have been added, woo!";
header("Location: someOtherPage.php");
}else{
$_SESSION['addUserStatus'] = "Error! Please contact support for assistance!");
header("Location: someOtherPage.php");
}
In the some other page:
if(isset($_SESSION['addUserStatus']){
echo "<script>showLoginMessage('" . $_SESSION['addUserStatus'] . "')</script>";
$_SESSION['addUserStatus'] = undefined;
}
Header already sent error
look at
http://php.net/manual/en/function.header.php
Remember that header() must be called before any actual output is sent

How to avoid the catch-22 of PHP session_start() vs "headers already sent" warning?

I have an application that works TOTALLY fine on my local server.
It requires two things:
An active $_SESSION so that a number of key data elements are available on every page. (Stuff like user_id, and user_role.)
A couple of "require_once()" calls at the top of my pages, so that I have some constants available and standard messages available and the same header on every page.
Again, on my local server (using php 5.6), this is all fine and dandy.
On my HOST server (also using php 5.6), however, I have a catch-22:
If I call "session_start()" on each of my pages, I get a "headers already sent" warning, due to my use of "require_once()".
If I do NOT call "session_start()" on each of my pages, the $_SESSION variable is empty when it gets to the next page.
The only ideas I have seem very bad:
Don't use sessions and pass all my data in the URL. This seems insecure, clumsy, and like bad practice.
Don't use "require_once()", which seems really stupid as I'll have duplicate code all over the place.
Any ideas about what I should do?
I am on a shared server, so I don't think I can modify the php.ini file. And my host company, who has been very helpful about any other issue, has been totally silent over the past 2 weeks as I've sent them questions about this.
I have created a very simple example that shows the issue. Probably the most informative bit is in the comments for "firstpage.php", specifically the "if" statement under the comment "Under what circumstances is session being started".
Here is the index page (called mytestindex.php).
<?php
// Make sure $_SESSION array is available.
session_start();
//***************************************************
// Print to the screen information about the session
// This sends headers on the host server.
//***************************************************
require_once("printsessioninfo.php");
// Set SESSION variable for later use on other pages
$_SESSION['emp_id'] = 100;
echo "\n\nThe employee id stored in SESSION is: " . $_SESSION["emp_id"] . "\n\n";
// Open next page when button clicked.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Set the name of the page we are going to next
$filename = "firstpage.php";
// ***************************************************************************************************
// If headers have't been sent (seems to depend on php.ini settings), simply call the header function
// This is the code that has worked on my local machine for years.
// ***************************************************************************************************
if (!headers_sent()) {
$redirect_to = "Location:" . $filename;
exit(header($redirect_to));
// *******************************************************************************************************************
// If headers have already been sent (require_once() above will do that), using the header function
// will generate a "headers have already been sent" warning on the host server. So need to use Javascript to avoid that.
// ********************************************************************************************************************
} else {
echo " Opening page with Javascript. ";
$code = '<script type="text/javascript">';
$code = $code . 'window.location.href="' . $filename . '";';
$code = $code . '</script>';
$code = $code . '<noscript>';
$code = $code . '<meta http-equiv="refresh" content="0;url=' . $filename . '" />';
$code = $code . '<noscript>';
echo $code;
exit;
}
}
?>
<div>
<form action="mytestindex.php" method="post">
<button type="submit">Go to first page</button>
</form>
</div>
Here is the page it links to (called firstpage.php):
<?php
/* First page */
//***************************************************
// Print to the screen information about the session
// This sends headers on the host server.
//***************************************************
require_once("printsessioninfo.php");
//***********************************************************************
// Print out other information before session started again on this page
if (headers_sent()) {
echo "Headers have already been sent.\n";
} else {
echo "No headers have been sent.\n";
}
if (isset($_SESSION)) {
echo "Session variable exists.\n";
} else {
echo "Session variable does not exist.\n";
}
//*****************************************************
// Under what circumstances is session being started
// and does it cause a "headers already sent" warning?
//*****************************************************
// THIS check is what works on my local machine, with no warnings about headers being sent.
if ( (!isset($_SESSION)) && (!headers_sent()) ) {
echo " START SESSION: session var is not set AND headers have not been sent.";
session_start();
} elseif (session_status == PHP_SESSION_NONE) {
echo " START SESSION: session does not exist";
session_start();
// THIS check is what works on my host server, BUT throws the warning about headers being sent.
} elseif (!isset($_SESSION)) {
echo " START SESSION: session var is not set";
session_start();
} else {
echo " No need to start a new session";
}
//******************************************************************************
echo "\n\n The employee id stored in the session variable is: " . $_SESSION["emp_id"] . " .";
if (session_status() == PHP_SESSION_ACTIVE) {
echo "\n\n\n NOW Session is active!";
}
?>
Here is a snippet of code that prints out some session info, so I have demonstrate how "require_once()" affects things (called printsessioninfo.php):
<?php
// Print session info
echo "<pre>";
$sessionfile = ini_get('session.save_path') . '/' . 'sess_'.session_id();
echo 'session file: ' . $sessionfile . ' ';
echo 'size: ' . filesize($sessionfile) . "\n\n\n";
if (session_status() == PHP_SESSION_NONE) {
echo "Session does not exist!\n";
} elseif (session_status() == PHP_SESSION_DISABLED) {
echo "Session is disabled!\n";
} elseif (session_status() == PHP_SESSION_ACTIVE) {
echo "Session is active.";
}
?>
I was able to fix this (thank you "mister martin"), by moving the code for "session_start()" into my config.php file, making sure it was the VERY FIRST bit of code.
Then for every page in the application I made sure this was the first line of code:
<?php
require_once("config.php");
And that did the trick, for both development and host servers.
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
Explanation required as it seems it wasn't clear enough (??):
If the status of the session is NONE then start it.
http://php.net/manual/en/function.session-status.php
http://php.net/manual/en/session.constants.php
Also this should be called BEFORE any require or require_once

Remove query from URL before $_SERVER['HTTP_REFERER']

On success or fail of a form submission I am using the following. The resulting url appears as http://example.com/directory/?success=false
The problem I am having is that when a user attempts to submit the form again after correcting validation error the resulting url becomes http://example.com/directory/?success=false?success=true - I need it to clear any querystring first. How could I do this?
PHP
# Redirect user to error message
header('Location: ' . $_SERVER['HTTP_REFERER'] . '?success=false');
}
You could use explode() to break the $_SERVER['HTTP_REFERRER'] string to get rid of the existing $_GET arguments:
$bits = explode('?',$_SERVER['HTTP_REFERRER']);
$redirect = $bits[0];
# Redirect user to error message
header('Location: ' . $redirect . '?success=true');
How about something like this:
$i = strchr($_SERVER['HTTP_REFERER'], "?");
$address = substr($_SERVER['HTTP_REFERER'], 0, $i);
header('Location: ' . $address . '?success=false');

Categories