Undefined index and unable to modify headers already sent [duplicate] - php

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 9 years ago.
We're using a script to manage cookies on our joomla install. It works fine. When we install it on another site that isn't joomla we are facing these errors
Notice: Undefined index: prefcookie
Warning: Cannot modify header
information - headers already sent by (
Our code is
<?php
error_reporting(-1);
$url="/path/filter.php?u=http%3A%2F%2F".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if ($_COOKIE['prefcookie'] == "path-all")
{
return;
}
elseif ($_COOKIE['prefcookie'] == "path-first")
header("Location: http://".$_SERVER["HTTP_HOST"]."$url%2F&b=2");
elseif($_COOKIE['prefcookie'] == "path-block")
header("Location: http://".$_SERVER["HTTP_HOST"]."$url%2F&b=2");
else
header("Location: http://".$_SERVER["HTTP_HOST"]."$url%2F&b=3");
?>
EDIT
That surpreses the error but doesn't solve the problem, the idea is that this checks the visitor for a preference and redirects the visitor to part of the site based on it, this fix just brings the visitor back to the requested file
The full code is
<?php
require_once('path/geoip/geoplugin.class.php');
$geoPlugin_array = unserialize( file_get_contents('http://www.geoplugin.net/php.gp?ip=' . $_SERVER['REMOTE_ADDR']) );
if ( $geoPlugin_array['geoplugin_continentCode'] == 'EU' )
{
require_once("path/includes/browser.php");
$browser = new Browser();
if( $browser->getBrowser() == Browser::BROWSER_GOOGLEBOT )
{
return;
}
elseif( $browser->getBrowser() == Browser::BROWSER_SLURP )
{
return;
}
elseif( $browser->getBrowser() == Browser::BROWSER_MSNBOT )
{
return;
}
else
{
$url="/path/filter.php?u=http%3A%2F%2F".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
// This will avoid undefined index
if ((!isset($_COOKIE['prefcookie'])) || ($_COOKIE['prefcookie'] == "path-block")) {
return;
}
elseif($_COOKIE['prefcookie'] == "path-first")
header("Location: http://".$_SERVER["HTTP_HOST"]."$url%2F&b=2");
elseif($_COOKIE['prefcookie'] == "path-block")
header("Location: http://".$_SERVER["HTTP_HOST"]."$url%2F&b=2");
else
header("Location: http://".$_SERVER["HTTP_HOST"]."$url%2F&b=3");}
}
?>
EDIT
Set pref cookie
<?php
if($_GET['optin'] == "all")
{
setcookie("prefcookie", "path-all", time()+60*60*24*30);
header("Location: http://".$_SERVER["HTTP_HOST"]);
}
elseif($_GET['optin'] == "first")
{
setcookie("prefcookie", "path-first", time()+60*60*24*30);
header("Location: http://".$_SERVER["HTTP_HOST"]."/path/filter.php?u=http%3A%2F%2Fwww.fatcowmedia.com%2F&b=2");
}
elseif($_GET['optin'] == "block")
{
setcookie("prefcookie", "path-block", time()+60*60*24*30);
header("Location: http://".$_SERVER["HTTP_HOST"]."/path/filter.php?u=http%3A%2F%2Fwww.fatcowmedia.com%2F&b=3");
exit;
}
?>
EDIT
how to find requested url
$url="/path/filter.php?u=http%3A%2F%2F".$_SERVER["HTTP_HOST"].$_SERVER['REQUEST_URI'];
send to requested url
header("Location: http://".$_SERVER["HTTP_HOST"]."$url%2F&b=2");
EDIT
<?php
error_reporting(E_ALL);
$url="/path/filter.php?u=http%3A%2F%2F".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
require_once('path/geoip/geoplugin.class.php');
$geoPlugin_array = unserialize( file_get_contents('http://www.geoplugin.net/php.gp?ip=' . $_SERVER['REMOTE_ADDR']) );
if ( $geoPlugin_array['geoplugin_continentCode'] == 'EU' )
{
require_once("path/includes/browser.php");
$browser = new Browser();
if( $browser->getBrowser() == Browser::BROWSER_GOOGLEBOT )
{
return;
}
elseif( $browser->getBrowser() == Browser::BROWSER_SLURP )
{
return;
}
elseif( $browser->getBrowser() == Browser::BROWSER_MSNBOT )
{
return;
}
else
{
// If expected cookie isn't set yet, send em to landing page
if (!isset($_COOKIE['prefcookie'])) {
header("Location: http://".$_SERVER["HTTP_HOST"]."$url%2F&b=2");
}
// If we made it this far, we have our expected cookie, we can implement a switch
switch ($_COOKIE['prefcookie']) {
case 'path-block':
case 'path-first':
header("Location: http://".$_SERVER["HTTP_HOST"]."$url%2F&b=2");
break;
default:
header("Location: http://".$_SERVER["HTTP_HOST"]."$url%2F&b=3");
break;
}
}
}
?>
UPDATED
==========
<?php
require_once('path/geoip/geoplugin.class.php');
$geoPlugin_array = unserialize( file_get_contents('http://www.geoplugin.net/php.gp?ip=' . $_SERVER['REMOTE_ADDR']) );
if ( $geoPlugin_array['geoplugin_continentCode'] == 'EU' )
{
require_once("path/includes/browser.php");
$browser = new Browser();
if( $browser->getBrowser() == Browser::BROWSER_GOOGLEBOT )
{
return;
}
elseif( $browser->getBrowser() == Browser::BROWSER_SLURP )
{
return;
}
elseif( $browser->getBrowser() == Browser::BROWSER_MSNBOT )
{
return;
}
else
{
if (!isset($_COOKIE['prefcookie'])) {
header("Location: http://".$_SERVER["HTTP_HOST"]."/path/filter.php?u=http%3A%2F%2Fwww.path.org".$_SERVER["REQUEST_URI"]."&b=2");
}
elseif($_COOKIE['prefcookie'] == "path-all")
{
return;
}
elseif($_COOKIE['prefcookie'] == "path-first")
header("Location: http://".$_SERVER["HTTP_HOST"]."/path/filter.php?u=http%3A%2F%2Fwww.path.org".$_SERVER["REQUEST_URI"]."&b=2");
elseif($_COOKIE['prefcookie'] == "path-block")
header("Location: http://".$_SERVER["HTTP_HOST"]."/path/filter.php?u=http%3A%2F%2Fwww.path.org".$_SERVER["REQUEST_URI"]."&b=2");
else
header("Location: http://".$_SERVER["HTTP_HOST"]."/path/filter.php?u=http%3A%2F%2Fwww.path.org".$_SERVER["REQUEST_URI"]."&b=2");
}
}
?>

Should probably add a check to make sure that the element exists in the array:
// This will avoid undefined index
if ((!isset($_COOKIE['prefcookie'])) || ($_COOKIE['prefcookie'] == "path-all")) {
return;
}
-- Update --
According to your updates and comments, the following code should work:
// If expected cookie isn't set yet, send em to landing page
if (!isset($_COOKIE['prefcookie'])) {
header("Location: http://".$_SERVER["HTTP_HOST"]."$url%2F&b=2");
}
// If we made it this far, we have our expected cookie, we can implement a switch
switch ($_COOKIE['prefcookie']) {
case 'path-block':
case 'path-first':
header("Location: http://".$_SERVER["HTTP_HOST"]."$url%2F&b=2");
break;
case 'path-all':
header("Location: http://".$_SERVER["HTTP_HOST"]);
break;
default:
header("Location: http://".$_SERVER["HTTP_HOST"]."$url%2F&b=3");
break;
}
For the record, in your original code you had 'path-block' twice, so I assumed it to be the same as 'path-first' as you have it. If this is not desired, you can copy and past the header location for 'path-first' and paste it under 'path-block'.
Also, it appears your url construct is malformed:
$url="/path/filter.php?u=http%3A%2F%2F".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
// If you decode the following construct it looks like (I decoded entities for clarity)
// http://www.example.com/path/filter.php?u=http://www.example.com/path/filter.php/&b=2
// %2F decodes to a slash "/", so the /&b=2 appears malformed, it should be /?b=2
header("Location: http://".$_SERVER["HTTP_HOST"]."$url%2F&b=2");
A useful encode/decode tool can be found # meyerweb.com/eric/tools/dencoder

You're seeing this notice because the index "prefcookie" does not exist. In all likelihood, on your Joomla install something is setting $_COOKIE['prefcookie'], but your install not on Joomla doesn't have this index.
Furthermore, the warning you are seeing is because you are trying to change the header information after it's already been sent. You can suppress this, however it's probably better to just redirect the user prior to sending the rest of the headers.

Related

Php Redirect to a new page from an if statement [duplicate]

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 5 years ago.
Please professional programmers in the house, what is wrong with this code?
I get this error whenever i try to run it.
Parse error: syntax error, unexpected ';' in C:\xampp\htdocs\a\go.php on line 8
The php code:
<?php
$term=$_POST['term'];
$level=$_POST['level'];
if (
$term = 'First';
$level='js1';
)
{
header("Location: result.php");
exit();
}
elseif (
$term = 'First';
$level='js2';
)
{
header("Location: result2.php");
exit();
}
else {
$error = "Entry is invalid";
}
?>
Check your if condition. The if and else if conditions must not contain any semicolons. If you are using two comparisons you must use && or || in between them. If you are using = in the if and elseif statement then it will always return true.
<?php
$term=$_POST['term'];
$level=$_POST['level'];
if ($term == 'First' && $level=='js1')
{
header("Location: result.php");
exit();
}
else if ($term == 'First' && $level='js2')
{
header("Location: result2.php");
exit();
}
else {
$error = "Entry is invalid";
}
?>
Change your if condition
it should be
if($term = 'First'&& $level='js1') or if($term = 'First'|| $level='js1')
elseif ($term = 'First' && $level='js2') or elseifif($term = 'First'|| $level='js2')
not
if ($term = 'First'; $level='js1';)
elseif ($term = 'First' ; $level='js2';)
All of your if statements have a malformed format. All you are doing is setting variables within your if statement. Therefore you are not using assignment operators properly. An example of how your if statement should look is:
if($condition === true || $condition2 == 'hello'){
doSomething();
} else if($condition === false || $condtion2 == 'bye'){
doSomethingElse();
}
EDIT: Also i would recommend working on your code indentation skills, this will really help to read your code in the future.
You are not making correct boolean expressions in those ifs.
if ($term === 'first' && $level === 'js1') {...}
elseif($term === 'First' && $level === 'js2') {...}
Also, I strongly recommend you to put a die(); after a redirect to avoid unnecessary load (unless you need to execute code after the redirect).
try this.
<?php
$term=$_POST['term'];
$level=$_POST['level'];
if( $term == 'First' && $level=='js1'){
header("Location: result.php");
exit();
} elseif ( $term == 'First' && $level=='js2'){
header("Location: result2.php");
exit();
} else {
$error = "Entry is invalid";
}
?>
If there is a header already sent error you receive then put ob_start() to top of your php file OR You can also use javascript for this like below.
<script>window.location.href = "a.php";</script>

How to redirect to file according to country wise

I am using different sites directories according to countries for my company like
Getacho.com
Getacho.com/pk/
Getacho.com/uk/
Getacho.com/ca/
I am using one script. As I am from pakistan when I open
Getacho.com
I redirect to
Getacho.com/pk
but the problem is when I open.
Getacho.com/about.php
I do not redirect to
Getacho.com/pk/about.php.
This is the script the code that does the first redirect:
<?php
require_once('geoplugin.class.php');
$geoplugin = new geoPlugin();
$geoplugin->locate();
// create a variable for the country code
$var_country_code = $geoplugin->countryCode;
// redirect based on country code:
if ($var_country_code == "US" OR $var_country_code == "UM") {
header('Location: http://www.getacho.com/');
}
elseif($var_country_code == "PK") {
header('Location: http://www.getacho.com/pk/');
}
elseif($var_country_code == "AE") {
header('Location: http://www.getacho.com/ae/');
}
elseif($var_country_code == "CA") {
header('Location: http://www.getacho.com/ca/');
}
elseif($var_country_code == "GB") {
header('Location: http://www.getacho.com/uk/');
}
elseif($var_country_code == "IN") {
header('Location: http://www.getacho.com/in/');
}
?>
Since you are using Apache, you can use the server-variable REQUEST_URI to get the requested url. Then it is simply adding that to the url:
if ($var_country_code == "US" OR $var_country_code == "UM") {
header( "Location: http://www.getacho.com{$_SERVER['REQUEST_URI']}" );
} elseif($var_country_code == "PK") {
header( "Location: http://www.getacho.com/pk{$_SERVER['REQUEST_URI']}" );
} elseif( ... ) {
//etc
}

Putting a session in a if and else statement

I've got a problem with putting a session to store some page info into a variable
heres the code:
<?php
$t = $_GET['nm'];
if ($t=="1")
{
session_start();
// store session data
$_SESSION['nm']=1;
}
else
{
?>
<script>
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
window.location = "http://www.gouda-info.nl/mobile";
}
</script>
<?php
}
$session = $_SESSION['nm'];
if ($session=="1")
{
When i try to use the script it just doesn't work. I use this script to redirect mobile users, but if they choose to use the Desktop version they'll be allowed by activating the session that stores if the user has activated the desktop version by putting nothing or a 1 in the link like so:
http://www.example.com/index.php?nm=1
hope anyone comes up with a bright solution. :)
EDIT:
it just fails if i try to run this code, it gives me a blank page.
session must be started on the top, and sometimes you deal with == 1 and other with $t == "1"
try this code:
// first line
session_start();
$t = $_GET['nm'];
if ($t == 1) { // use 1 instead of "1"
// store session data
$_SESSION['nm'] = 1;
} else {
?>
<script>
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)) {
window.location = "http://www.gouda-info.nl/mobile";
}
</script>
<?php
}
$session = $_SESSION['nm'];
if ($session == 1) { // use 1 instead of "1"
}
You are using js code in php, but your js will be run after entire php file executed. So use php instead;
<?php
session_start();
$t = $_GET['nm'];
if ($t == "1") {
// store session data
$_SESSION['nm'] = "1";
} else {
if(isMobile()) {
header('Location: http://www.gouda-info.nl/mobile');
exit();
}
}
$session = $_SESSION['nm'];
if ($session == "1") {
......
}
function isMobile($user_agent=NULL) {
if(!isset($user_agent)) {
$user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
}
return (strpos($user_agent, 'Android') !== FALSE
|| strpos($user_agent, 'webOS') !== FALSE
|| strpos($user_agent, 'iPhone') !== FALSE
|| strpos($user_agent, 'iPad') !== FALSE
|| strpos($user_agent, 'iPod') !== FALSE
|| strpos($user_agent, 'BlackBerry') !== FALSE);
}

