Header() function not working properly - php

Whenever verifyUser is returned true then the if statement should execute but for some reason instead of going to the header location, the page just refreshes and that's all that happens. I've checked to be sure that the input information is correct and it is and when the information is incorrect the else statement executes perfectly fine. If anyone has any ideas as to why this is happening, please let me know. Thank you.
Here is the segment where the header() statement is made:
function validateUser($name, $pass)
{
$check = verifyUser($name, md5($pass));
if($check)
{
$_SESSION['status'] = 'authorized';
header('location: index.php');
} else{
echo'Please enter a correct username and password <br />';
echo "<a href='http://localhost/cms/admin/login.php'>Try Again?</a>";
exit;
}
}
Here is the verifyUser function just in case anyone needs it.
function verifyUser($name, $pass)
{
// Escape strings
$username = mysql_real_escape_string($name);
$password = mysql_real_escape_string($pass);
$result = mysql_query("select * from users where username='$username' and password='$password' limit 1");
if (mysql_num_rows($result)>0)
{
return true;
} else{
return false;
}
}

The most common reason that header() doesn't work is because something else has been output first. header() can only be called before anything else has sent output to the browser.
If this is the case, PHP will throw an error when header() is called. If you're not displaying errors on the page, you can check your error logs to see if this is happening.
You should also call die() or exit() immediately after (or a soon as possible after) the header() call, to prevent anything else from happening after the redirect header. It's unlikely but possible that something later in the program could also cause the redirect to fail even where the initial header() call succeeded.

Try using "url" instead of "location":
header("refresh:1;url=index.php");

You can put this line in your project at very first line (actually before sending any output), otherwise header function never will work after sending any output (e.g. html code or echo print etc);
ob_start();
Or, check that are headers already sent before sending new headers;
if(!headers_send()){
header("header params...");
} else {
echo "<script>window.location.href="index.php"</script>";
}

check to make sure that $_SESSION['status'] = 'authorized'; is defined

In mysql query use quotes on variable names as follows:
mysql_query("select * from users where username="'".$username."'" and password="'".$password."'" limit 1");

Related

wrong webpage rendered on user error

I am currently writing a page of a website, and I have a function that renders a new webpage to tell the user that they made an error if the date they have selected is in the past. The function looks like this:
if($interval < 0){
handle_error($dbval_date_error2);
}
If the user did put in a valid date, then the date is stored in a database and a new webpage is displayed which shows the new data entry.
The problem I have is that the handle_error function appears not to work usually. It functions exactly as it should if I also include some kind of print statement:
if($interval < 0){
handle_error($dbval_date_error2);
echo "here";
}
But if I just have the error function on its own, the function call just gets completely ignored and the entry gets stored in the database.
The error function looks like this:
function handle_error($error)
{
$_SESSION['error'] = $error;
header('location:../register/register.php');
}
The problem lies in how you're constructing your header; there needs to be a space between the colon and the path, Location needs to be uppercase, and you need to call exit(); after you set the header.
function handle_error($error)
{
$_SESSION['error'] = $error;
header('Location: ../register/register.php');
exit();
}
Just add an exit() after your header():
function handle_error($error)
{
$_SESSION['error'] = $error;
header('location:../register/register.php');
exit();
}
And it should work

Redirect if binding parameters returns an error

