I've searched in various places for this solution, but have not been able to solve the problem that happened to me. What happens is actually in the following code:
[21-Jul-2017 23:35:30 UTC] PHP Parse error: memory exhausted in
/home/.../public_html/folder/index.php on line 2860
Chronologically, I want to create many options if one of the options is met. Here's the problem code:
<?php
if(isset($_GET['url'])) {
$u = $_GET['url'];
if($u == 'old/page1.html') {
header('Location: /new/page1.htm');
} if($u == 'old/page2.html') {
header('Location: /new/page2.htm');
} if($u == 'old/page3.html') {
header('Location: /new/page3.htm');
} if($u == 'old/page4.html') {
header('Location: /new/page4.htm');
}
//.....
//.....(line 5691)
}
?>
If I only use the above code, then it can run normally. But if I use my code number of 5691 lines, then the warning starts to appear and the site can not be opened.
I suspect there is a problem on the maximum amount of memory used, but do not know exactly.
If you really need to sort it out this way, then this would probably be better:
<?php
if (isset($_GET['url'])) {
$u = $_GET['url'];
$redirects = [
'old/page1.html' => '/new/page1.htm',
// ...
];
if (array_key_exists($u, $redirects)) {
$redirect = $redirects[$u];
header(sprintf(
'Location: %s',
$redirect
));
}
}
This way at least you can manage the redirect mapping separately, without the need to add a bunch of conditions.
You could also put the mapping into a separate file:
<?php
return [
'old/page1.html' => '/new/page1.htm',
// ...
];
and then adjust your script:
<?php
if (isset($_GET['url'])) {
$u = $_GET['url'];
$redirects = require __DIR__ . '/redirects.php';
if (array_key_exists($u, $redirects)) {
$redirect = $redirects[$u];
header(sprintf(
'Location: %s',
$redirect
));
}
}
This way you don't need to modify your script if the mapping changes.
Alternatively, use elseif:
<?php
if (isset($_GET['url'])) {
$u = $_GET['url'];
if ($u == 'old/page1.html') {
header('Location: /new/page1.htm');
} elseif ($u == 'old/page2.html') {
header('Location: /new/page2.htm');
} elseif ($u == 'old/page3.html') {
header('Location: /new/page3.htm');
} elseif ($u == 'old/page4.html') {
header('Location: /new/page4.htm');
}
}
You can replace those 5691 lines of code with this
if(isset($_GET['url'])) {
$u = $_GET['url'];
if(substr($u, 3) === 'old'){
$new = str_replace('old', 'new', $u);
header("Location: $new");
}
Related
I have a PHP application (a request form) that first checks for an active $_SESSION before a user can access the site. Because of the timeout period set for this form there is rarely an active session. Here's the check:
if (isset($_SESSION['samlUserdata'])) {
$attributes = $_SESSION['samlUserdata'];
$user_department = $attributes['department'];
$user_email = $attributes['email'];
$user_employee_id = $attributes['employee_id'];
$user_full_name = $attributes['full_name'];
}
...and here is the else {} that I use to grab the REQUEST_URI:
else {
if (isset($_SERVER['REQUEST_URI'])) {
$referer = $_SERVER['REQUEST_URI'];
$redirect = "https://myinternalwebsite.net$referer";
}
header("Location: https://myinternalwebiste.net/confirm_auth.php?sso");
}
...and last, here is what I do with the $_GET
if (isset($_GET['sso'])) {
if (isset($redirect)) {
$auth->login($redirect);
} else {
$auth->login("https://myinternalwebsite.net/");
}
}
However, once my session is killed I am never properly routed back to the URL set in the ['REQUEST_URI'], I am always just dumped onto the internal site's front page. I have troubleshooted this on and off for some time over the last week, to no avail. I've tried other variables in the $_SERVER array as well, such as ['REDIRECT_URL'].
I'm at a loss, and I'm sure this fairly simple for anyone with more experience than myself... so I am all ears and eager to learn.
EDIT:
Thank you for the comments below. Per your advice I will add the entirety of my code here, removing only the unnecessary parts. (And yes, I appreciate the tip to flip the initial (isset()) to (!isset(). Thank you for that.)
<?php
session_start();
$auth = new OneLogin\Saml2\Auth($saml_settings);
if (isset($_SESSION['samlUserdata'])) {
$attributes = $_SESSION['samlUserdata'];
$user_department = $attributes['department'];
$user_email = $attributes['email'];
$user_employee_id = $attributes['employee_id'];
$user_full_name = $attributes['full_name'];
} else {
if (isset($_SERVER['REQUEST_URI'])) {
$referer = $_SERVER['REQUEST_URI'];
$redirect = "https://example.net$referer";
}
header("Location: https://example.net/confirm_auth.php?sso");
}
if (isset($_GET['sso'])) {
if (isset($redirect)) {
$auth->login($redirect);
} else {
$auth->login("https://example.net/");
}
} else if (isset($_GET['slo'])) {
$auth->logout();
} else if (isset($_GET['acs'])) {
$auth->processResponse();
$errors = $auth->getErrors();
if (!empty($errors)) {
echo '<p>', implode(', ', $errors), '</p>';
}
if (!$auth->isAuthenticated()) {
echo "<p>Not authenticated!</p>";
exit();
}
$_SESSION['samlUserdata'] = $auth->getAttributes();
if (isset($_POST['RelayState']) &&
OneLogin\Saml2\Utils::getSelfURL() != $_POST['RelayState']) {
$auth->redirectTo($_POST['RelayState']);
}
} else if (isset($_GET['sls'])) {
$auth->processSLO();
$errors = $auth->getErrors();
if (empty($errors)) {
echo '<p>Sucessfully logged out!</p>';
} else {
echo '<p>', implode(', ', $errors), '</p>';
}
}
?>
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);
}
I'm working on a website and the index page checks if the user is logged in or not with this piece of code:
if (!$_SESSION['login'] && $_SESSION['login'] == "") {
include_once($_SERVER['DOCUMENT_ROOT'] . "/login/");
} elseif ($_SESSION['login'] == 1) {
include_once($_SERVER['DOCUMENT_ROOT'] . "/main/");
}
But I want it to look cleaner, then I started wondering if was possible to achieve something like this with a function:
checklogin($_SESSION['login']);
I don't have much experience with functions, so i'm sorry if my question looks stupid, so thanks in advance.
Try this
if(check_login()) {
echo 'You are in!';
} else {
header('Location: login.php');
exit;
}
function check_login () {
if(isset($_SESSION['login'] && $_SESSION['login'] != '') {
return true;
} else {
false;
}
}
Just use empty:
if ( empty($_SESSION['login']) ) {
include_once($_SERVER['DOCUMENT_ROOT'] . "/login/");
} else {
include_once($_SERVER['DOCUMENT_ROOT'] . "/main/");
}
Or condense it:
include_once $_SERVER['DOCUMENT_ROOT'].(empty($_SESSION['login']) ? "/login/" : "/main/");
There is what you need:
function userCheck()
{
return (isSet($_SESSION['login']) && $_SESSION['login']);
}
if(userCheck())
include_once($_SERVER['DOCUMENT_ROOT'] . "/main/");
else
include_once($_SERVER['DOCUMENT_ROOT'] . "/login/");
Disregarding the fact of whether or not your approach makes sense, I think this would do what you expect:
function checklogin($login){
if (!$login && $login == "") {
include_once($_SERVER['DOCUMENT_ROOT'] . "/path/");
}
}
// **** call to the function
checklogin($_SESSION['login']);
// ****
You can use this function:
function checklogin() {
return (isset($_SESSION['login'])) ? true : false;
}
then on pages you want to check whether the user is logged in or not, you can:
if(checklogin() === true){
//here you would put what you want to do if the user is logged in
} else {
//this would be executed if user isn't logged in
header('Location: protected.php');
exit();
//the above would redirect the user
}
I want to write a simple if statement using HTTP_ACCEPT_LANGUAGE function that redirects based on result of what the users browser language is. I am still a beginner so am obviously keeping it as simple as possible. This is what I have so far but the "if" statement needs work. Can anyone help me with a fix?
<?php
$lang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
if ($lang=german) {
header("Location: http://www.example.com/german/index.html");
} else if ($lang=spanish) {
header("Location: http://www.example.com/spanish/index.html");
}
else if ($lang=french) {
header("Location: http://www.example.com/french/index.html");
}
else if ($lang=chinese) {
header("Location: http://www.example.com/chinese /index.html");
} else {
echo "<html>english content</html>";
}
?>
I don't know what your language literals are, so I'd say make them ISO language codes.
Use a switch statement, this is more readable and smaller:
$lang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
switch($lang) {
case "de-DE":
case "es-ES":
case "cn-CN":
case "fr-FR":
header("Location: http://www.example.com/$lang/index.html");
break;
default:
header("Location: http://www.example.com/en-US/index.html");
break;
}
Further, you are assigning, not comparing. You compare with ==:
if ($lang == "de-DE")
Assuming you always redirect to /language/, you could do it this way:
<?php
$lang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
if ( in_array( $lang,array("german","spanish","french","chinese") ) ) {
header("Location: http://www.example.com/$lang/index.html");
} else {
echo "<html>english content</html>";
}
?>
Also, the comparisons in your if need to be done with ==, it's assignment otherwise!
Try this:
<?php
$path = array(
'en-US' => 'english',
// etc
);
$accepts = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
if (in_array($accepts[0], $path)) { // if path exists for language then redirect to path, else redirect to default path (english)
header('Location: http://www.example.com/' . $path[$accepts[0]] . '/index.html');
} else {
header('Location: http://www.example.com/english/index.html');
}
?>
HTTP_ACCEPT_LANGUAGE returns not "english", but two signs symbol like "en", or region and language symbol like "en_us". You shouldn't use if statement it's hard to read. You should use array (in future you can simple write it to config files, or move to databases).
The proper code should look that:
$default_lang = 'en';
$lang_redirectors = array('de' => 'http://www.example.com/german/index.html',
'en' => 'http://www.example.com/english/index.html');
function redirect($url){
header("Location: " . $url);
}
$hal = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
$langs = explode($hal, ',');
foreach($langs as $lang){
$lang_prefix = substr($lang, 0, 2);
if(in_array($lang_prefix, $lang_redirectors)){
redirect($lang_redirectors[$lang_prefix]);
break;
}
redirect($lang_redirectors[$default_lang]);
}
<?php
$browserlang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
$lang = $browserlang[0] . $browserlang[1] . $browserlang[2] . $browserlang[3] . $browserlang[4];
if (($lang=="sk_SK") OR ($lang=="sk-SK")) {
header("Location: https://www.example.sk/sk");
}
else if (($lang=="en_EN") OR ($lang=="en-EN") OR ($lang=="en_GB") OR ($lang=="en_US") OR ($lang=="en-GB") OR ($lang=="en-US")) {
header("Location: https://www.example.sk/en");
}
else {
header("Location: https://www.example.sk/en");
}
?>
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.