php | ERR_TOO_MANY_REDIRECTS [duplicate] - php

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 5 years ago.
I am experiencing some issues with php, on my localhost. I receive a err_too_many_redirects error from my browser.
I am recieving this error when I am trying to direct a user from accessing information from a different place on the web server.
Here is the code:
<?php
session_start();
if(isset($_SESSION['valid'])) {
$loggedIn = $_SESSION['name'];
if($loggedIn != basename(getcwd())) {
echo "You are in the wrong place.";
$url = '../../users/' . $loggedIn . '/index.php';
header('Location: ' . $url);
} else {
echo "Hello";
}
} else {
$url = 'index.php';
header('Location: ' . $url);
}
?>
Can someone please explain to me why it is doing this? I have tried multiple things such as re-arranging the order of the process.
Can someone please help me?

My bad, silly mistake.
I was re-directing them straight back to the INDEX page of the user
Code:
<?php
session_start();
if(isset($_SESSION['valid'])) {
$loggedIn = $_SESSION['name'];
if($loggedIn != basename(getcwd())) {
echo "You are in the wrong place.";
$url = '../../users/' . $loggedIn . '/index.php';
header('Location: ' . $url);
} else {
echo "Hello";
}
} else {
$url = 'index.php';
header('Location: ' . $url);
}
?>
I had to update the URL here in the else statement for the if(isset($_SESSION['valid]')) Here it is:
$url = '../../index.php';
header('Location: ' . $url);

Related

PHP - some proplems on detecting HTTPS Protocol

i am getting an problem on loading my Template and i had tried testing my template on XAMPP and the same problem happened again
Internal Server Error
The server encountered an internal error or misconfiguration and was
unable to complete your request.
Please contact the server administrator at admin#main-hosting.eu to
inform them of the time this error occurred, and the actions you
performed just before this error.
More information about this error may be available in the server error
log.`
it doesn't show anything at first just loading page and then that error no more... please help but on XAMPP it just keeps loading my page
but after some time when i was trying to resolve the problem, found it and tried solving it but i need some help please on fixing the code which caused it before
$Domain = $_SERVER['HTTP_HOST'];
$Path = $_SERVER['PHP_SELF'];
if (!empty($_SERVER['HTTPS']) && ('on' == $_SERVER['HTTPS']))
{
echo '<script type="text/javascript">window.location.assign("https://' .$Domain.$Path. '");</script>';
}
else
{
echo '<script type="text/javascript">window.location.assign("http://' .$Domain.$Path. '");</script>';
}
please some help ???
The reason is because each time your page is loading the script is running and refreshing the site endless. You need to know if the page have already been redirected.
example:
<?php
if (!isset($_GET['r'])){
$Domain = $_SERVER['HTTP_HOST'];
$Path = $_SERVER['PHP_SELF'];
if (!empty($_SERVER['HTTPS']) && ('on' == $_SERVER['HTTPS']))
{
echo '<script type="text/javascript">window.location.assign("https://' .$Domain.$Path. '?r=https");</script>';
}
else
{
echo '<script type="text/javascript">window.location.assign("http://' .$Domain.$Path. '?r=http");</script>';
}
}
?>
I do not understand the point of this.. And I would recommend you to use Location instead. Example:
header('Location: http://www.example.com/');
This is a very poor way to reload a page.
The code below reloads the page infinitely until the url is modified...
To understand this, run the code below...
$Domain = $_SERVER['HTTP_HOST'];
$Path = $_SERVER['PHP_SELF'];
if (!empty($_SERVER['HTTPS']) && ('on' == $_SERVER['HTTPS'])) {
echo 'HTTPS AVAILABLE';
echo '<script type= "text/javascript">window.location.assign("https://' . $Domain .$Path. '");</script>';
} else {
echo 'HTTPS NOT AVAILABLE ';
echo '<script type="text/javascript">window.location.assign("http://' . $Domain .$Path.' ");</script>';
}
while the pages keeps loading, modify the code to this
$Domain = $_SERVER['HTTP_HOST'];
$Path = $_SERVER['PHP_SELF'];
if (!empty($_SERVER['HTTPS']) && ('on' == $_SERVER['HTTPS'])) {
echo 'HTTPS AVAILABLE';
echo '<script type="text/javascript">window.location.assign("https://' . $Domain . '");</script>';
} else {
echo 'HTTPS NOT AVAILABLE ';
echo '<script type="text/javascript">window.location.assign("http://' . $Domain .' ");</script>';
}
once saved this will redirect you to https://localhost or http://localhost
if running on your local machine.
The window.location.assign() reloads the page infinitely if the url is the same.

How to avoid the catch-22 of PHP session_start() vs "headers already sent" warning?

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

PHP conditional statetment from form [duplicate]

This question already has answers here:
The 3 different equals
(5 answers)
Closed 6 years ago.
How do I make the statement below work. I have a form that post the values to my function.php. Is it possible for me to include the .html files on the function.php as a content rather than heading to the locations? I am new student learning the hard way.
<?php
if ($_POST['city'] = 'london'){
header('Location: london.html');
}
if ($_POST['city'] = 'manchester'){
header('Location: manchester.html');
}
if ($_POST['city'] = 'conventry'){
header('Location: coventry.php');
}
exit;
?>
You have to use == in if statement, not =.
Try this,
<?php
if ($_POST['city'] == 'london'){
header('Location: london.html');
}
if ($_POST['city'] == 'manchester'){
header('Location: manchester.html');
}
if ($_POST['city'] == 'conventry'){
header('Location: coventry.php');
}
exit;
?>
Check the below link for more info.
https://www.tutorialspoint.com/php/php_decision_making.htm
If you are just using the value in the location as a straight swap of destination - you don't need any ifs at all - just put the variable in the location:
<?php
$city = $_POST['city'];
header('Location:' . $city . '.html');
exit;
?>
//$city = london;
//header('Location:london.html');
If you have different file extensions - eg the .html and .php that you show here - then you can use a switch statement to reduce the if statements:
<?php
$city = $_POST['city'];
switch ($city) {
case "london":
header('Location: london.html');
break;
case "manchester":
header('Location: manchester.html');
break;
case "coventry":
header('Location: coventry.php');
break;
default:
echo "Your destination did not match any of our available cities";
}
exit;
?>

How to correctly check if page was included? [duplicate]

This question already has answers here:
PHP: Check if a file is loaded directly instead of including?
(15 answers)
Closed 8 years ago.
I want to make sure that my pages are being included working index page. I would like to know what would be correct way of assuring that my page is being included instead of rendered by itself?
Right now I'm checking if there are at least 2 included files, but I'm not sure I'd it's behavior.
include('config/config.inc.php');
$cms = new cms();
if(($_SERVER['REQUEST_METHOD'] === 'GET' || $_SERVER['REQUEST_METHOD'] === 'POST') && !empty($_GET['page'])) {
include($cms->GetTheme() . "/head.php");
$cms->IncludeModule($_GET['page']); <- actual page being included
include($cms->GetTheme() . "/foot.php");
} // end (GET || POST) && GET
else { // just index.php
include($cms->GetTheme() . "/head.php");
foreach($cms->GetModuleList() as $module) {
echo " $module <br />";
}
include($cms->GetTheme() . "/foot.php");
} // end ELSE
Included page and how I check is it's included
<?php
$module_name = 'Log out user';
$module_directory = 'admin';
$this->SetTitle($module_name); // setting page title
if(count(get_required_files()) < 2) {
header('Location: index.php');
}
else {
if(isset($_SESSION['user'])) {
$this->DestroyUser();
echo "You have been logged out! Please navigate to the Login Page.";
}
else {
header('Location: index.php?page=login');
}
}
?>
I'm not sure if you're talking about this:
include 'test.php';
If yes, then do a simple test like this:
test.php
$testVar = '1';
index.php
include 'test.php';
echo $testVar;
I have no idea what library you're using, so i hope this simple example will allow you to understand.

PHP header issue within my file [duplicate]

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 9 years ago.
I have this problem being reported in one of my files;
Warning: Cannot modify header information - headers already sent by (output started at /home/*/public_html/addengine/parseclick.php:1) in /home/*/public_html/addengine/parseclick.php on line 40
Here is the code of the actual file;
<?php
include_once("../admin/database.php");
$today = date("Y-m-d");
$data = str_replace(' ', '+', $_GET['data']);
$de_data = decrypt($data,$ad_passcode='',$salt='');
$arr_data = explode(":",$de_data);
/*
Array: arr_data
arr_data[0] = pub_ad_id
arr_data[1] = adv_ad_id
arr_data[2] = compaign_id
*/
$pid = $arr_data[0];
$aid = $arr_data[1];
$cid = $arr_data[2];
/*$billing = getvalue("billing_type","compains",$cid);
if($billing == 'cpc' || $billing == 'both')
{
countClick($aid,"adds",$pid);
countClick($pid,"pub_adds",$pid);
}*/
$adv_ad_id = $aid;
$pub_ad_id =$pid;
countClick($adv_ad_id,$pub_ad_id);
$parenturl = $_SERVER["HTTP_REFERER"];
if( verifyLegitimateurl($parenturl,$pid) == 'Passed' && emailAlreadyExists($_SERVER['REMOTE_ADDR'],"banips","cip") == false)
{
$url = getvalue("url","adds",$aid);
header("Location: ".$url);
}
?>
The error is because of this line:
header("Location: ".$url);
You cannot redirect if you already started to write to the page.
So if you have something like this
<!Doctype html>
<?php
header("Location: ".$url);
?>
You will get that error, you have to make sure you dont have any html above the php , or you dont echo anything.
So if you place your php on top , you wont get the error:
<?php
header("Location: ".$url);
?>
<!Doctype html>
instead of
header("Location: ".$url);
use
<META http-equiv="refresh" content="0;URL=<?php echo $url;?>">
obviously you should close the php tag before this html code and start it again after this code
Use ob_start(); after <? at the beginning of file and place ob_flush(); before ?> at the end of the file.

Categories