0

I have this code right here:

if(isset($_SESSION['username'])) {
    header("location: home.php");
    exit();
}

This code works, but I want it to redirect to home.php with out having to visit a different page and then the page this code is on to trigger the code. I don't know how to do that. But for some reason it does not work how I want it to, because this only triggers when the person is logged in and then opens another tab on their browser an visits this page with the code to redirect them back to the home.php page, without having to go to another page and then to the page with this code again to make this code work.

4
Contributors
14
Replies
19
Views
4 Years
Discussion Span
Last Post by Djmann1013
Featured Replies
  • **@Djmann1013** >This code works, but I want it to redirect to home.php with out having to visit a different page and then the page this code is on to trigger the code. if(isset($_SESSION['username'])) { header("location: home.php"); exit(); } You need to put this: session_start(); on all of your pages. You … Read More

  • **@Djmann1013** >I use the session_start(); on all the pages, just this code did not have it. Yes, I did add a session_start() at the top of the page. You know you never mention whether it work on or not? If not post your whole session code. Read More

  • **@Djmann1013** Before this **PHP Session Detection** issue did you resolve this issue first: http://www.daniweb.com/web-development/php/threads/439685/php-sessions Read More

  • **@Djmann1013** if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { $_SESSION['inactive'] = $_SESSION['inactive'] + 20; } Did you get a chance read this carefully on the pink box: http://php.net/manual/en/function.ob-start.php I post it here: `Some web servers (e.g. Apache) change the working directory of a script when calling the callback function. You can change … Read More

  • Thanks guys. I am actually revamping my site because of this outdated code, dulplicates of code blocks, and other major problems. Thanks for helping me. Read More

2

@Djmann1013

This code works, but I want it to redirect to home.php with out having to visit a different page and then the page this code is on to trigger the code.

if(isset($_SESSION['username'])) {
header("location: home.php");
exit();
}

You need to put this:

session_start();

on all of your pages.

You can try this too:

<?
session_start();
$_SESSION['username'];
session_write_close();
header("Location: home.php");
}
?>

Edited by LastMitch: grammer

0

I don't get what you are trying to do.

The code will check to see if $_SESSION['username'] has been set, this usually indicates that a user is logged in.
If it is set (they are logged in), the user will be redirected to home.php.

