In the following code, the "header:" line is giving problem.
$q = mysql_query($a) or die(mysql_error());
$row = mysql_fetch_array($q);
$ValidationResponse = "false";
if ($_COOKIE['user_name'] != "")
{
while ($row) {
if ($_COOKIE['user_name'] = $row['username'])
{
$ValidationResponse = "true";
break;
}
}
if ($ValidationResponse == "true")
{
ob_start();
header("location:personal_view.php");
ob_clean();
}
else
echo "<script>alert('Invalid Login. Try Again.');</script>";
}
$_COOKIE['user_name'] = "";
Three useful functions I tend to have:
function redirect($url) {
while (ob_end_clean()) ; // do nothing
header("Location: " + $url);
exit;
}
function reload() {
redirect($_SERVER['REQUEST_URI']);
}
function reloadQS() {
redirect($_SERVER['REQUEST_URI'] + '?' + $_SERVER['QUERY_STRING']);
}
The above correctly handles what might be nested output buffers already but will fail if content has already been sent to the user, which you can't do anything about. I'd suggest using the above otherwise you'll litter your code with loops to clean buffers and there's no point in that.
You're using output buffering incorrectly, which is why it's failing. Change:
ob_start();
header("location:personal_view.php");
ob_clean();
to:
ob_end_clean();
header("Location: personal_view.php");
exit;
You should put the ob_start at the very beginning of the script
Also, i'm not sure about this, but i always seen the location header written in this way
header("Location: location.php");
Location with capital L an a space after the colon ": "
This might sound stupid, but are you sure you are not outputting anything before the header() function call? Apache won't redirect even if it finds a newline character before the starting tag <?php in a script.
Related
I've made this script, but the 4th line isn't right and I have really no clue how to solve this. I really appriciate if someone helps me. This is my code:
<?php
$url = $_GET["url"];
$badsite = array("http://check.com", "http://hotmail.com");
if($url == $badsite) {
echo "This URL is harmful.";
} else {
echo "Not harmful";
header("Location: " . $_GET["url"]);
}
?>
So the thing which doesn't work is the following line
if($url == $badsite) {
How can I make it so it checks if the GET contains a $badsite?
You don't want to check if the value equals the array, you want to check if it's in the array. Perhaps something like this:
if (in_array($url, $badsite)) {
// ...
}
Side note, you don't need (or want, really) this echo statement:
echo "Not harmful";
header("Location: " . $_GET["url"]);
You might get an error by emitting output before sending a header. But even if you buffer output or in some other way suppress that error, there's no reason to emit output when returning a redirect response. The browser would display it for only an instant, if at all. A redirect by itself is a complete HTTP response, no output is required.
In this case you can use the function in_array:
http://php.net/manual/en/function.in-array.php
<?php
$url = $_GET["url"];
$badsite = array("http://check.com", "http://hotmail.com");
if(in_array($url, $basite)) {
echo "This URL is harmful.";
} else {
echo "Not harmful";
header("Location: " . $_GET["url"]);
}
?>
I am struggling with code that redirects a user to other pages based on language detection. I found this code which looks promising as so far I have not had any luck from other posts on this website. My only question is related to the first line of code. What do I put in the "" part on first line?
<?php
$lc = ""; // Initialize the language code variable
// Check to see that the global language server variable isset()
// If it is set, we cut the first two characters from that string
if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
$lc = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
}
// Now we simply evaluate that variable to detect specific languages
if($lc == "fr"){
header("location: index_french.php");
exit();
} else if($lc == "de"){
header("location: index_german.php");
exit();
}
?>
<h2>Hello Default Language User</h2>
<h3><?php echo "Your 2-letter Code is: ".$lc; ?></h3>
When I run this code I get an error message:
Warning: Cannot modify header information - headers already sent by (output started at /home/m3418630/public_html/sumoresources/index.php:3) in /home/m3418630/public_html/sumoresources/index.php on line 12
Can anyone explain why this happens?
thanks
In your code snippet, you have to set a default language to the variable $lc. It will be overwritten if the server sends a language code from the current request.
This snippet can detect language from user's browser
$locale = null;
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
$languages = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
foreach ($languages as $lang) {
$lang = str_replace('-', '_', trim($lang));
if (false === strpos($lang, '_')) {
$locale = strtoupper($lang);
} else {
$lang = explode('_', $lang);
if (count($lang) == 3) {
$locale = strtolower($lang[0]) . ucfirst($lang[1]) . strtoupper($lang[2]);
} else {
$locale = strtolower($lang[0]) . strtoupper($lang[1]);
}
}
}
}
echo $locale;
see http://codepad.viper-7.com/F1XfU5
You don't put anything there, it's just initiating the variable as it says in the comment.
If you're getting a headers already sent error, that means your outputting information to the page before sending header(), you can't do this without buffering using ob_start(), ob_end_flush().
Here is my code
<?php
if (!isset($_SESSION)) { session_start(); }
if (!isset($_SESSION['username'])) { header("Location: index.php"); }
ob_start();
if($_POST) {
$id = $_POST['book_id'];
$command = $_POST['command'];
$sourcePage = $_POST['source'];
} else if ($_GET){
$command = $_GET['command'];
$sourcePage = $_GET['source'];
$id = $_GET['book_id'];
} else {
header("Location: index.php");
}
// if command is 2 then show cart content
if($command == 2) {
showCart();
// if command is 1 then add book to cart
} else if($command == 1) {
addToCart($id);
header("Location: $sourcePage");
// if command is 0, then remove book from cart
} else if($command == 0) {
deleteFromCart($id);
header("Location: $sourcePage");
} else if(!isset($command)){
header("Location: index.php");
}
ob_flush();
?>
Why is it that even if I'm not logged in, I'm not redirected?
is it possible that the page is simply refreshing under the condition that $_POST or $_GET exists, falling into one of the later header("Location: ...") commands?
If so, you'd want to fix the problem by adding a die();
if (!isset($_SESSION['username'])) { header("Location: index.php"); die(); }
Using exit() or die functions may fix the problem. But there is only very very limited amount of situations where actually need to use one of these functions.
I think you can enhance if else conditions by putting some more conditions. But this will increase your lines of code.
From my experience, every time there is redirect via headers, its following connected code tends to execute.
For example : if you have an else/else if along with an if(which has the redirect code) then they will also be executed and the redirect never happens. However if you break up the conditions into individual ifs then after entering one if if a redirect is present such that there is no succeeding code after that header code in the if then the redirect will happen.
Better to use die()/exit() all over to avoid discrepancies.
<?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).
Is there any way to check if an included document via include('to_include.php') has returned anything?
This is how it looks:
//to_include.php
echo function_that_generates_some_html_sometimes_but_not_all_the_times();
//main_document.php
include('to_include.php');
if($the_return_of_the_include != '') {
echo $do_a_little_dance_make_a_little_love_get_down_tonight;
}
So after I've included to_include.php in my main document I would like to check if anything was generated by the included document.
I know the obvious solution would be to just use function_that_generates_some_html_sometimes_but_not_all_the_times() in the main_document.php, but that's not possible in my current setup.
make function_that_generates_some_html_sometimes_but_not_all_the_times() return something when it outputs something and set a variable:
//to_include.php
$ok=function_that_generates_some_html_sometimes_but_not_all_the_times();
//main_document.php
$ok='';
include('to_include.php');
if($ok != '') {
echo $do_a_little_dance_make_a_little_love_get_down_tonight;
}
If you are talking about generated output you can use:
ob_start();
include "MY_FILEEEZZZ.php";
function_that_generates_html_in_include();
$string = ob_get_contents();
ob_clean();
if(!empty($string)) { // Or any other check
echo $some_crap_that_makes_my_life_difficult;
}
Might have to tweak the ob_ calls... I think that's right from memory, but memory is that of a goldfish.
You could also just set the contents of variable like $GLOBALS['done'] = true; in the include file when it generates something and check for that in your main code.
Given the wording of the question, it sounds as if you want this:
//to_include.php
return function_that_generates_some_html_sometimes_but_not_all_the_times();
//main_document.php
$the_return_of_the_include = include 'to_include.php';
if (empty($the_return_of_the_include)) {
echo $do_a_little_dance_make_a_little_love_get_down_tonight;
} else {
echo $the_return_of_the_include;
}
Which should work in your situation. That way you don't have to worry about output buffering, variable creep, etc.
I'm not sure if I'm missing the point of the question but ....
function_exists();
Will return true if the function is defined.
include()
returns true if the file is inclued.
so wrap either or both in an if() and you're good to go, unless I got wrong end of the stick
if(include('file.php') && function_exists(my_function))
{
// wee
}
try
// to_include.php
$returnvalue = function_that_generates_some_html_sometimes_but_not_all_the_times();
echo $returnvalue;
//main_document.php
include('to_include.php');
if ( $returnvalue != '' ){
echo $do_a_little_dance_make_a_little_love_get_down_tonight;
}