About header error in PHP - php

I am working on a PHP project where I am trying to redirect from one page to another, using header (Location:something.php). It's working fine on the local machine but when uploaded to the server, the following error occurs:
Warning: Cannot modify header information - headers already sent by (output started at /homepages/4/d404449574/htdocs/yellowandred_in/newTest/editHome.php:15) in /homepages/4/d404449574/htdocs/yellowandred_in/newTest/editHome.php on line 43
I already tried with include, include_once, require and require_once but it's giving other errors like:
Cannot redeclare logged_in() (previously declared in C:\wamp\www\ynrNewVersion-1\editHome.php:3) in C:\wamp\www\ynrNewVersion-1\adminIndex.php on line 5
My code
<?php
session_start();
function logged_in() {
return isset($_SESSION['username']);
}
function confirm_logged_in() {
if (!logged_in()) {
include "error404.php";
exit;
}
}
confirm_logged_in();
require_once("connection.php");
$query="select * from home";
$homeInfo = mysql_query($query, $connection);
$result = mysql_fetch_array($homeInfo);
$content = $result['content'];
$rssFeeds = $result['rssFeeds'];
$message = "";
if(isset($_POST['submit'])){
$content = $_POST['content'];
$rssFeeds = $_POST['rssFeeds'];
if($content == "" || $rssFeeds == ""){
$message = "Please enter into all the fields";
} else {
$query = "UPDATE home SET content='$content',rssFeeds='$rssFeeds' WHERE id=1 LIMIT 1";
$result = mysql_query($query,$connection);
if(!$result){
echo "error".mysql_error();
}
if ($result == 1) {
header("Location:adminIndex.php");
} else {
$message = "Error Occurred";
}
}
}
if(isset($_POST['cancel'])){
header("Location:adminIndex.php");
}
?>

Use ob_start() at the top of PHP page;

you need to put an exit() or die() after the header function - otherwise the rest of the script will continue to execute.
The redirection can take a relative or absolute URL. The problem is with the space BEFORE the colon. Try it like this:
header("Location: adminIndex.php");
die();

The problem is that you have echo before your header function.
if(!$result){
echo "error".mysql_error();
}
before your two header("Location:adminIndex.php"), your can't echo anything.

Related

ERR_TOO_MANY_REDIRECTS in PHP

My logout.php file is like this. Is there any mistake in my code
logout.php
<?php
session_start();
session_destroy();
header('Location:index.php');
exit;
?>
Here is my index.php file. If I am set $_SESSION['s_activId'] then it is working properly but when I am trying to put condition if $_SESSION['s_activId'] is not set at that time I want to pass header on index page sometimes it works sometimes it does not work.
<?php
include('include/config.inc.php');
if(!isset($_SESSION['s_activId']))
{
$_SESSION['s_urlRedirectDir'] = $_SERVER['REQUEST_URI'];
header("Location:index.php");
}
else
{
$wrong = '';
if(isset($_POST['submit']))
{
$checkLogin = "SELECT userName,password,userType
FROM user
WHERE BINARY userName = '".$_POST['userName']."'
AND BINARY password = '".$_REQUEST['password']."'";
$checkLoginresult = mysql_query($checkLogin);
if($userLoginRow = mysql_fetch_array($checkLoginresult))
{
$_SESSION['s_activId'] = $userLoginRow['userName'];
$_SESSION['s_password'] = $userLoginRow['password'];
$_SESSION['hg_userType'] = $userLoginRow['userType'];
if(!$_SESSION['s_urlRedirectDir'])
{
header("Location:index.php");
}
else
{
header("Location:reminder.php");
}
}
else
{
$wrong = "UserId And Password Is Not Valid";
}
}
}
include("bottom.php");
$smarty->assign('wrong',$wrong);
$smarty->display("index.tpl");
?>
The problem arise in the condition below in index.php:
if(!isset($_SESSION['s_activId']))
{
$_SESSION['s_urlRedirectDir'] = $_SERVER['REQUEST_URI'];
header("Location:index.php");
}
When you logout, you are calling session_destroy() on logout.php and redirecting on index.php and the condition above gets true as s_activId is not set in session and again you are redirecting on index.php (without setting s_activId in session). The above condition will be true until the variable s_activId set in session and because of this you are getting ERR_TOO_MANY_REDIRECTS error.
The solution is, on index.php set the variable s_activId in session before calling the header method. Refer the code below:
if(!isset($_SESSION['s_activId']))
{
$_SESSION['s_urlRedirectDir'] = $_SERVER['REQUEST_URI'];
$_SESSION['s_activId'] = true;
header("Location:index.php");
}
Dont redirect index.php to index.php. you having redirects loop. Also
if you have code below that also can fire add die in if because after
redirect code below still executes. I didnt read your code, maybe
there isnt problems with this but after
header("Location: lalala"); always add die(); or exit();