If you want to redirect users that aren't logged in, use
if(!isset($_SESSION['username'])){ ...

If you want to redirect everyone, remove the IF

p.s. Don't forget to use session_start(); at the top of the page.

Edited by Zagga

0

I use the session_start(); on all the pages, just this code did not have it. Yes, I did add a session_start() at the top of the page.

3

@Djmann1013

I use the session_start(); on all the pages, just this code did not have it. Yes, I did add a session_start() at the top of the page.

You know you never mention whether it work on or not?

If not post your whole session code.

0
<?php
ob_start();

session_start();

if(isset($_SESSION['username'])) {
    header("location: home.php");
    exit();
}

ob_flush();
?>
0

THis really looks overcooked to me. Is there any reason that you're using output buffers?

I'm assuming that this code sends logged in users to the home page - so in effect, logged in users are not allowed to see this page, although users not logged in are.

0

@diafol I have the ob_start(); it is because I have more than one header(); on the page, it gives me an error. And, yes, the user not logged in can see the page. But, the user logged in cannot. This is because I don't want the user to have to log in again and again.

Edited by Djmann1013: Edits

0

Ok, it is alot, but, here it is.

index.php

<?php

session_start();

//core files
include('/home/public_html/core/init.inc.php');

include('/home/public_html/sess.php');

mysql_connect('localhost', 'root', '');
mysql_select_db('db');



$result = mysql_query("SELECT * FROM logo WHERE id='1'") or die(mysql_error());

$row = mysql_fetch_array($result);

$image = $row['url'];

?>

<!DOCTYPE html>

<html>

<head>

<!-- CSS Includes -->
<link type="text/css" rel="stylesheet" href="css/menu_styles.css">
<link type="text/css" rel="stylesheet" href="css/theme.css">

<!--Favicon-->
<link rel="icon" href="http://i.imgur.com/Z3FJn.png" type="image/gif"/>

<!-- IE Edge -->
<meta http-equiv="X-UA-Compatible" content="IE=edge" />

<!-- Scripts -->
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>

<script src="http://code.jquery.com/jquery-latest.js"></script>

<!-- Blog Feed -->
<script>

$(document).ready(function(){

    $('#blog').load('rss.php');

});

</script>

<!-- Header Image, might make another header image -->
<center><img src="<?php echo $image; ?>" /></center>

<!-- Title -->
<title>Welcome to AwsomeChat - The Free Social Hangout</title>




</head>

<body>

<!-- Navigation Bar -->
<ul class="menu">
  <li><a href="index.php" class="active"><span>Home</span></a></li>
  <li><a href="login.php"><span>Login</span></a></li>
  <li><a href="signup.php"><span>Signup</span></a></li>
</ul>

<div class="content" id="content" border="0" style="position:relative; /*left:390px;*/ height:1504px; top:10px; border-top-left-radius: 10px; border-top-right-radius: 10px; border-bottom-left-radius: 0px; border-bottom-right-radius: 0px;">
<center><i><? echo $_SESSION['username']; ?></i></center>
<div class="blog" id="blog" style="position:absolute; height:330px; width:350px; top:10px; left:10px; background-color:#FFFFFF;">

</div>


        <b style="position:absolute; top:30px; left:462px;">This is AwsomeChat - a free place just to hang out. This site is made for chatting or socializing with a friend. This site is free, no membership needed to use this site.</b>
        <br />
        <br />
        <br />
        <b style="position:absolute; top:1400px;">&copy Djmann1013 Productions, 2012-2013. All rights reserved.</b>


</div>

</body>
</html>

home.php

<?php 

ob_start();
session_start();

// SESS stuff
$_SESSION['inactive'] = $_SESSION['inactive'] + 20;

include('/home/public_html/session.php');

include('/home/public_html/ban/ban_inc.php');

//core files
include('/home/public_html/core/inc/user.inc.php');

if(!isset($_SESSION['username'])) {
    header("location: login.php");
    exit();
}

mysql_connect('localhost', 'root', '');
mysql_select_db('DB');


$myusername = $_SESSION['username'];

$query = mysql_query("SELECT * FROM $tbl_name WHERE user_username='$myusername'") or die();
$row = mysql_fetch_array($query);

$accepted = $row['accepted'];

// Show admin panel
if ($row['memberstat'] == "Admin" || $row['memberstat'] == "Owner") {     
echo "<br />";
echo "<br />";
echo "<h1>Admin Panel</h1>";
echo "<iframe src='../admin/admin_login.php' width='430' height='210'></iframe>";

} else {

// The person is not an admin or moderator. Don't show the panel.

}

if ($accepted == "0"){
// Have the user see the rules
header( 'Location:../rules/' );
}

$result = mysql_query("SELECT * FROM users WHERE user_username='{$myusername}'"); 

while ($row = mysql_fetch_array($result)) { 

$user_id = $row['user_id']; 
$img = $row['image'];

}
//echo $url; - For testing

$result = mysql_query("SELECT * FROM logo WHERE id='1'") or die(mysql_error());

$row = mysql_fetch_array($result);

$image = $row['url'];

$q = mysql_query("SELECT * FROM embed WHERE id='1'") or die(mysql_error());
$embed = mysql_fetch_array($q) or die(mysql_error());

$URI = $embed['uri'];
$ok = $embed['show_widget'];

$q = mysql_query("SELECT * FROM users WHERE user_username='{$_SESSION['username']}'") or die(mysql_error());

$row = mysql_fetch_array($q);

$online = $row['user_online'];

if($online == 'Online'){

// Do nothing

} else {

// Redirect the user/client
header('Location: login.php');

}

/* AJAX check  */
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
  $_SESSION['inactive'] = $_SESSION['inactive'] + 20;
}

