I'm developing a php application and i have a problem retaining session values. I have two files, one is a sidebar (sidebar.php) and a home page (home.php). I have included the sidebar on the home page.
There are login controls on the sidebar and i can successfully login. I know it has successfully logged in because it shows me a message Welcome 'username'. But when i go to the home page, the welcome 'username' part is not shown as the session values are destroyed. instead the login form is shown. Why is that?
This is the home page (sidebar.php)
<?php require_once('connections.php'); ?>
<?php
// if the login button is clicked
if (isset($_POST['btnLogin']))
{
$myusername=$_POST['textusername'];
$mypassword=$_POST['textpassword'];
$result=mysql_query("SELECT * FROM users_table WHERE username='$myusername' and password='$mypassword'");
$count=mysql_num_rows($result);
if($count>=1)
{
$_SESSION['username'] = $row["username"] ;
$_SESSION['userid']= $row["ID"];
}
else
{
//Any code here
}
}
?>
<div class="col-md-12 right-aside">
<?php
if (isset($_SESSION['userid']))
{
echo Welcome : " . $_SESSION['username'];
echo " <a href='logout.php'> | Logout</a>";
}
else //if session is not set
{
echo 'Some html for login form';
}
?>
</div>
The following is the home page (home.php)
<?php include("head.php"); ?>
<body>
<div class="container container-body">
<div class="row">
<div class="col-md-9 main-content">
<div class="row">
<p>Some Text Here</p>
</div><!-- /.row -->
</div><!-- /.main-content -->
<div class="col-md-3">
<div class="row">
<?php include 'sidebar.php';?>
</div>
</div>
Are you starting a session in home.php?
You must call session_start() at the first line of every php script in which you want to access session variables.
Try adding this in top of home.
<?php
session_start();
//Then do your work
Then even if session_start is called again in head.php or sidebar.php , it will be ignored, as the session was already started.
Related
I have a multipage and work on mobile, I use PHP session to keep to consistence, I added a logout button on top and session should be cleared and reload the login page. Below is the content of page, login page is redirected after clicking the logout button but session id seem doesn't be cleared. I have already load the logout with data-ajax=false
HTML
<body class="ui-mobile-viewport ui-overlay-a">
<section id="home" data-role="page">
<header data-role="header">
<h1>Summary</h1>
</header>
<article data-role="content" class="ui-content" role="main">
<button href="#signin_section">Sign-in</button><br>
</article> <!-- article content -->
</section> <!-- section home -->
<section id="signin_section" data-role="page">
<header data-role="header">
<h1>Summary</h1>
Logout
</header>
<article data-role="content" class="ui-content" role="main">
<div id="signin">
<form action="checklogin.php" name="form" id="form" method="post">
... (content omitted) ...
</form>
</div>
</article>
</section>
</body>
PHP script of Logout
<?php
session_start();
unset($_SESSION['login']);
session_destroy();
header("Location: http://jetsodev.aimedia.hk/admincheck");
?>
PHP script of Login
<?php
session_start();
if (isset($_SESSION['login'])) {
....
}
?>
You should use session_unset rather than session_destroy, since the latter “does not unset any of the global variables associated with the session, or unset the session cookie.”
I have a website project where the right hand side of each page is being called from the includes folder that contains an input field and a button. Once the user clicks on the button a php script is run and depending on the result from the script the user is redirected to a thankyou-success.php or a thankyou-failure.php file. These files are located in the root folder. I would like to prevent the user from directly typing the url to these paths and seeing the success or failure message directly. How can the user be prevented from such direct access?
At the moment I am redirecting to the files as follows:
//if found this email in our database
if($count==1)
{
header('Location: thankyou-success.php');
}
else
{
//echo "Cannot send Confirmation link to your e-mail address";
header('Location: thankyou-failure.php');
}
The two php files being called are exactly the same except for the text message displayed. I have removed the <head> tag to keep things simple and clear. The content of the file is as follows:
<body>
<!-- header start here -->
<?php include("includes/header.php") ?>
<!-- header end here -->
<!-- page title start here -->
<section id="pagetitle-container">
<div class="row">
<div class="twelve columns">
<div id="pagetitle-border">
<div id="breadcrumb">
<ul>
<i class="fa fa-caret-right"></i>
<li>Home</li>
</ul>
</div>
<p> <br></p>
<div class="twelve columns">
<p>Unable to send the activation email to the email address provided. Please confirm and try again.</p>
</div>
</div>
</div>
</section>
<!-- page title end here -->
<!-- content section start here -->
<section id="content-wrapper">
<div class="row">
</div>
</div>
</section>
<!-- content section end here -->
<footer>
<?php include("includes/footer.php") ?>
</footer>
<script>$('#noscript').remove();</script>
<!-- pageloader part 2 start -->
<!-- pageloader part 2 ends -->
</body>
</html>
You can move these files outside your web root, and include from the php script that runs on button click.
Your docroot is defined in your web server configuration. Assuming your docroot is /var/www/website/public, you need to move the files that you do not want direct access to somewhere outside this folder like: /var/www/website/files/. Then, from your main script you need to include these files rather than redirecting the user:
main.php:
if ($success) {
include(dirname(__FILE__) . '/../files/thankyou-success.php';
} else {
include(dirname(__FILE__) . '/../files/thankyou-failure.php';
}
One way is to use $_SESSION. On submit of your form, you can do:
$_SESSION['result'] = TRUE;
And in thankyou-success.php, you can do:
if ($_SESSION['result']) {
echo "Success";
unset($_SESSION['result']);
}
else {
echo "How did you get here?";
}
I need some links (related to user account) to appear on the index page for the user who logged in. i have a session variable'email'.
i did this but it didn't work.
<div id="left">
left div content
</div>
<div id=-"right">
<?php
if(isset($_SESSION['email']))
{
?>
//show user some links to his account.
<?php
}
else
{
?>
//show login and register forms
<?php
}
?>
</div>
<?php
session_start(); // add this line
if(isset($_SESSION['email']))
{
?>
Link to php manual.
your first statement within the
<?php
session_start();
//followed by rest of the code.
?>
should be
session_start();
Then the further code.
<?php
session_start();
if(isset($_SESSION['login']))
{
include_once('includes/header.php'); ?>
<!DOCTYPE html>
<html>
<body>
<div id="mainframe">
<img src="img/header.png">
<div id="menu">
<?php include_once('includes/navbar.php'); ?>
</div>
<div id="content">
<h3>Shopping Cart</h3>
</div>
</div>
<?php include_once('includes/footer.php'); ?>
</body>
</html>
<?php }
else
{
header('location: login.php');
}
?>
Here is my small PhP code I've got at the moment, my login session is $_SESSION['login'].
And I'd like to display : Logged in As on my page when they are logged in, I've tried several things but it didn't work out.
Does anyone know a simple method / solution for this?
Put this somewhere in your if statement.
It will show Logged in as User at right top corner of page
<div style="position:absolute; right:0px; top:0px;">
<?php echo "Logged In as". $_SESSION['login']; ?>
</div>
U need to pass username using SESSION variable for the same
write a simple sql query to get the username from any variable you are taking from user to make sure that the particular user is the correct user.i am taking password.
$query = "SELECT name FROM users WHERE password='$password'";
$username = mysql_result(mysql_query($query),0);
$_SESSION['username'] = $username;
than proceed as you are doing
<?php
session_start();
if(isset($_SESSION['login']) && isset($_SESSION['username']))
{
echo "logged in as".$_SESSION['username'];
}
I am not an expert in PHP, and all that I know comes from tuts. I try anyway to do the best I can by myself, but now I have a problem and cannot find what is causing the issue.
I made a bolg using this tutorial. The tutorial is great, easy to understand and everything, the only BUT is that they don't explain how to make a control panel/admin system. So, I made one by myself! I created a simple php/html5 file with icones for the functionalities that exist in the blog: "Add a new blog entry", "Edit an existing blog entry", "Add/manage categories" and "Log out". For the log in mechanism I used this other tutorial. Everything is working fine except for one thing:
After one has logged in the control panel and presses in one of the functions (let's say "Add a new blog entry") and then presses on the button "Back to the control panel", the system automatically logs out and forces you to log in again.
Anybody can explain me why? Bellow is the code of my control panel and the check.php which is included on the control panel (I cut off unnecessary code for other functions like slide shows, css sheets and others):
Control Panel:
<?php require('autent/check.php'); ?>
<p style="background:#48c248; line-height:30px; vertical-align:middle; color:#fff; font-weight:bold;">If you can see this, you're logged in</p>
<!DOCTYPE html>
<head>
<meta charset="utf-8" />
<title></title>
<!-- Rich text editor -->
<script src="ckeditor/ckeditor.js"></script>
</head>
<body>
<div class="row">
<div class="twelve columns">
<h4>Useful links</h4>
<h5>Archive</h5>
<p>
<?php
mysql_connect ('localhost', 'dbuser', 'dbpass') ;
mysql_select_db ('tablename');
$result = mysql_query("SELECT FROM_UNIXTIME(timestamp, '%Y') AS get_year, COUNT(*) AS entries FROM php_blog GROUP BY get_year");
while ($row = mysql_fetch_array($result)) {
$get_year = $row['get_year'];
$entries = $row['entries'];
echo "Entries from " . $get_year . " (" . $entries . ")<br />";
}
?>
</p>
<h5>Category Archive</h5>
<p>
<?php
mysql_connect ('localhost', 'dbuser', 'dbpass') ;
mysql_select_db ('tablename');
$result1 = mysql_query("SELECT * FROM php_blog_categories ORDER BY category_name ASC");
while($row = mysql_fetch_array($result1)) {
$result2 = mysql_query("SELECT COUNT(`id`) AS entries FROM php_blog WHERE category = $row[category_id]");
$num_entries = mysql_fetch_array($result2);
echo '' . $row['category_name'] . ' (' . $num_entries['entries'] . ')<br />';
}
?>
</p>
</div>
<h4>Control panel - Manage your blog</h4>
<img src="../images/new_blog.png" title="Add a new blog entry" alt="Add a new blog entry"/><br>
<p>Add a new blog entry</p>
</div>
<div class="four columns">
<img src="../images/edit_blog.png" title="Edit a blog entry" alt="Edit a blog entry"/><br>
<p>Edit an existing blog entry</p>
</div>
<div class="four columns">
<img src="../images/cat_blog.png" title="Add/manage categories" alt="Add/manage categories"/><br>
<p>Add/manage categories</p>
</div>
<div class="four columns">
<p> </p>
</div>
</div>
<div class="four columns">
<img src="../images/logout.png" title="End your session" alt="End your session"/><br>
<p>End your session</p>
</div>
<!-- other html and footer follows -->
</body>
</html>
check.php
<?php
session_start();
if (!isset($_SESSION['loggedin'])) {
header("Location: login.php");
exit;
} else {
// the session variable exists, let's check it's valid:
require('autent/config.php');
$userexists = false;
foreach($users as $username => $password) {
if (md5($username.$password.$salt) == $_SESSION['loggedin'])
$userexists = true;
}
if ($userexists !== true) {
exit('<p style="background:#fd0000; line-height:30px; vertical-align:middle; color:#fff; font-weight:bold;">Invalid session: please login.</p>');
}
}
?>
It may because of session timeout problem.try to increase the session time by referring the following url.
How do I expire a PHP session after 30 minutes?
Session variables are stored on your server, not on the users computer like a cookie. So the user can't ever modify $_SESSION variables. It is helpful to create a boolean variable in your session that can be used as a quick flag to tell you if the user is still signed in.
When you create the session for the user, you could create a session variable like this:
$_SESSION['valid'] = TRUE;
From here on out, all you have to do is check if the session is still set to true:
session_start();
if (!$_SESSION['valid']) {
header("Location: login.php");
exit;
}
That code checks if the session is not true and if it is not, send them to login.php
When you sign them out, you can unset the session variable or just set it to false.