I am trying to have my page redirect to another script which will display all error messages if there should be any. Here is what I am trying to do:
//Prepare statement
$checkCode = $conn->prepare("SELECT COUNT(code) FROM subscribers WHERE code LIKE ?");
if(!$checkCode){
header('Location:'.$errorURL."?&notification=prepareFailed");
die();
}else{
$checkCode->bind_param("s", $code);
if(!$checkcode){
header('Location:'.$errorURL."?&notification=bindParamFailed");
die();
}else{
$checkCode->execute();
if(!$checkCode){
header('Location:'.$errorURL."?&notification=executeFailed");
die();
else{
//store result in a variable etc.}
}
$conn and $errorURL are obviously declared. $code is previously retrieved from the database.
This code redirects me to the page whose URL ends in bindParamFailed, therefore the error comes from the bind_param statement. If I comment out the if(!$checkCode){...} part it work like a charm.
Why is it not working? Any ideas?
Are there any other (maybe more intelligent) ways of programming such a custom error page?
While the $conn->prepare() statement will return boolean false into the variable $checkCode on failure, the other calls you are making on the $checkCode object will not modify the object. It will still be "truthy", so if ($checkCode) isn't meaningful and the error states will never be entered, even if the bind/execute code fails.
Instead you need to check the values returned by those method calls for success or failure instead of checking if ($checkCode) again. I'd recommend refactoring it into a chain of if(), each of which has the potential to redirect away.
//Prepare statement
// If this fails, $checkCode will indeed be boolean false
$checkCode = $conn->prepare("SELECT COUNT(code) FROM subscribers WHERE code LIKE ?");
if(!$checkCode){
header('Location:'.$errorURL."?&notification=prepareFailed");
die();
}
// No need for the else because you cannot reach this code unless the previous
// block was true -- it would redirect away on error.
if (!$checkCode->bind_param("s", $code)) {
header('Location:'.$errorURL."?&notification=bindParamFailed");
die();
}
// Same here...
if (!$checkCode->execute()) {
header('Location:'.$errorURL."?&notification=executeFailed");
die();
}
// All is well, store the variable
// and perform the rest of your code...
This could be refactored a little more to call header() only once and set an error string on the prior errors.
//Prepare statement
$checkCode = $conn->prepare("SELECT COUNT(code) FROM subscribers WHERE code LIKE ?");
if(!$checkCode){
$err = "prepareFailed";
}
// On subsequent checks, test that the $err variable is still empty
// If it isn't, that section will be skipped and you'll fall through to the
// redirection header() call.
if (empty($err)) {
if (!$checkCode->bind_param("s", $code)) {
$err = "bindParamFailed";
}
}
if (empty($err)) {
if (!$checkCode->execute()) {
$err = "executeFailed";
}
}
// Now, if the $err string is non-empty, redirect with the message
if (!empty($err)) {
header('Location:'.$errorURL."?&notification=$err");
die();
}
else {
// All is well, store the variable
// and perform the rest of your code...
}
This might be because of case sensitive variable names. First you use $checkCode = ... (camel case) and ghen you check if ($checkcode) (lowercase). Maybe the lowercase var is simply undefined...

Check result of PHP include

I've got my login and session validity functions all set up and running.
What I would like to do is include this file at the beginning of every page and based on the output of this file it would either present the desired information or, if the user is not logged in simply show the login form (which is an include).
How would I go about doing this? I wouldn't mind using an IF statement to test the output of the include but I've no idea how to go about getting this input.
Currently the login/session functions return true or false based on what happens.
Thanks.
EDIT: This is some of the code used in my login/session check but I would like my main file to basically know if the included file (the code below) has returned true of false.
if ($req_method == "POST"){
$uName = mysql_real_escape_string($_POST['uName']);
$pWD = mysql_real_escape_string($_POST['pWD']);
if (login($uName, $pWD, $db) == true){
echo "true"; //Login Sucessful
return true;
} else {
echo "false";
return false;
}
} else {
if (session_check($db) == true){
return true;
} else {
return false;
}
}
You could mean
if (include 'session_check.php') { echo "yeah it included ok"; }
or
logincheck.php'
if (some condition) $session_check=true;
else $session_check=false;
someotherpage.php
include 'session_check.php';
if ($session_check) { echo "yes it's true"; }
OR you could be expecting logincheck.php to run and echo "true" in which case you're doing it wrong.
EDIT:
Yes it was the latter. You can't return something from an included file, it's procedure not a function. Do this instead and see above
if (session_check($db) == true){
$session_check=true;
} else {
$session_check=false;
}
Actually..
$session_check=session_check($db);
is enough
Depending on where you want to check this, you may need to declare global $session_check; or you could set a constant instead.
you could have an included file which sets a variable:
<?php
$allOk = true;
and check for it in you main file:
<?php
include "included.php";
if ($allOk) {
echo "go on";
} else {
echo "There's an issue";
}
Your question seems to display some confusion about how php includes work, so I'm going to explain them a little and I think that'll solve your problem.
When you include something in PHP, it is exactly like running the code on that page without an include, just like if you copied and pasted. So you can do this:
includeme.php
$hello = 'world';
main.php
include 'includeme.php';
print $hello;
and that will print 'world'.
Unlike other languages, there is also no restriction about where an include file is placed in PHP. So you can do this too:
if ($whatever = true) {
include 'includeme.php';
}
Now both of these are considered 'bad code'. The first because you are using the global scope to pass information around and the second because you are running globally scoped stuff in an include on purpose.
For 'good' code, all included files should be classes and you should create a new instance of that class and do stuff, but that is a different discussion.

Another command to replace exit in php?

is there any any other command we can use as an alternative to exit(); in php.
Because it breaks my html code at the end of the page if the condition is not met and when script has to exit.
Or if anyone has any other idea to resolve this issue???
Thanks
Update:
html code...
<?php
if username is not in correct format
echo "Please check your username";
exit();
if Username and Password didn't match
echo "Wrong Username or Password.";
exit();
if some other condition not met
echo "Condition not met";
exit();
?>
html code continues...
Now the problem is if any of the condition is not met and the script has to exit, the html code below it, which is a whole webpage, does not display...
And please...I am not a computer geek, had a problem so asked it, but why people vote down the question??? don't understand....
You should probably wrap your code into an if statement:
<?php
if($code == 'ok'){
echo 'ok';
} else {
echo 'not ok';
}
?>
your script doesn't have to exit(), you can add statements where you want and how you want.
As the name suggests, the PHP exit() statement will cause your PHP script to exit, right there and then, and not do anything else. If you want it to carry on processing the rest of the code, just don't use exit().
Looking at your code, what you seem to be aiming for is displaying errors to the user, and then (I would guess) re-showing the form they filled in incorrectly.
Rather than just echoing the errors as soon as you discover them, why not store them into a variable, which can then be displayed at an appropriate point in the HTML? Even the most basic of scripts can benefit from a bit of basic code structure.
As an example (and I stress this is not the One True Pattern for this kind of thing), you could arrange your file something like this:
if ( /* form has been submitted */ )
{
$errors = validate_form();
if ( count($errors) > 0 )
{
display_form($errors);
}
else
{
display_success_message();
}
}
else
{
display_form();
}
function validate_form()
{
$errors = array();
// Series of if conditions, each adding a message to $errors if appropriate
return $errors;
}
function display_form($errors=array())
{
// HTML <ul> list displaying the contents of $errors, if any
// HTML for form
}
function display_success_message()
{
// HTML thanking user for a successful form submission
}

cookie won't set

This is a question regarding an old one of mine: cookie won't unset:
cookie wont unset
where I had problems unseting the cookie (but it was set 'properly'),
Now that the problem is solved; the cookie doesn't seem to SET
cookie 'set': (does not work)
setcookie("id",$data['id'], time()+3600*24*30,'/');
setcookie("alias",$data['nombre'], time()+3600*24*30,'/');
cookie check: (seems to work)
function sesion(){
if(isset($_COOKIE['id']) && isset($_COOKIE['alias'])){
$_SESSION['logueado'] = true;
$_SESSION['id'] = $_COOKIE['id'];
$_SESSION['alias'] = $_COOKIE['alias'];
return true; //THIS IS NEVER RETURNING TRUE
}
if(isset($_SESSION['id']) && isset($_SESSION['logueado']) && $_SESSION['logueado'] == true){
return true;
}
else{ return false;
}
}
cookie unset: (works)
function cerrar_sesion(){
session_start();
$_SESSION['logueado']= false;
$_SESSION['id']= NULL;
session_unset();
session_destroy();
setcookie("id",false,time()-3600,"/");
setcookie("alias",false,time()-3600,"/");
unset($_COOKIE['id']);
unset($_COOKIE['alias']);
}
What happens is that login is working only through $_SESSION so after 30 minutes of no activity the user is no longer logged in,
Any idea what I'm doing wrong? Thanks a lot!
As stated above you cannot read a cookie from the same page as it is set. I see you have tried tricking this using ajax but i do not believe that would be a valid trick as Ajax calls do not change the state of the page you are still on. so you can either do a full refresh or redirect OR at the same time you use setcookie you can also define the values you need in $_COOKIE so its available on the same page. like this:
setcookie("id",$data['id'], time()+3600*24*30,'/');
setcookie("alias",$data['nombre'], time()+3600*24*30,'/');
$_COOKIE['id'] = $data['id'];
$_COOKIE['alias'] = $data['nombre'];
set cookie lines work fine with me.
as for }else if(isset($_COOKIE['id']) && i
since you return if you remove the else here is still okay, if there was no return above you would have to keep the else here in order not to evaluate this block
generally speaking I am not sure that elseif is the same with else if in all cases
The way the function session is build will act like this:
On the first load it will show: no cookie, no session because you cannot see a cookie until reload (which I guess you already know).
-On second load you will see cookie alive session set.
-after the second load you always see session is set.
All I want to say that session works exactly as expected to work, so I don't really see any problem.
<?php
$data='Hello';
setcookie("id",$data['id'], time()+3600*24*30,'/');
setcookie("alias",$data['nombre'], time()+3600*24*30,'/');
session_start();
function sesion()
{
if(isset($_SESSION['id']) && isset($_SESSION['logueado'])
&& $_SESSION['logueado'] == true)
{
echo 'SESSION IS SET<br>';
return true;
}
if(isset($_COOKIE['id']) && isset($_COOKIE['alias']))
{
$_SESSION['logueado'] = true;
$_SESSION['id'] = $_COOKIE['id'];
$_SESSION['alias'] = $_COOKIE['alias'];
echo 'COOKIE is alive and session set'.$_SESSION['alias'].'<br>';
return true; //THIS IS NEVER RETURNING TRUE
}
else
{
echo 'NO SESSION, NO COOKIE YET, WAIT UNTIL REFRESH<br>';
return false;
}
}
sesion() ;
?>
Try removing the path parameter from your setcookie() calls, maybe that's the issue.
Also, did you check that $data actually contains any data?
Propably you have really known problem with setting cookies and you have disabled error reporting about warnings.
Just try:
error_reporting(E_ALL);
You will propably see at your page something like "Cannot modify headers. Headers already sent". That because you need to SET cookies before you display anything on your page. So solution to resolve your problem is to implement your code to SET cookies at the bottom of your page or use ob_start/ob_clean.
Let me know if it helps :)
According to the "setcookie()" implementation in PHP, the cookie value check will not work until you move the control from the page that you are creating the cookie. So, your "SET" will create the cookie in one page and "sesion()" should be called from other page to check the value of the cookie that you set. Try it and hope it helps!
Try the following approach (please refine this as per your need). What I am trying here to refresh the page itself after setting the cookie and the "sesion()" function is a dynamic function that may or may not have any arguments. So, when you pass any argument to it, the the cookie will be set, otherwise it will be checked for existence. An accompanying function with func_num_args() is func_get_args(). It will help you to sanitize the expected arguments in the function.
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
ini_set("log_errors", 0);
session_start();
function sesion(){
// func_num_args() number of arguments passed to the function
if (func_num_args() == 0) { // if no arguments were passed, means the page is refreshed and cookie won't be set further
if(isset($_COOKIE['id']) && isset($_COOKIE['alias'])){
$_SESSION['logueado'] = true;
$_SESSION['id'] = $_COOKIE['id'];
$_SESSION['alias'] = $_COOKIE['alias'];
return true; //THIS IS NEVER RETURNING TRUE
}
if(isset($_SESSION['id']) && isset($_SESSION['logueado']) && $_SESSION['logueado'] == true){
return true;
}
else {
return false;
}
}
else { // if number of args > 0, means you need to cookie here and refresh the page itself
global $data; // set this to global as the $data will be available outside of this function
setcookie("id",$data['id'], time()+3600*24*30,'/');
setcookie("alias",$data['nombre'], time()+3600*24*30,'/');
/**
* refresh the page by javascript instead of header()
* as header already being sent by the session_start()
*/
echo '<script language="javascript">
<!--
window.location.replace("' . $_SERVER['PHP_SELF'] . '");
//-->
</script>';
die();
}
}
sesion(1); // passed an argument to set the cookie
?>
I think you will face issue with the JavaScript section, as it will change the page URL and I guess you are trying to include this script into the pages. So, I will take the help of call_user_func() and the final "else" part after the setcookie() lines will be changed with the following line:
call_user_func("sesion");
Hope this will make sense now.

Categories