redirecting with if statment based on cookie using header('location:') gives weird error in firefox

I am trying to redirect my visitors to for example http://localhost/site/test.php?lang=en_USbased on the country code in the cookie like this:
if (isset($_COOKIE['country']))
{
$country = $_COOKIE['country'];
header('Location: test.php?lang=en_US');
if ($country == "NO"){
header('Location: test.php?lang=no_NO');
}
}
else
{
header('Location: test.php?lang=en_US');
}
But i get this weird error in firefox: The page isn't redirecting properly
Found a solution:
if (!isset($_GET['lang']))
{
if (isset($_COOKIE['country']))
{
$country = $_COOKIE['country'];
$redirect = "en_US";
if ($country == "NO"){
$redirect = "no_NO";
header('Location: crime.php?lang='.$redirect);
}
if ($country == "EN"){
$redirect = "en_US";
header('Location: crime.php?lang='.$redirect);
}
}
else
{
header('Location: crime.php?lang=en_US');
}
}
The problem is that it is unconditionally redirecting, and always to itself, causing an infinite loop which Firefox detects and stops. You need to add conditions to prevent redirects once the final page has been reached.

How to change the elements in the page base on user who is logged in

Please give me an idea on how to display elements in a page depending on who is logged in. For example, a user or an administrator.
I'm thinking of something like this but I get a parse error, what do I lack in this code?:
EDIT:
<?php
session_start();
if (!(isset($_SESSION['loginAdmin']) && $_SESSION['loginAdmin'] != '')) {
header ("Location: loginam.php");
}
else if (!(isset($_SESSION['loginAdmin']) && $_SESSION['loginAdmin'] =='')) {
include('head2.php');
}
else if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) {
header ("Location: login.php");
}
else if (!(isset($_SESSION['login']) && $_SESSION['login'] =='')) {
include('head3.php');
}
?>
Please help, there's no error but its not functioning properly. Whenever I try to access the page where I have this code. And login as a user. It redirects to loginam.php(the page where the admin will login). But there's no problem when I log in as admin. It works properly. What do I do?
Use
if (condition)
{
}
else if (condition) {
}
Also Just to make things simpler .. try something like ..
function is_admin() {
if(isset($_SESSION['loginAdmin']) && $_SESSION['loginAdmin'])
return true;
} else {
return false;
}
}
and then check
if(is_admin()) {
///admin block
} else {
//admin login
}
if(is_user()) {
///user block
} else {
//user login
}
if else is not valid. It's else if.
Other than that, it would help if you posted the parser error along with your code.
You're also not closing your <?php statement before opening it again.
because you have an invalid code.
he's the trimmed code:
&lt?php
session_start();
if (!isset($_SESSION['loginAdmin']) && ($_SESSION['loginAdmin'] != '')) {
header ("Location: loginam.php");
} else {
include('head2.php');
}
?>
&lt?php
if (!isset($_SESSION['login']) && ($_SESSION['login'] != '')) {
header ("Location: login.php");
} else {
include('head3.php');
}
?>
pay a little attention to the code.

Categories