$quert = mysql_query("SELECT * FROM private_messages WHERE sent_to='{$_SESSION['username']}' AND viewed='0'");
$nummsg = mysql_num_rows($quert);

ob_flush();
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="X-UA-Compatible" content="IE=edge" />


    <title>Home - Awsome Chat</title>

        <!--CSS Includes-->
        <link href="/css/menu_styles.css" rel="stylesheet" type="text/css">
        <link type="text/css" rel="stylesheet" href="/css/theme.css">

        <!--Favicon-->
        <link rel="icon" href="http://i.imgur.com/Z3FJn.png" type="image/gif"/>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <!-- Script -->
    <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>
    <script type="text/javascript">

    $(document).ready( function(){

        $("#chats").load("chat/feed.php");

        $("#submitChat").submit( function(){

            $.post('chat/ajaxPost.php', $('#submitChat').serialize(), function(data) {

                $("#messages").append('<div>'+data+'</div>');
                $('#message').val("");
            });
                return false;
        });
});

    setInterval(function(){
        $('#chats').load('chat/feed.php');
    }, 1000);


    </script>
<center><img src="<?php echo $image; ?>" style="padding:0px; margin:2px;"/></center>

<ul class="menu">
    <li><a href="home.php" class="active"><span>Home</span></a></li>
    <li><a href="find.php"><span>People</span></a></li>
    <li><a href="update_profile.php"><span>Update Profile</span></a></li>
    <li><a href="account_settings.php"><span>Account Settings</span></a></li>
    <li><a href="private_messages.php"><span>Private Messages<?php echo "(". $nummsg .")"; ?></span></a></li>
    <li><a href="logout.php"><span>Logout</span></a></li>
</ul>

<title><?php echo $user_info['username']; ?>'s Profile</title>

</head>
    <?php

    mysql_connect('localhost','root', '') or die(mysql_error());
    mysql_select_db('DB') or die(mysql_error());

    $queee = mysql_query("SELECT * FROM notifications WHERE id='1'");
    $row = mysql_fetch_array($queee);

    $M = $row['text'];
    $code = $row['code'];

    if(empty($M)){

        // Do nothing

    } else {

        echo $code;

    }
    ?>
    <br />
    <?php
    $mAl = mysql_query("SELECT * FROM users WHERE user_username='{$_SESSION['username']}'");
    $membe = mysql_fetch_array($mAl);
    $rok = $membe['memberstat'];

    if($rok == "Admin" || $rok == "Owner" || $rok == "Moderator"){

    $quR = mysql_query("SELECT * FROM mod_notifications WHERE id='1'");
    $row1 = mysql_fetch_array($quR);

    $Mo = $row1['text'];
    $codeE = $row1['code'];

    if(empty($Mo)){

        // Do nothing

    } else {

        echo $codeE;

    }

    }
    ?>
    <br />
<body>

<div class="leftBar" style="position:absolute; border-top-left-radius: 10px; border-top-right-radius: 10px; border-bottom-left-radius: 10px; border-bottom-right-radius: 10px; left:10px; background-color:white; /*top:130px;*/ border:1px solid white; height:900px; width:450px;">

<center>

<h3 style="color:red;">Welcome, <?php echo $_SESSION['username']; ?>!</h3>
<br />
<img src="<?php echo $img; ?>" alt="<?php echo $user_info['username']; ?>'s Profile Image" width="150" height="150" style="position:absolute; left:10px; top:50px;"/>
<br />
<br />
<a href="update_profile.php">Edit Profile</a>
<br />
<a href="account_settings.php">Account Settings</a>
<br />
<br />
<br />
<br/ >
<br />
<embed src="http://www.satisfaction.com/christmas-countdown-generator/countdown1.swf" quality="high" bgcolor="#000000" width="450" height="200" name="countdown1" align="middle" allowScriptAccess="samedomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />
<br />
<br />
<?php
if($ok == "Ok"){
    //PARTY :D
    echo "<b>Music</b><br /><br />";
    echo "<iframe src='https://embed.spotify.com/?uri=$URI&theme=white' width='300' height='380' frameborder='0' allowtransparency='true'></iframe><br />";
    echo "<b>To use this widget, you need to download spotify.</b>";
} else {
    //Do nothing.
}
?>
</center>

