Reputation: 759
I have to make a simple site which you can log in and out of, and if the user is logged in they see some features which they otherwise would not. I'm not very good with web development however I have managed to get something together which seems to have worked. I've decided I don't want to redirect the user to another page when logging in and logging out so this has made it a bit harder for me to understand.
I just wondered if I'm going about the session starts and destroy in the right way and if anyone could give me any pointers as to making it better if that's even possible.
<?php
if(isset($_POST['logout'])) {
session_destroy();
}
}
session_start();
if(!isset($_SESSION['username'])) {
if (!empty($_POST['username']) && !empty($_POST['password'])) {
$result = mysql_query("SELECT * FROM users WHERE username ='$_POST['username']' AND password = '$_POST['password']'");
if(mysql_num_rows($result))
$_SESSION['username'] = $_POST['username'];
}
else {
echo "";
}
}
}
?>
<?php if(!isset($_SESSION['username'])) {
echo '<div id = "account">
<form name="input" action="index.php" method="post">
Username:<input type="text" name="username" /> Password:<input type="password" name="password" />
<input type="submit" value="GO!" />
</form>
}
else {
echo "Signed in"
<form name='logout' action='index.php' method='post'>
<input type='submit'value='Reset' name='logout'/>
";
} ?>
<?php
$test = mysql_query("SELECT * FROM posts ORDER BY post_id DESC");
if($test) {
while($row = mysql_fetch_array($test)) {
echo '<div class="posts">';
echo "$row[post]";
echo '</div>';
}
}
Upvotes: 0
Views: 7522
Reputation: 619
You can try method in calling session
. Just like mine
Here it will check if you are connected to your database I name it connect.inc.php
<?php
if(!mysql_connect('localhost', 'root', '')|| !mysql_select_db('byp_db'))
{
die(mysql_error());
}
?>
Next I created my core.inc.php
where it will check if you are already in session
you will use the loggedin()
method in that
<?php
error_reporting(E_ALL ^ E_NOTICE);
ob_start();
session_start();
$current_file = $_SERVER['SCRIPT_NAME'];
$http_referer = $_SERVER['HTTP_REFERER'];
function loggedin() {
if(isset($_SESSION['user_p_info_id'])&&!empty($_SESSION['user_p_info_id'])) {
return true;
}else {
return false;
}
}
function getuserfield($field){
$query = "SELECT `$field` FROM `user_p_info` where `user_p_info_id`='".$_SESSION['user_p_info_id']."'";
if($query_run = mysql_query($query)){
if($query_result = mysql_result($query_run, 0, $field)){
return $query_result;
}
}
}
?>
Next is you will create your log-in form
<?php
require 'connections/connect.inc.php';
require 'connections/core.inc.php';
if(isset($_POST['uname']) && isset($_POST['password'])){
$uname = $_POST['uname'];
$pword = $_POST['password'];
//echo $uname;
//echo $pword;
if(!empty($uname)&&!empty($pword)){
$query_login = "SELECT * FROM user_a_info where username = '$uname' and password = '$pword'";
//echo $query_login;
$query_result = mysql_query($query_login);
$num_rows = mysql_num_rows($query_result);
if($num_rows == 0){
?>
<script type="text/javascript">
alert("Invalid Data !");
</script>
<?php
}else{
//echo "validated";
$user_p_info_id = mysql_result($query_result, 0, 'user_p_info_id');
$_SESSION['user_p_info_id']=$user_p_info_id;
header('Location: index.php');
}
}
}
?>
<form action="login.php" method="POST">
<p> USERNAME : <input type="text" name="uname" /> </p>
<p> PASSWORD : <input type="password" name="password" /> </p>
<p> <input type="submit" value="LOGIN" /> </p>
</form>
And then your log-out function will look like this
<?php
require 'core.inc.php';
session_destroy();
header('Location: ../index.php');
?>
Just take note that if you want to check whether you are in session
or not just put this condition
<?php
require 'connections/connect.inc.php';
require 'connections/core.inc.php';
if(loggedin()) {
// Do something
}
?>
Hope this helps
Upvotes: 0
Reputation: 1765
May be instead of checking for $_POST['logout'] everytime the page loads, you can redirect the user to a different logout specific page.
Upvotes: 0
Reputation: 8763
I worked on your code and made many changes. I tried to add lots of comments to make it more easy to understand. Hopefully there are no syntax errors, but I couldn't actually test is since I don't have the MySQL databases and such.
Here is your main code:
<?php
//When you are developing and testing, set the error level as high as possible.
//This will help you find problems early. A well written program will have no errors and warnings, ever.
error_reporting(E_ALL | E_STRICT);
//Starting the session should be one of the first things your code does, and should only be done once.
session_start();
require 'config.php';
if(isset($_POST['logout']))
{
//I don't think there is any reason to check if username is set. If you are logging out, just destroy.
session_destroy();
//Also unset the session username since session_destroy() does not affect existing globals.
unset($_SESSION['username']);
}
//I changed this to elseif, because there should not be a condition where you are logging out and checking for a login.
elseif(!isset($_SESSION['username']))
{
//You should not assume that variables are set, because accessing them if they are not set
//will cause a warning. I've added isset().
if(isset($_POST['username']) && !empty($_POST['username']) && isset($_POST['password']) && !empty($_POST['password']))
{
//You absolutely MUST escape your strings or you are at risk of SQL injection.
//Use mysql_real_escape_string() for this.
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$result = mysql_query("SELECT * FROM members WHERE username ='$username' AND password = '$password'");
//You should probably check that the value === 1 here.
//I'm assuming it should always be 1 or 0.
if(0 === mysql_num_rows($result))
{
$_SESSION['username'] = $username;
}
else {
echo "Fail :(";
}
}
//If you put an else statement here, you could print an error for if the username was not specified.
}
//You should not have SQL queries in your template, so I moved this here.
//Notice that I'm just setting $posts to the data. It's best to just pass
//the data, and format it in the template.
$result = mysql_query("SELECT * FROM posts ORDER BY post_id DESC");
if($result)
{
$posts = array();
while($row = mysql_fetch_array($result))
{
$posts[] = $row['post'];
}
}
else
{
$posts = false;
}
//Try to separate code logic from templates.
//Your program is small, so it's not that important, but I would do it anyway.
require 'template.php';
?>
Here is your template code, which should go in a new file called template.php:
<div id = "container">
<h1>#HookyGear Bay</h1>
<div id = "login">
<?php if(!isset($_SESSION['username'])) {
echo '<div id = "accountBox">
<form name="input" action="index.php" method="post">
Username:<input type="text" name="username" /> Password:<input type="password" name="password" />
<input type="submit" value="Sign In" />
</form>
</div>';
}
else {
echo "<div id='accountBox'>You Are logged in as ".$_SESSION['username']."
<form name='logout' action='index.php' method='post'>
<input type='submit'value='Reset' name='logout'/>
</div> ";
} ?>
</div>
<div id = "content">
<?php
if(false !== $posts)
{
foreach($posts as $post)
{
echo '<div class="blogPosts">'.$post.'</div>';
}
}
else { ?>
<div class="blogPosts"><?php echo "no blog posts"; ?></div>
<?php
}
?>
<div style="clear:both;"></div>
</div>
</div>
Upvotes: 1