Alternative to "header" for re-directs in PHP - php

I am working on a project and I am required to run my program on someone else's webserver. It is a pretty simple login page that I am having the problem with. The program works correctly if I run it through my local host via WAMP. The problem I am having is that the re-direct portion is not working correctly it validates the user and starts a session but when it gets to the redirect nothing happens.
I am either doing something wrong with my syntax which I think is highly unlikely since it does work correctly through my local host. Or alternatively I'm thinking that the server does not have that function (not sure if its possible to pick and choose which modules your server supports although I'm sure it's feasible).
I don't know if it matters but they are using "cpanel" which is where I can access the files and there all in the same directory so if someone could tell me where I am going wrong or suggest an alternative to redirecting via "header" any help would be greatly appreciated. I've looked around but it seems that "header" is the standard work horse.
Heres the code I have:
if( (!empty($_POST['username'])) && (!empty($_POST['password'])) )
{
// username and password sent from Form
$myusername = $_POST['username'];
$mypassword = $_POST['password'];
$sql="SELECT UserName FROM User WHERE UserName='$myusername' and Password='$mypassword'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
//$active=$row['active'];
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1)
{
echo "we made if to the if";
session_start();
session_register("myusername");
$_SESSION['login_user']=$myusername;
echo "right b4 the re-direct";
header("location: UI.php");
exit;
}
else
echo "Your user name/password was not correct pleast TRY AGAIN!!!";
}
Update: In response to the statements about the echos would the problem possible by that I am processing my form in the same file and using echo $_SERVER['PHP_SELF']

I use this function for redirect...
Which works in all situations..even if headers are already sent..or even javascript is disabled..
function redirect($url)
{
if (!headers_sent())
{
header('Location: '.$url);
exit;
}
else
{
echo '<script type="text/javascript">';
echo 'window.location.href="'.$url.'";';
echo '</script>';
echo '<noscript>';
echo '<meta http-equiv="refresh" content="0;url='.$url.'" />';
echo '</noscript>'; exit;
}
}

By using the below code we redirect the page
$page = $_SERVER['REQUEST_URI'];
echo '<script type="text/javascript">';
echo 'window.location.href="'.$page.'";';
echo '</script>';

From the docs:
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.
Your echo is causing the redirect to fail, as is any other output sent before the header.

echo "<script>window.location.href='yourPage.php'</script>";

Redirecting via headers is illegal if any content has come through. Take out all the echos and it should work. If you do want there to be a message shown to the user before the redirect, you'll likely have to do it with JavaScript via location.href.

You cannot set headers after outputting some text, so either you move the header call before the echo statements (fine in your case) or you use output buffering.

You probably have already sent content to the browser before the php header is sent.
This can be just a \n after a closing php tag ( ?> )
To find the place where unwanted output is generated canbe hard on bigger projects or long lines of classes extending each other.
To find the problem you can do this:
error_reporting(E_ALL);
ini_set("display_errors", 1);
header("Location: https://mydomain.com/myLoginAdress/");
die();
Strict error reporting will throw line and file of the output.

Use This Code
Syntax :
echo '<script type="text/javascript"> window.location="<Your_URL>";</script>';
write this line insted of header("location: UI.php");
echo '<script type="text/javascript"> window.location="UI.php";</script>';

Related

Session not set till page reload?