</div>

<div class="content" style="position:absolute; border-top-left-radius: 10px; border-top-right-radius: 10px; border-bottom-left-radius: 10px; border-bottom-right-radius: 10px; height:900px; width:750px; left:500px;">

<?php

if ($user_info === false) {
echo "User does not exist.";
} else {

?>

<center>
<br />
<br />
    <form id="submitChat" method="POST">

    <input type="hidden" name="username" value="<?php echo $_SESSION['username']; ?>" />
    <input type="hidden" name="image" value="<?php echo $img; ?>" />
    <input type="hidden" name="id" value="<?php echo $user_id; ?>" />
    <label>Message:</label><br />
    <input type="text" maxlength="140" name="message" id="message" size="50"/>
    <br />
    <input type="submit" value="Chat" />

    </form>

<h4>Chat Feed</h4>

<!-- Chat feed -->
<div id="chats"></div>

</center>
<b style="position:absolute; top:850px;">&copy Djmann1013 Productions, 2012-2013.</b>
</div>

<?php
}
?>
</div>

</body>

</html>

user.inc.php

<?php
//user.inc.php file
session_start();

$pages = array('login', 'signup', 'index', 'password_reset');
$page = substr(end(explode('/', $_SERVER['SCRIPT_NAME'])), 0, -4);

if (in_array($page, $pages) === false){

      if (isset($_SESSION['username']) === false){

              header( 'Location: login.php' );
              die();

      }

}

$u_agent = $_SERVER['HTTP_USER_AGENT']; 
$ub = False; 
if(preg_match('/MSIE/i',$u_agent)){
    header('Location:ie.html');
}

// SQL stuff.
mysql_connect('localhost', 'root', '');
mysql_select_db('DB');

// Get users from table
function fetch_users() {
$result = mysql_query('SELECT `user_id` AS `id`, `user_username` AS `username` FROM `users` LIMIT 10');
echo mysql_error();
$users = array();
while($row = mysql_fetch_array($result)) {

    $users[] = $row;
}
return $users;
}
//Checks if user exists.
function user_exists($user){
$user = mysql_real_escape_string($user);

$total = mysql_query("SELECT COUNT('user_id') FROM `users` WHERE `user_username`= '{$user}'");

return (mysql_result($total, 0) == '1') ? true: false;
}

//Checks if user entered the valid login info.
function valid_credentials($user, $pass){
$user = mysql_real_escape_string(htmlentities($user));
$pass = mysql_real_escape_string(htmlentities($pass));

$total = mysql_query("SELECT COUNT('user_id') FROM `users` WHERE `user_username` = '{$user}' AND `user_password` = '{$pass}'");

return (mysql_result($total, 0) == '1') ? true: false;

}

// Adds user to database with the register.php page.
function add_user($user, $pass, $email){
$user = mysql_real_escape_string(htmlentities($user));
$pass = sha1($pass);
$email = mysql_real_escape_string(htmlentities($email));

$bio = "I just signed up!";
$memberstat = "Member";
$banned = "0";
$o = "Online";
$img = "http://i.imgur.com/XV16L.png";

$frm = "Djmann1013";
$snder_id = "1";
$snd_to = $user;

$msg = "Hi, welcome to AwsomeChat!
        I am Djmann1013, the CEO and creator of this site. This site is still in development.
        If you don't like the design, I am working on a new one. So just be patient.

        I hope you enjoy this site, to give feedback by sending me a message.

        ~Djmann1013, CEO and Creator
";
$code = rand();

      $to = $email;
      $from = "support@awsomechat.tk";
      $subject = "Account Verification Email - AwsomeChat";
      $content = "
    hi, $user!

    Click on the link, or copy and paste the URL in your browser:

    http://www.awsomechat.tk/verify.php?code=$code

    ~AwsomeChat Team

     ";
     mail($to,$subject,$content);

// Add the user
mysql_query("INSERT INTO `users` (`user_username`, `user_password`, `user_email`, `banned`, `memberstat`, `user_bio`, `user_online`, `image`, `email_verif`) VALUES ('{$user}', '{$pass}', '{$email}', '{$banned}', '{$memberstat}', '{$bio}', '{$o}', '{$img}', '{$code}')");

// Then, send message (preventing errors by doing this after the account was added into the database)
mysql_query("INSERT INTO private_messages (`sent_to`, `sent_from`, `message`, `sender_id`) VALUES('{$snd_to}', '{$frm}', '{$msg}', '{$snder_id}')");

}
// Fetches the info on a given user with the $user_info['']; function.
function fetch_user_info($uid)  {
   $uid = (int)$uid;
   $sql = "SELECT `user_username` AS `username`, `user_bio` AS `bio` FROM `users` WHERE `user_id` = {$uid}";
   $result = mysql_query($sql);
   return mysql_fetch_assoc($result);
}