Write text with echo() after reloading page with header()

I have page called account_settings.php and it's consist of change password, change profile pic, change user details (name, bio etc.). My question is how to write message with echo() after redirecting page with header().
Something like this:
if (true)
{
Do_Some_MySQL();
header("Location: account_settings.php");
echo "Success!";
}
else
{
echo "Error!";
}
Thank you for all replies. ;-)
You can't actually do something after sending a Location header - it is impossible.
Instead, you could use $_SESSION array value to perform your task. Like:
if (true)
{
Do_Some_MySQL();
$_SESSION['message'] = 'Error!';
header("Location: account_settings.php");
}
else
{
echo "Error!";
}
And then on your account_setting.php:
<?php echo $_SESSION['message'] ?>
This would be nice if the account_settings.php is not the same page as you currently are. Otherwise, you could use the following code:
if (true)
{
Do_Some_MySQL();
$error = 'Success!';
header("Location: account_settings.php");
}
else
{
$error = "Error!";
}
And on the same page:
<?php if($error) echo $error; ?>
Also don't forget to include session_start() on both pages if you didn't it yet.
I would use a SESSION variable:
on redirect-page:
<?php
#session_start();
if(true){
$_SESSION['success'] = 1;
header("Location: account-settings.php");
}
?>
and on account-settings.php:
<?php
#session_start();
if(isset($_SESSION['success'])){
echo "Success!";
unset($_SESSION['success']);
}
You cannot echo anything after you just redirected. The browser is already processing the request to redirect to another page, so it doesn't bother about displaying the message anymore. What you seem to be looking for is something called flash message. You can set a temporary message in the session and have it display on the new page. For example, in your account_settings.php page:
// Make sure you have an actual session
if (!session_id()) {
session_start();
}
if (true) {
Do_Some_MySQL();
$_SESSION['flashMessage'] = 'Success!';
header('Location: account_settings.php');
}
Then in your template file for account_settings, check if there is any flash message and display it accordingly (and unset it to avoid a loop):
if (isset($_SESSION['flashMessage'])) {
echo $_SESSION['flashMessage'];
unset($_SESSION['flashMessage']);
}
These people are correct...you can't send headers after a redirect. Although I think this would be a beneficial alternative. To send a GET request in your header and process it on the receiving page. They are suggesting to use $_SESSION vars, but you can use GET vars. Ex:
if (true)
{
//Do_Some_MySQL();
header("Location: account_settings.php?message=success");
//above has GET var message = Success
}
else
{
header("Location: account_settings.php?message=error");
}
On your account_settings.php page have this code:
if (isset($_GET['message'])) {
$message = $_GET['message'];
if ($message == "success") {
echo "Success";
} else {
echo "Error";
}
}
This removes the need of CONSTANT SESSION vars. and gives you plenty of flexibility.
header("Location: account_settings.php?message=No%20results%20found");
//%20 are URL spaces. I don't know if these are necessary.
If you need you can add more then one.
header("Location: account_settings.php?message=error&reason=No%20Results&timestamp=" . Date());
then account_settings.php can be:
if (isset($_GET['message'])) {
$message = $_GET['message'];
$reason = $_GET['reason'];
$time = $_GET['timestamp'];
if ($message == "success") {
echo "Success";
} else {
echo "Error: <br/>";
echo "Reason: $reason";
}
}
But remember GET exposes your messages in the browsers URL. So DON'T send sensitive information unless you secure it. Hope this helps.

php redirect_to() function undefined

