aidangig February 2016

PHP if/else is not functioning properly

enter image description hereI am trying to use an if/else statement in PHP. Currently what I am trying to do is if the $_SESSION['usr']; is equal to the current directory ($dir_auth2) variable that the user is trying to access. Then they can access the directory or index.php I have in it. Else, if the $_SESSION['usr']; is != to the current directory, then redirect them to home page. Currently, when a user types in somebody else's directory, that is not theres they can access it.

<?php
session_name('tzLogin');
session_set_cookie_params(2*7*24*60*60);
session_start();
//This if statement below is the problem
if($_SESSION['usr'] == $dir_auth1) {
  //This demo.php is the home page
  header("Location: demo.php");

} else {
  echo "You are logged in as " . $dir_auth1;
} 



$dir = getcwd();
$dir1 = str_replace('/home/pophub/public_html/', '/', $dir);


$dir_auth = getcwd();
$dir_auth1 = str_replace('/home/pophub/public_html/gallry/', '', $dir_auth);
echo $_SESSION['usr'];
echo $dir_auth1;

 $dir_user = getcwd();
 $dir_user1 = str_replace('/home/pophub/public_html/gallry', '', $dir_user);


?>

Answers


radoh February 2016

Either you haven't posted the whole script or you don't define $dir_auth2 anywhere. Which is bad since you rely on its value in

if($_SESSION['usr'] == $dir_auth2) {

Also, you should use die() after calling header()

header("Location: demo.php");
die();

How to make a redirect in PHP?


WheatBeak February 2016

I think this is what you're looking for.

You need to define the variable $dir_auth1 before trying to use it in the if/else statement.

Also I think what you want is != instead of ==

<?php
session_name('tzLogin');
session_set_cookie_params(2*7*24*60*60);
session_start();

$dir = getcwd();
$dir1 = str_replace('/home/pophub/public_html/', '/', $dir);
$dir_auth = getcwd();
$dir_auth1 = str_replace('/home/pophub/public_html/gallry/', '', $dir_auth);
$dir_user = getcwd();
$dir_user1 = str_replace('/home/pophub/public_html/gallry', '', $dir_user);


if($_SESSION['usr'] != $dir_auth1) {
    header("Location: demo.php");
} else {
    echo "You are logged in as " . $dir_auth1;
} 
?>

Also you can combine all of your string functions into one like so:

$dir_auth1 = str_replace(array("/home/pophub/public_html/","/home/pophub/public_html/gallry/"),"",getcwd());

Post Status

Asked in February 2016
Viewed 3,895 times
Voted 4
Answered 2 times

Search




Leave an answer