// Sets the profile info on the update_profile.php page with the set_user_info
// ANYMORE DATA THAT NEEDS TO BE SAVED, JUST ADD A COMMA AFTER $bio LIKE THIS:
// ($bio, $var) {
// AND ADD THE VAR TO THE CODE BLOCK WITH mysql_real_escape_string(); LIKE THIS:
//
//$bio = mysql_real_escape_string(htmlentities($bio));
//
//$var = mysql_real_escape_string(htmlentities($var));
//

function set_profile_info($bio){
$bio = mysql_real_escape_string(nl2br(htmlentities($bio)));

$sql = "UPDATE `users` SET `user_bio` = '{$bio}' WHERE `user_username` = '{$_SESSION['username']}'";
mysql_query($sql);
}

function send_report($body, $username, $reporter){
$body = mysql_real_escape_string(nl2br(htmlentities($body)));
$username = mysql_real_escape_string(nl2br(htmlentities($username)));
$reporter = mysql_real_escape_string(nl2br(htmlentities($reporter)));

// Add the report....
mysql_query("INSER INTO `report_feed` (`report`, `user_reporting`, `username`) VALUES ('{$body}', '{$reporter}', '$username')");

}
?>

init.inc.php

<?php
session_start();

// SQL stuff.
mysql_connect('localhost','root','');
mysql_select_db('DB');

include('/home/public_html/core/inc/user.inc.php');

$pages = array('login', 'signup', 'index', 'password_reset');
$page = substr(end(explode('/', $_SERVER['SCRIPT_NAME'])), 0, -4);

if (isset($_COOKIE['username'], $_COOKIE['password'])){
    if (valid_credentials($_COOKIE['username'], $_COOKIE['password'])){
       $_SESSION['username'] = htmlentities($_COOKIE['username']);

       setcookie('username', $_COOKIE['username'], time() + 3600);
       setcookie('password', $_COOKIE['password'], time() + 3600);
   } 
}
if (in_array($page, $pages) === false){

      if (isset($_SESSION['username']) === false){

              header( 'Location: login.php' );
              die();

      }

}


?>

That is all the code that inviolves sessions, there are other pages, but these are the main pages that first detect the session.

0

There seems to be a lot of duplication in these include files, such as session_start(). I'd have a look at cleaning them up first.

0

@LastMitch Yes, the issue was solved.

Edited by Djmann1013

4

@Djmann1013

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$_SESSION['inactive'] = $_SESSION['inactive'] + 20;
}

Did you get a chance read this carefully on the pink box:

http://php.net/manual/en/function.ob-start.php

I post it here:

Some web servers (e.g. Apache) change the working directory of a script when calling the callback function. You can change it back by e.g. chdir(dirname($_SERVER['SCRIPT_FILENAME'])) in the callback function.

and also like what diafol said clean up a bit on the duplicate.

1

Thanks guys. I am actually revamping my site because of this outdated code, dulplicates of code blocks, and other major problems. Thanks for helping me.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.