will header () works inside function after HTML - php

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
....

Related

Can I have different headers for php code?

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.

Header already sent after form redirect

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.

headers already sent only in subdomain

I have a main webpage that logs in and redirects using header() without any problems.
I also have another webpage that would need to log in, so I made another login.php page for it.
Both webpages have the same structure, in fact I just copy-pasted the main webpage into the other webpage and changed var names, etc
If I log in in the main webpage everything is allright, no warnings. But if I log in in the other webpage I get the following warning:
Warning: Cannot modify header information - headers already sent by (output started at /home/aet/platform.corporativelines.com/themes/aet/main.php:12) in /home/aet/platform.corporativelines.com/pages/login.php on line 18
This is main.php:12
<title>AET | <?php print $title ?></title>
And this is login.php line 18
header("Location: /home");
The main webpage have the same in those lines, exactly the same but no warnings... Can someone tell me why?
Both webpages are in a subdomain, but main is just temporary, I'll move it when is finished. Maybe that have something to do... (If you want to visit, "pre" is the temporary subdomain)
The framework is the same for both webpages, the custom session start function have the domain set to ".domain.com" like says here.
PHP Code:
index.php (both websites):
ini_set('display_errors', '1');
//requires and initializations
$hasExpired = $web_user::sec_session_start();
$client = $web_user->login_check(); // FALSE OR CLIENT
$isLogged = false;
$includes1 = array(
'/pages' => $pages . 'pages.php'
);
if ($client != false) {
$isLogged = true;
$includes2 = array(
'/morepages' => $pages . 'morepages.php'
);
}
else {
$includes2 = array(
'/otherpages' => $pages . 'otherpages.php'
);
}
$includes = array_merge($includes1, $includes2);
$url = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
//some more security checks for url
$title = $lang->getW($url);
include('themes/aet/main.php');
main.php (both websites):
<?php
defined('_AET') or die();
?>
<!DOCTYPE html>
//html structure
<title>AET | <?php print $title ?></title>
//body
//main
<?php
$include = '/404';
if (array_key_exists($url, $includes)) {
$include = $url;
}
include($includes[$include]);
?>
login.php (both websites):
// login post, checks and call to function
if ($login_array[0] == "OK") {
header("Location: /home");
}
// login form html
I can say they are the same pages in both webpages.
EDIT: Sorry I have not been clear. In both websites I have ini_set('display_errors', '1'); In the main website I'm not getting any error plus the header() redirection is working fine. In the other website I'm getting the error, if I disable them, the error won't show but neither the redirection will work.
In main.php it looks like you are outputting php comments - check carefully if anything (including white space) is output from PHP before your DOCTYPE (i.e. the first line of HTML output).
If you have a PHP script that does this:
<?php
print "before headers: will cause a problem";
?>
// this will also cause text to be output
<!DOCTYPE html>
<html> ...
you will have a problem. If that is not the case, can you post the entire beginning of main.php.
The "problem" was (first) calling header() after output and (second) having output_buffering enabled.
To solve this, I just moved the login post script (and any other script that calls header()) to another file and include it in index.php before including the main.php (before the HTML/Dom output starts).
if ($url == '/login') {
include('pages/headers/login_post.php');
}
// now we can safely start the DOM output
include('themes/main.php');

How to redirect with header location in php when using ob_start?

<?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).

PHP - redirection under Chrome

I have a problem with the following code:
<?php
session_start();
require_once("config.php");
if(isset($_SESSION['location']) && !empty($_SESSION['location'])) {
$location = $_SESSION['location'];
$url = ABS_PATH . $location;
unset($_SESSION['location']);
header('Location: ' . $url);
}
The value of $url is:
http://www.domain.eu/somepage
and value passed to header() is:
Location: http://www.domain.eu/somepage
It is ok under Opera, IE (7,8,9) and Firefox but unfortunately it is not working under Chrome and I have no idea why. Mentioned code sample comes from file index.php and it is execuded every time You load a page. I have other file (display.php) to which I send url via AJAX request. File display.php sets value of $_SESSION['location'] and returns content of page. In browsers other than Chrome when I refresh page it redirects me to proper URL. During debuging I noticed that even when I put die(); after
unset($_SESSION['location']);
it does not execute it, but when i put it before it works. Can anyone have any idea how to solve my problem?
Thanks in advance for help.
<?
session_start();
$_SESSION['location'] = 'http://www.google.com';
if(isset($_SESSION['location']) && !empty($_SESSION['location'])) {
$location = $_SESSION['location'];
header("location: ".$location);
}
?>
Works for me. Expand on that code and see when it breaks.
Add a die; right after your header:location. This should do the trick.
Chrome needs an http status first:
header("Status: 200");
header('Location:' . $url);

Categories