I am working on a database and I need to redirect the user to another page after the login process.
I am using the redirect_to() function. After the code executes it gives me the error
Fatal error: Call to undefined function redirect_to()
Here is what I tried
if($result){
$num_rows = mysqli_num_rows($result);
if($num_rows == 1){
$found_user=mysqli_fetch_array($result);
redirect_to("main.php");
}
else{
redirect_to("index.php");
}
}
You have to define the redirect_to function before calling it. Try this code
<?php
if($result){
$num_rows = mysqli_num_rows($result);
if($num_rows == 1){
$found_user=mysqli_fetch_array($result);
redirect_to("main.php");
}
else{
redirect_to("index.php");
}
}
function redirect_to($location){
header('Location:'.$location);
}
?>
Try to use header :
<?php
/* Redirection vers une page différente du même dossier */
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'mypage.php';
header("Location: http://$host$uri/$extra");
exit;
?>
redirect_to() isn't a function. You want to use header("Location: main.php");
As this is adding header information, it needs to be loaded before anything is passed to the page (I believe), so don't attempt to print anything out to the page before header() is called.
If you want to do something like that, I suggest using javascript.
redirect_to doesn't exist, or if it does, it's not been included/required correctly.
Add this;
if( function_exists('redirect_to') == FALSE ) { //Future proofing...
function redirect_to($where) {
header('Location: '. $where);
exit;
}
}
If you already have output, I would advise you looking at using output buffering.
You can easily redirect using following header("Location: ....) syntax:
header("Location: main.php");
exit;
You should equip your project with this function first as others have pointed. Alternatively refactor your code to use the builtin php function -> http://php.net/manual/en/function.http-redirect.php

How to redirect with php

I have a register form for member. But when member registered in my website i want automatically open wellcome.php page. I know it is header("Location: wellcome.php"); but i did it and nothing happen. What can i do? Registered is successfully But does not redirect.
<?php
include("includes/connect.php");
session_start();
if(isset($_POST['submit_bregister'])){
$name = $_POST['name'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$re_email = $_POST['re_email'];
$password = sha1($_POST['password']);
$vergi_num = $_POST['vergi_num'];
$sirket_kategorisi = $_POST['sirket_kategorisi'];
$is_kategorin = $_POST['is_kategorin'];
$ulke = $_POST['ulke'];
$sehir = $_POST['sehir'];
if($name==''){
echo"<div class='error_name'>Adınız alanını boş bıraktınız!</div>";
exit();
}
if($surname==''){
echo"<div class='error_name'>Soyadınız alanını boş bıraktınız!</div>";
exit();
}
if($vergi_num==''){
echo"<div class='error_name'>Vergi numaranızı girmediniz!</div>";
exit();
}
if(strlen($vergi_num)>11 || strlen($vergi_num)<0){
echo"<div class='error_name'>Vergi numaranız en az çok 11 hane olabilir!</div>";
exit();
}
if($sirket_kategorisi==''){
echo"<div class='error_name'>Şirket Kategorisi alanını boş bırakamazsınız!</div>";
exit();
}
if($is_kategorisi==''){
echo"<div class='error_name'>İş kategoriniz alanını boş bırakamazsınız!</div>";
exit();
}
if($ulke==''){
echo"<div class='error_name'>Yaşadığınız Ülkeyi boş bırakamazsınız!</div>";
exit();
}
if($sehir==''){
echo"<div class='error_name'>Yaşadığınız Şehir alanını boş bırakamazsınız!</div>";
exit();
}
if($email==''){
echo"<div class='error_name'>E-Mail alanını boş bıraktınız!</div>";
exit();
}
if($_POST['email'] !== $_POST['re_email']){
echo"<div class='error_name'>E-Mail Adresleriniz Eşleşmiyor!</div>";
exit();
}
$check_email = "SELECT * FROM users WHERE email='$email'";
$run = mysql_query($check_email);
if(mysql_num_rows($run)>0){
echo "<div class='error_name'>Bu E-Mail adresi kullanımda!</div>";
exit();
}
$sirket_kategorisi = (int)$sirket_kategorisi;
$query = "SELECT is_kategorisi FROM business_category WHERE id='$sirket_kategorisi'";
$res = mysql_query($query);
$row = mysql_fetch_assoc($res);
$sirket_kategorisi = $row['is_kategorisi'];
$querys ="INSERT INTO `users` (`name`,`surname`,`email`, `re_email`,`password`,`vergi_num`,`sirket_kategorisi`,`is_kategorin`,`ulke`,`sehir`)
VALUES ('$name','$surname','$email', '$re_email','$password','$vergi_num','$sirket_kategorisi','$is_kategorin','$ulke','$sehir')";
$result = mysql_query($querys) or die(mysql_error());
if($result){
header('Location: email');
exit;
}
else {
header('Location: error');
exit;
}
}
?>
The headers cannot be sent after there is any output on the page. The echo is an output, so you cannot send any new headers – in you case the Location header.
You should have the redirect before the echo.
Are you sure this header("Location: wellcome.php"); is at the end of your code?
What i mean with that is for example if you have an if what waits for the Get argument, something like:
if(isset($_GET['register']){
//... code for registration
}
please make sure that the header("Location: wellcome.php"); is at the end of if but inside of the bracket, and its good to use exit(); after the header.
Also you cant echo something before the header();, you should have an error when you do that, check if you are getting one.
Some of your code will help a lot to figure whats wrong.
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
<html>
<?php
/* This will give an error. Note the output
* above, which is before the header() call */
header('Location: http://www.example.com/');
exit;
?>
Normally something like this will result in a Cannot modify header information - headers already warning unless you don't have error/warning reporting turned on.
PHP doesn't allow output before header becuase it will redirect to the page straight away using header(), so there is no point outputting a message before you use it. If you try it will cause an error.
You could, however, add in the header of that page
<meta http-equiv="refresh" content="5;url='http://www.your-website.com/welcome.php'" />
The content attr is broken down into 2 sections time(sec) and url i.e.
content="(time in seconds) ; url='(url)'"
You can change either of these, however, make sure you keep them both inside content=""

Php Header command working in one file but not working on other

hye ,
My current Directory structure is like
Admin (index.php, country.php)
Classes(connection.php,login.php,country.php)
header.php
footer.php
index.php
includes(header.php,footer.php)
my problem is that on webserver when i am in /admin/country.php and add a country using form post method and action set to /classes/country.php my header statement "Header("Location: ../Admin/country.php")" is working ok but when i am on my index page in root directory and try to login with form action "classes/login.php" and on successful login i use header("Location: ../Admin/index.php") it never redirects but everything works fine my local server, i don't know whats the problem over here, Any help would be really appreciated,
I have searched this forum and others and tried to use the techniques they have told but nothing is working
my index page index.php
my Admin Section Admin/Country.php
my login.php script is below
<?php
ob_start();
include_once("classes/connection.php");
?>
<?php
class login
{
public static function validateLogin($userName,$password)
{
if(isset($userName) && isset($password))
{
$connection = dbconnection::getConnection();
$query = "Select * from tbllogin Where loginID ='" . $userName .
"' and password = '" . $password . "'";
$result = mysql_query($query);
$rowsAffected = mysql_affected_rows();
if($rowsAffected==0)
{
//header("Location: ../index.php/");
//exit();
return false;
}
else
{
while($row = mysql_fetch_array($result))
{
//working
$role = $row["role"];
if($role == "Admin")
{
//header('Location: ../Admin/index.php');
//exit();
return true;
}
else
{
//echo "hello";
//header("Location: ../index.php/");
//exit();
return false;
}
//return $result;
//header("Location: ../index.php");
}
}
}
else
{
//header("Location: ../index.php/");
return false;
}
}
}
?>
<?php
if(isset($_POST["btnSumbit"]))
{
$isValid = login::validateLogin($_POST["userID"],$_POST["password"]);
if(isset($isValid))
{
if($isValid ==true)
{
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'Admin/index.php';
header("Location: http://$host$uri/$extra");
exit();
}
}
}
ob_end_flush();
?>
Don't use header redirects with relative paths. You should redirect to the front end URL path or absolute paths.
It's possible that your "classes/login.php" is an included file into "index.php" -- so you're actually trying to step out of the web server directory - which is why it works locally but not on the server.

Categories