So after a LOT of trial and error, I set up something to test whether my session is set or not, which looks like this :
<?php
session_start();
if (isset($_SESSION['email'])) {
echo "Logged In!";
}
else {
echo "NOT LOGGED IN!";
}
?>
And what I realize is that after Login ( which redirects to the site's homepage) The session is not set until I reload the entire homepagepage.
Has anyone experienced anything like this and/or knows how to get around such a problem?
Thanks in advance!
This snippet of code works for me as a test. Make sure your order of operations matches this. If that does not work, make sure you are allowing cookies in your browser. Failing that, there could be something screwy about your PHP/Apache configuration.
<?php
session_start();
if (!isset($_GET['test']))
{
$_SESSION['email'] = "something ".time();
header('location:?test');
die;
}else{
echo 'Value: "' .$_SESSION['email']. '"';
echo '<br /><br />< Do again';
die;
}
?>
Your pages need to be set up like so in this order (particularly the session_start()):
login.php
<?php
session_start();
// 1) Some code here to check database if username and password check out
// 2) If username and password check out and validation is good
// 3) Redirect to your next page (index.php in this case)
?>
index.php (home page)
<?php
session_start();
?><!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1><?php
if(isset($_SESSION['email'])) { ?>
EMAIL IS SET!! Great job!
<?php } else { ?>
UM...No..<?php } ?></h1>
</body>
</html>
I was having a horrible time with this. I have an index page that loads every time and inside a content div loads specific php scripts via include. I control the navigation of the website in this way by passing GET variables to the index.html, so my index page loads every single time no matter what content you're viewing. The very first line of index.html was:
<?php
session_start();
Some of my php scripts running as includes on the index page would set session variables then redirect to the index page and the session variable would not be there,, or they would not be set to what they should be. It was driving me mad, I could ctrl-F5 and sometimes they would show up and sometimes not. The only thing I can figure was that it was somehow opening different sessions for different urls that were in the address bar (by different urls I mean ones with different GET parameters. Simply putting this at the beginning of my index.html solved all my problems. I assume this causes the same session to open each time:
<?php
session_name('SessName');
session_start();
Thanks for all the help guys, but I found the problem.
Apparently I have to be extremely specific with my url in the redirect file.
I had header('location: http://domain.com');
instead of
header('location: http://www.domain.com');
...facepalm

PHP Should I use ob_clean after ob_start

I made a simple login-system in php and mysql, but I keep getting errors saying that headers already been sent, and using ob_start fixes this problem, but im not sure if I should then use ob_clean at the footer afterward?
Also, the error comes when I have logged in to the account page, saying header already been sent in previuos page - > header("Location: account.php"); But I have to redirect the user when they login.
My login page looks like this
require_once('models/init.php'); // db connection and other functions
include('header.php'); // some html code for the header, with one line php-function to check if user is logged in, if so show "home" tab instead of "login"
{
php code to check if username/pass matches etc, and if so redirect to account page
header("Location: account.php");
}
echo "<form>" // display the login form
include("footer"); // including footer, some html/js code.
This code above works if I use ob_start in the header.php file. But should I use ob_clean afterwards in the footer.php file?
Sorry if anything is unclear, english is not my first languish
Thanks!
The general principle is you cannot use echo before header(). So, this will never work:
echo "this is my header";
header("Location: account.php");
echo "this is my footer";
However, if you sent the headers first, everything works fine:
header("Location: account.php");
echo "this is my header";
echo "this is my footer";
In your case, you should do the check before you include the header:
require_once('models/init.php'); // db connection and other functions
if ($user_is_logged_in) { // Do your check here
header("Location: account.php");
}
include('header.php'); // some html code for the header, with one line php-function to check if user is logged in, if so show "home" tab instead of "login"
echo "<form>" // display the login form
include("footer"); // including footer, some html/js code.
ob_start() captures the output (what would otherwise be printed or echoed). If you don't need to echo the output or to do anything with it then just use ob_end_flush() when you are finished.

why doesn't my php redirect work?

Im writing a login script. My db.php doesnt echo/print anything so why doesnt header("Location: index.php"); redirect upon successful login? the login info is correct. I know i need to sanitize the input but that is not a problem at the moment.
<?php
require('db.php');
$username = $_POST['un'];
$password = $_POST['pw'];
$qry="SELECT uid FROM users WHERE name='$username' AND pass='".md5($password)."'";
$result=mysql_query($qry);
if(mysql_num_rows($result) == 1){
session_regenerate_id();
$user = mysql_fetch_assoc($result);
$_SESSION['S_UID'] = $user['uid'];
session_write_close();
header("Location: index.php");
exit();
}else{
echo "<center><form action='index.php' name='login'>Login failed! Please try again with correct username and password.<br><input type='submit' name='failed' value='Return to Login'></form></center>";
exit();
}
?>
the function header will only work if no output has been sent by the script before the function is called. Check if any codes above has echoed something.
If not, check that the include files above do not have an extra space or newline after the closing "?>" tag. Otherwise this space or newline will be sent to the browser before your header.
Are you sure no output is being produced anywhere in the script (or db.php)? Not even a few extraneous spaces ?
Try using the full URL for example:
header("Location: http://www.mysite.com/index.php");
Some browsers (thanks IE) doesn't understand the 301 redirect code with uncompleted URI.
This header location behavior in PHP is a good tool, but easy to be implemented in the incorrect scenario...for this purpose i would consider using require() instead of header(location)
like:
if (!imLoggedIn()){
require('loginForm.php');
exit;
}

Redirects - alternative to "<meta http-equiv='refresh' />"? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Best redirect methods?
Hello
I am working with some legacy code that includes a module for user registration / login. There is a block that queries the DB to see if the user is logged in, then re-directs to the login page.
The re-direct is handled by <meta http-equiv='refresh' content='=2;index.php' /> but I have since learnt this is depreciated, and doesn't work in all browsers.
Is there an alternative way to put a re-direct within the code below?
$username = mysql_real_escape_string($_POST['username']);
$password = md5(mysql_real_escape_string($_POST['password']));
$checklogin = mysql_query("SELECT * FROM users WHERE username = '".$username."' AND password = '".$password."'");
if(mysql_num_rows($checklogin) == 1)
{
$row = mysql_fetch_array($checklogin);
$email = $row['email'];
$_SESSION['username'] = $username;
$_SESSION['email'] = $email;
$_SESSION['LoggedIn'] = 1;
echo "<h1>Success</h1>";
echo "<p>We are now redirecting you</p>";
echo "<meta http-equiv='refresh' content='=2;index.php' />";
}
else
{
echo "<h2>Error</h2>";
echo "<p>Sorry, your account could not be found. Please click here to try again.</p>";
}
Many thanks for any pointers.
META refresh is not deprecated. Your refresh tag has an extra =. It should be
<meta http-equiv='refresh' content='2;index.php' />
You can do a refresh with a header too:
header("Refresh: 2;index.php");
Or use 302 redirection:
header("Location: /index.php");
Or do it in Javascript.
And the best method? Use a META refresh tag in the <head> section. Rationale for this is that IE does not save headers when it uses cached version of a page.
You can use header() before any content is sent to the server:
header("Location: index.php");
die();
this will send the browser a 302 response and cause it to open the other page instead.
Always make sure you DO NOT output any content after issuing a `header("Location"). Anything you output will still be sent to the browser!
The easiest way to achieve that is usually issuing a die() after the header("Location:") call.
In addition to the header function mentioned by Pekka, you could alternatively use javascript - this is the behavior intended to replace the meta refresh which has been deprecated.
<script>top.location = 'index.php';</script>
Simply replace your meta line with the above.
You can even add a timeout as follows:
<script>setTimeout('top.location = \'index.php\'', 2000);</script>
The above will wait 2 seconds before redirecting.
header ("Location: index.php?success=1");
exit;
and in index.php
if (!empty ($_GET['success'])) {
echo "<h1>Success</h1>";
}
First of all: Meta is only allowed in the head-section of a HTML-document so putting it out after h1 and p in the body is wrong and won't work at all in most browsers.
For showing a message for 2 seconds and redirect afterwards you'd have to use javascript, php can't do that for you.
Plain javascript would be using setTimeout (value in milliseconds)
setTimeout("location.href = 'index.php';",2000);
If you want to use jQuery you could use the delay()-function.

Do all header("Location: member.php?id=$username") have to be the first thing in a script? (PHP)

I know in the Manuel it says that the header has to be the first thing in a script, but how come I see some codes where header("Location: member.php?id=$username") is in a if-statement?
Ex:
//a bunch of codes above
if($result!="0"){
// authenication correct lets login
$_SESSION["password"] = $password;;
$_SESSION["username"] = $username;
header("Location: member.php?id=$username");
}
else
{
echo "Wrong username or password. Please try again!";
}
But when I do this, it sometimes would/won't throw an error.
How do I allow the header (); to be used in a script without any errors?
I want to redirect the user back to the login if they click "no" and to the homepage if they click "yes".
It doesn't have to be the first thing in the script. But it haves to be the first thing that you output to the user. You MUST NOT echo stuff before using the header function. If you don't, you can use it at any place you want.
You could also "ignore output" using ob_start and ob_end_clean.
Best regards,
T.
You have to use output buffering so that nothing is sent back to the browser until the entire operation is complete. Check out the ob_start function, that should give you a good starting place.
ob_start
Without output buffering, the script sends header info back to the browser, and once that has happened you cannot use header() to redirect.
header('Location: member.php?id='.$username);
You might want to change and use this code instead if you are just going to send or $_GET['username'] an value from your previous session.

Categories