Can I set first header as ("Access-Control-Allow-Origin: *") then switch to header("HTTP/1.1" . $errCode . $errMsg) if an error comes up before kill() the page?
My code current look like this:
<?php
header ("Access-Control-Allow-Origin: *");
// other things go here
function handleError ($errMsg, $errCode) {
header("HTTP/1.1" . $errCode . $errMsg);
die();
}
?>
Yes you can.
In your case, both headers will be sent.
But remember that no output should be sent before you call header() in your error handler.
Related
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
....
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
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.
$result = $mail->send($recipient, $headers, $html);
if($result === 1)
{
$report= "1";
header("Location: objednavka.php?reaction=".$report);
//echo("Your message has been sent!");
}
else
{
$report= "2";
header("Location: objednavka.php?reaction=".$report);
//echo("Your message was not sent: " . $result);
}
if this mail function runs down the if statement decide that if it was successfull or not. If I use the echo() part it writes that Your message has been sent. But if I want to redirect the user to another page it doesnt work. Why? How can I call the header function successfully?
From PHP - header():
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.
You forgot to set a corresponding status code (header())
header("Location: objednavka.php?reaction=$report", true, 301);
<?php
ob_start();
echo "<body><p>Hello "
if ($condition) {
header( "Location: http://www.google.com/" );
exit;
}
echo " World!</p></body>";
ob_end_flush();
?>
When $condition is true I get this:
<body>Hello
What I want is when $condition will be true then go to Google!!!
I don't know what is happening, can you explain or give me a solution!?
Thanks.
Just add ob_end_clean(); before the header call.
Everything should work, just put an ; after echo "<body><p>Hello" and you will be fine..
If I were you, I would have started what might go wrong first then do the processing.
An example
$exit_condition_1 = some_value1;
$exit_condition_2 = some_value2;
if($exit_condition_1 == false){
//Redirect
//Exit
}
if(!$exit_condition_2){
//Redirect
//Exit
}
//start the buffer ob_start()
//show some HTML
//flash the buffer ob_end_clean()
there is no point of starting the buffer then if something goes wrong close it and redirect. Just do value testing at the begining then process the request.
An example: lets say that you want to view a product's info and you have a function that will do that
function view_product($product_id){
if(!$product = getProductById($product_id)){
//product does not exist, redirect
}
if(the user does not have enough access rights){
//show a message maybe
//redirect
}
//everything is alright then show the product info
}
To resolve a similar situation where a function was using ob_start() and there was header("Location: http://www.example.com"); after that but erring "already sent...", I replaced the header(... call with
echo "<script> window.location.href = 'https://www.example.com' </script>"
and it worked in that particular case (all that was needed was a just page redirect anyway).