SESSSION still work afterclosing tabs - php

i create php files that check user login in. If the user and password is correct, user can visit the catalog page. However there are some problems with the session. After reopening browser it still display the hidden data. I know the session will be closed when i close the browser but this case seems weird. This is the login form:
<html>
<body>
<?php
$LabelLogin=array("login"=>"login",
"password"=>"password",
);
echo "<h1> Login and Register Page </h1>";
echo "<form action='CheckLoginDetail.php' method=POST>";
foreach($LabelLogin as $keys =>$values)
{
if($keys=='password')
{
echo "$values <input type='password' name='$keys' /><br/>";
}
else
{
echo "$values <input type='text' name='$keys' /><br/>";
}
}
echo "<input type='submit' value='submit' />";
echo "<br/>click <a href='register.php'>here<a/> to register if you don't have an accout <br/>";
echo "</form>";
?>
</body>
2nd CheckLoginDetail.php
<?php
session_start();
include("connect.inc");
$connect=mysqli_connect($host,$username,$password,$dbname) or die ("can't connect to server");
$labels=array("login"=>"login",
"password"=>"password");
foreach($_POST as $keys =>$values)
{
if(empty($values))
{
$empty_values[]=$keys;
}
elseif(!preg_match("/^[A-Za-z0-9_]+$/",$values))
{
$invalid_values[]=$keys;
}
else
{
$data[$keys]=$values;
}
}
if(#sizeof($empty_values)>0 or #sizeof($invalid_values)>0)
{
if(#sizeof($empty_values)>0)
{
echo "login name or password or both can not be empty !";
}
if(#sizeof($invalid_values)>0)
{
echo "values contain invalid characters";
}
include("FrontPage.php");
exit();
}
else
{
foreach($data as $keys =>$values)
{
$clean_data[$keys]=mysqli_real_escape_string($connect,strip_tags(trim($values)));
}
$query="SELECT LoginName and Password FROM yugimemberinfo WHERE LoginName='";
foreach($clean_data as $keys =>$values)
{
if($keys=="login")
{
$query.="$values'";
}
if($keys=="password")
{
$values=md5($values);
$query.=" AND Password='$values'";
}
}
$result=mysqli_query($connect,$query) or die("can't execute query ".mysqli_error($connect));
if(mysqli_num_rows($result)==0)
{
echo "login fail";
include("FrontPage.php");
exit();
}
else
{
$_SESSION['access']="yes";
echo "login succesfully !<br/>";
echo "Here are two options for you :<br/>";
echo "<ul>
<li><a href='ShowCatalog.php'>Go to Card Catalog</a></li>
<li><a href='search_form.php'>Searching for your cards</a></li>
</ul>";
$query_insert="INSERT INTO yugimember (LoginName,LoginTime) VALUES(";
foreach($clean_data as $keys =>$values)
{
//echo "$keys =>$values<br/>";
if($keys=="login")
{
$query_insert.="'$values',";
}
}
//insert login name and time to yugimember
$query_insert.="'".date("Y-m-d H:i:s")."')";
$result=mysqli_query($connect,$query_insert) or die ("can't execute query line 62");
}
}
?>
if users login successfully, they can lick to the link that take them to another site called "ShowCatalog.php"
<?php
session_start();
include("connect.inc");
$connect=mysqli_connect($host,$username,$password,$dbname) or die ("can't connect to server");
if(#$_SESSION['access'] != 'yes')
{
include("FrontPage.php");
exit();
}
$query="SELECT * FROM dragon ";
$result=mysqli_query($connect,$query) or die("can't execute query");
echo "<hr/>";
while($row=mysqli_fetch_assoc($result))
{
extract($row);
echo $type."<br/>";
echo $CardName."<br/>";
echo $atk." \ ".$def."<br/>";
echo $Description;
echo "<br/>".$picture."<br/>";
echo "<br/>";
echo "<a href='../dragon/{$picture}'><img src='../dragon/{$picture}' height='300' width='300'></a>";
echo "<hr/>";
}
?>
I make the ShowCatalog.php only display data for user logining in. However when i login in and close the browser then reopen it the ShowCatalog.php the data is stilled appear.

Not sure but when you do this :
if(#$_SESSION['access'] != 'yes')
If the session does not exist (because you closed your browser), maybe it will bypass this condition.
Try :
if (!isset($_SESSION['access']) | $_SESSION['access'] != 'yes')

Related

User register/login?

Im new to PHP, login.php make you use your username instead of your email. How do you make it where I can have user's login just via email, an password instead of them using there username an password.
Login.php
<?php
session_start();
// Header file
require_once "views/template/header.php";
if ($_GET["op"] == "login")
{
if (!$_POST["username"] || !$_POST["password"])
{
die("You need to provide your e-mail and password.");
}
// Create query
$q = "SELECT * FROM `users` "
."WHERE `username`='".$_POST["username"]."' "
."AND `password`=PASSWORD('".$_POST["password"]."') "
."LIMIT 1";
// Run query
$r = mysql_query($q);
if ( $obj = #mysql_fetch_object($r) )
{
// Login good, create session variables
$_SESSION["valid_id"] = $obj->id;
$_SESSION["valid_user"] = $_POST["username"];
$_SESSION["valid_time"] = time();
// Redirect to member page
Header("Location: members.php");
}
else
{
// Login not successful
die("Sorry, could not log you in. Wrong login information.");
}
}
else
{
//If all went right the Web form appears and users can log in
echo "<form action=\"?op=login\" method=\"POST\">";
echo "Username: <input name=\"username\" size=\"15\"><br />";
echo "Password: <input type=\"password\" name=\"password\" size=\"8\"><br />";
echo "<input type=\"submit\" value=\"Login\">";
echo "</form>";
echo "Don't have account <a href='register.php'>create account now!</a>";
}
require_once "views/template/footer.php";
?>
Register.php
<?php
// dbConfig.php is a file that contains your
// database connection information. This
// tutorial assumes a connection is made from
// this existing file.
require_once "views/template/header.php";
//Input vaildation and the dbase code
if ( $_GET["op"] == "reg" )
{
$bInputFlag = false;
foreach ( $_POST as $field )
{
if ($field == "")
{
$bInputFlag = false;
}
else
{
$bInputFlag = true;
}
}
// If we had problems with the input, exit with error
if ($bInputFlag == false)
{
die( "Problem with your registration info. "
."Please go back and try again.");
}
$profile=$_POST['profilename'];
$password=$_POST['password'];
$email=$_POST['email'];
$fname=$_POST['firstname'];
$lname=$_POST['lastname'];
// Fields are clear, add user to database
// Setup query
$q = "INSERT INTO users (`profilename`,`password`,`email`,`firstname`,`lastname`)
VALUES ('$profile','$password','$email','$fname','$lname')";
// Run query
$r = mysql_query($q);
// Make sure query inserted user successfully
if ( !mysql_insert_id() )
{
die("Error: User not added to database.");
}
else
{
// Redirect to thank you page.
Header("Location: register.php?op=thanks");
}
} // end if
//The thank you page
elseif ( $_GET["op"] == "thanks" )
{
echo "<h2>Thanks for registering!</h2>";
}
//The web form for input ability
else
{
echo "<form action=\"?op=reg\" method=\"POST\">\n";
echo "Profile Name: <input name=\"profilename\" MAXLENGTH=\"16\"><br />\n";
echo "Password: <input type=\"password\" name=\"password\" MAXLENGTH=\"16\"><br />\n";
echo "Email Address: <input name=\"email\" MAXLENGTH=\"25\"><br />\n";
echo "First Name: <input name=\"firstname\" MAXLENGTH=\"25\"><br />\n";
echo "Last Name: <input name=\"lastname\" MAXLENGTH=\"25\"><br />\n";
echo "<input value='Submit' type=\"submit\">\n";
echo "</form>\n";
}
// EOF
require_once "views/template/footer.php";
?>
Just look for the email instead of the username:
// Create query
$q = "SELECT * FROM `users` "
."WHERE `email`='".$_POST["username"]."' "
."AND `password`=PASSWORD('".$_POST["password"]."') "
."LIMIT 1";
And change your form label:
echo "Email: <input name=\"username\" size=\"15\"><br />";
That's the quickest fix. Obviously to be more thorough you'll want to replace all instances of "Username" or $_POST['username'] in your login script with email, and you should stop using the mysql_* library since it's deprecated and soon to be removed.

User information does not get sent to database

I am new at designing websites and I recently wanted to add login/registration forms to my website I have a database and have coded all of the forms but when I attempt to register I am unable to because my information is not added to the database. I have been working on this for a while any advice on how to better my forms and registration system would be more than helpful. Thanks in advance!
Here are my forms:
Registration:
<?php
session_start();
include "dbConfig.php";
if (isset($_GET["op"]) == "login") {
if (!$_POST["username"] || !$_POST["password"]) {
die("You need to provide a username and password.");
}
// Create query
$q = "SELECT * FROM `gd_database` "
."WHERE `username`='".$_POST["username"]."' "
."AND `password`=PASSWORD('".$_POST["password"]."') "
."LIMIT 1";
// Run query
$r = mysql_query($q);
if ( $obj = #mysql_fetch_object($r) ) {
// Login good, create session variables
$_SESSION["valid_id"] = $obj->id;
$_SESSION["valid_user"] = $_POST["username"];
$_SESSION["valid_time"] = time();
// Redirect to member page
Header("Location: members.php");
} else {
// Login not successful
die("Sorry, could not log you in. Wrong login information.");
}
} else {
echo "<form action=\"?op=login\" method=\"POST\">";
echo "Username: <input name=\"username\" size=\"15\">";
echo "Password: <input type=\"password\" name=\"password\" size=\"8\">";
echo "<input type=\"submit\" value=\"Login\">";
echo "</form>";
}
?>
Login:
<?php
session_start();
include "dbConfig.php";
if (isset($_GET["op"]) == "login") {
if (!$_POST["username"] || !$_POST["password"]) {
die("You need to provide a username and password.");
}
// Create query
$q = "SELECT * FROM `gd_database` "
."WHERE `username`='".$_POST["username"]."' "
."AND `password`=PASSWORD('".$_POST["password"]."') "
."LIMIT 1";
// Run query
$r = mysql_query($q);
if ( $obj = #mysql_fetch_object($r) ) {
// Login good, create session variables
$_SESSION["valid_id"] = $obj->id;
$_SESSION["valid_user"] = $_POST["username"];
$_SESSION["valid_time"] = time();
// Redirect to member page
Header("Location: members.php");
} else {
// Login not successful
die("Sorry, could not log you in. Wrong login information.");
}
}
else
{
echo "<form action=\"?op=login\" method=\"POST\">";
echo "Username: <input name=\"username\" size=\"15\">";
echo "Password: <input type=\"password\" name=\"password\" size=\"8\">";
echo "<input type=\"submit\" value=\"Login\">";
echo "</form>";
}
?>
Your login and registration scripts are the same code and they assume that you already have an account are trying to verify the credentials. You'll need to insert the data from the form into the database with an INSERT statement before anything else. Right now, you're just checking for accounts in an empty table.
Look up some tutorials for registering users. Tutsplus is nice.
here is a code for registration
register.php
<?php
include ("dbConfig.php");
if ( $_GET["op"] == "reg" )
{
$bInputFlag = false;
foreach ( $_POST as $field )
{
if ($field == "")
{
$bInputFlag = false;
}
else
{
$bInputFlag = true;
}
}
if ($bInputFlag == false)
{
die( "Problem with your registration info. "
."Please go back and try again.");
}
$q = "INSERT INTO `dbUsers` (`username`,`password`,`email`) "
."VALUES ('".$_POST["username"]."', "
."PASSWORD('".$_POST["password"]."'), "
."'".$_POST["email"]."')";
$r = mysql_query($q);
if ( !mysql_insert_id() )
{
die("Error: User not added to database.");
}
else
{
Header("Location: register.php?op=thanks");
}
}
elseif ( $_GET["op"] == "thanks" )
{
echo "<h2>Thankyou for registering!</h2>";
}
else
{
echo "<form action=\"?op=reg\" method=\"POST\">\n";
echo "Username: <input name=\"username\" MAXLENGTH=\"16\"><br />\n";
echo "Password: <input type=\"password\" name=\"password\" MAXLENGTH=\"16
\">\n";
echo "Email Address: <input name=\"email\" MAXLENGTH=\"25\"><br />\n";
echo "<input type=\"submit\">\n";
echo "</form>\n";
}
?>
inorder to add data into your database you need to use a query INSERT.hope this code would help you in solving your problem.

login script not working

I am trying to check the login, then trying to echo basic user info. Thanks in advance for everyones help. Any suggestions on why I'm unable to echo row data based on a specific logged in user?
<?php
<?php
session_start();
// dBase file
include "config.php";
ini_set('display_errors', 1);
if (isset($_GET["op"] ) && $_GET["op"] == "login")
{
if (!$_GET["username"] || !$_GET["password"])
{
die("You need to provide a username and password.");
}
// Create query
$q = "SELECT * FROM `users` "
."WHERE `username`='".$_GET["username"]."' "
."AND `password`=PASSWORD('".$_GET["password"]."') "
."LIMIT 1";
// Run query
$r = mysql_query($q);
$row = mysql_assoc_array($r);
$count = mysql_num_rows($r);
if ($obj = mysql_fetch_object($r) && $count == 1)
{
// Login good, create session variables
$_SESSION["id"] = $row['id'] = $obj->id;
$_SESSION["user"] = $row['username'] = $obj->username;
$_SESSION["time"] = time();
// Redirect to member page
Header("Location: welcome.php");
}
else
{
// Login not successful
die("Sorry, could not log you in. Wrong login information.");
header("Location: login2.php");
}
}
{
//If all went right the Web form appears and users can log in
echo "<form action=\"?op=login\" method=\"GET\">";
echo "Username: <input name=\"username\" name=\"username\" size=\"32\"><br />";
echo "Password: <input type=\"password\" name=\"password\" size=\"32\"><br />";
echo "<input type=\"submit\" value=\"Login\">";
echo "</form>";
}
?>
You're using mysql_fetch_object so you need to do:
$_SESSION["user"] = $obj->username;
Rather than:
$_SESSION["user"] = $row['username'];

primary key increase not orderly

i have a list of card names and a php file inserting card. When i inserted one card and deleted it in the database then inserted again. The primary key increase after the card delete. For example:
Card number 1
Card number 2
Card number 3 --> if i delete this value and inserte again the primary key is 4 not 3 how to fix that problem ?
Here is my code
<?php
// this file show card name and picture
include("connect.inc");
$connect=mysqli_connect($host,$username,$password,$dbname) or die ("can't connect to server");
$query="SELECT * FROM dragon ";
$result=mysqli_query($connect,$query) or die("can't execute query");
echo $_SESSION['count'];
echo "<hr/>";
while($row=mysqli_fetch_assoc($result))
{
extract($row);
echo $type."<br/>";
echo $CardName."/";
echo $Description;
echo "<br/>";
echo "<a href='../dragon/{$picture}' border='0'> <img src='../dragon/{$picture}' border='0' width='300' height='300'/></a>";
echo "<hr/>";
}
?>
this file shows the insert form
<?php
$labels=array("type"=>"type",
"CardName"=>"Card Name",
"Description"=>"Description",
"atk"=>"Attack",
"def"=>"Defend",
"picture"=>"picture");
echo "<form action='InsertCard.php' method='POST'>";
echo "<h2>Insert new card </h2>";
foreach($labels as $keys =>$values)
{
echo "$values <input type='text' name='$keys'/><br/>";
}
echo "<input type='submit' value='insert new cards'/>";
echo "<input type='submit' name='return' value='return'/>";
echo "</form>";
?>
this file handle the inserted file
<?php
$labels=array("type"=>"type",
"CardName"=>"Card Name",
"Description"=>"Description",
"atk"=>"Attack",
"def"=>"Defend",
"picture"=>"picture");
if(#isset($_POST['return']))
{
header("Location:ShowCatalog.php");
}
include("connect.inc");
$connect=mysqli_connect($host,$username,$password,$dbname) or die("can't connect to server");
foreach($_POST as $keys =>$values)
{
if(empty($values))
{
if($keys=='type' or $keys=='CardName' or $keys=='Description' or $keys=='picture')
{
$empty_values[]=$keys;
}
}
else
{
if($keys=='type')
{
if(!preg_match("/^[A-Za-z -]{4,15}$/",$values))
{
$invalid_data[]=$keys;
}
}
elseif($keys=='CardName')
{
if(!preg_match("/^[A-Za-z -]{4,30}$/",$values))
{
$invalid_data[]=$keys;
}
}
elseif($keys=='Description')
{
if(!preg_match("/^[A-Za-z., -]{4,255}$/",$values))
{
$invalid_data[]=$keys;
}
}
elseif($keys=="atk" or $keys=="def")
{
if(!preg_match("/^[0-9]{3,5}$/",$values))
{
$invalid_data[]=$keys;
}
}
elseif($keys=='picture')
{
if(!preg_match("/^[A-Za-z -]{4,30}(.jpg)$/",$values))
{
$invalid_data[]=$keys;
}
}
/*else
{
$clean_data[$keys]=trim(strip_tags($values));
}*/
}
}
if(#sizeof($empty_values)>0 or #sizeof($invalid_data)>0)
{
if(#sizeof($empty_values)>0)
{
$join=join(", ",$empty_values);
$msg="You forgot to input: $join<br/>";
echo $msg;
}
if(#sizeof($invalid_data)>0)
{
$join=join(", ",$invalid_data);
$msg="Invalid data: $join";
echo $msg;
}
echo "<form action='$_SERVER[PHP_SELF]' method='POST'>";
echo "<h2>Insert new card </h2>";
foreach($labels as $keys =>$values)
{
echo "$values <input type='text' name='$keys'/><br/>";
}
echo "<input type='submit' value='insert new cards'/>";
echo "<input type='submit' name='return' value='return'/>";
echo "</form>";
exit();
}
foreach($_POST as $keys =>$values)
{
$queried_data[$keys]=mysqli_real_escape_string($connect,trim(strip_tags($values)));
}
$check_existence="SELECT CardName FROM dragon WHERE CardName=";
foreach($queried_data as $keys =>$values)
{
if($keys=="CardName")
{
$check_existence.="'".$values."'";
}
}
$checking_result=mysqli_query($connect,$check_existence)or die("can't execute query ".mysqli_error($connect));
if(mysqli_affected_rows($connect)>0)
{
echo "card is already existed !";
include("ShowForm.php");
exit();
}
else
{
$query="INSERT INTO dragon(";
foreach($queried_data as $keys =>$values)
{
$query.=$keys.",";
}
$query.=")";
$query=preg_replace("/\,\)/",")",$query);
$query.="VALUES(";
foreach($queried_data as $keys =>$values)
{
if($keys=="type" or $keys=="CardName" or $keys=="Description")
{
$values=ucfirst($values);
}
if($keys=="atk" or $keys=="def")
{
if(empty($values))
{
$values='n/a';
}
}
$query.="'".$values."',";
}
$query.=")";
$query=preg_replace("/\,\)/",")",$query);
$result=mysqli_query($connect,$query);
echo "card is inserted !";
}
?>
That is expected behaviour, in other words, that's now AI works. Instead of counting on the ID's being sequential, you should keep track of this by yourself in case you need it. When you have done an insert with mysqli, you can fetch the "insert id" after the query has been done, if you need it for reference later.
For more information on getting insert id see:
http://www.php.net/manual/en/mysqli.insert-id.php
This is not a problem. When using autoincrement primary keys, the key assigned to your input is the lowest positive value that has not been assigned yet. This is useful in many ways. For example, you have another table with a foreign key. If your design is bad, you may delete a row from this table and remain with an orphan foreign key. This is a easy detectable error, but if when you insert another row, it gets the key of the deleted row, then yor foreign key will point to other data. This error is very hard to detect. So, the problem is not how keys are assigned, but your expectations. You might consider asking what are you trying to achieve, in order to get an useful answer for your work.
I see you didn't post any code relating to the delete query, so if you are using a delete in sql manually use the following code.
ALTER TABLE dragon AUTO_INCREMENT = 1
this will reset auto incrementing, and sql will insert the next highest integer.
see https://stackoverflow.com/a/8923132/2401804

session variable values are not being passed between pages

i am a little new to php and although i have managed to pass values of session variables before this piece of code is leaving me puzzled
<form action="team_reg2.php" method="post" name="form1" class="cent" id="form1">
<p><strong>Team Registration</strong></p>
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("databolism",$con);
$result=mysql_query("select * from events where id=$_POST[event]",$con);
$row=mysql_fetch_assoc($result);
$num=$row['max_team'];
$_SESSION['max_team']=$num;
$_SESSION['event_id']=$_POST['event'];
for($i=1;$i<=$num;$i++)
{
print "<p><span id=\"sprytextfield$i\"\n>";
print "<label>member$i";
print "<input type=\"text\" name=\"mem$i\" id=\"mem$i\" />\n";
print "</label>\n";
print "<span class=\"textfieldInvalidFormatMsg\">Please enter only id</span></span></p>\n";
}
?>
now this will pass via post to team_reg2.php
<?php
$con=mysql_connect("localhost","root","");
if(!$con)
die("could not connect to db");
$db=mysql_select_db("databolism",$con);
$num=6;
$event=14;
$result=mysql_query("select * from events where id=$event",$con) or die(mysql_error());
$row=mysql_fetch_assoc($result);
$query='fantasia1_'.$row['name'];
$query2="select max(t_id) from $query";
$que=mysql_query($query2,$con);
$result=mysql_fetch_array($que) or die(mysql_error());
$chk3=$result['max(t_id)'];
if($chk3==NULL)
{
for($i=1;$i<=$num;$i++)
{
$name='mem'.$i;
if($_POST["$name"]!="")
{
$query2="insert into $query values(1,'$_POST[$name]')";
$que=mysql_query($query2,$con);
}
}
echo " please note your team id is 1 <br>";
echo " your team members are : <br>";
for($i=1;$i<=$num;$i++)
{
$name='mem'.$i;
echo "$_POST[$name]<br>";
}
}
else
{
$str="select * from $query where (";
for($i=1;$i<=$num;$i++)
{
$name='mem'.$i;
$text="p_id='$_POST[$name]'";
if($i==1)
$str=$str.$text;
else
$str=$str.' or '.$text;
}
$str=$str.')';
$query2=$str;
echo "$str<br>";
// echo "$query2</br>";
$que=mysql_query($query2,$con) or die(mysql_error());
$num=mysql_num_rows($que);
if($num!=0)
{
while($result=mysql_fetch_array($que))
{
echo "$result[p_id] is already registered in team $result[t_id]<br>";
}
//include("reg_team.html");
}
else if($num==0)
{
//echo $query;
$query2="select max(t_id) from $query";
$que=mysql_query($query2,$con) or die(mysql_error());
//echo "$que<br>";
$result=mysql_fetch_array($que);
$max=$result['max(t_id)'];
$max++;
$num=$_SESSION['max_team'];
for($i=1;$i<=$num;$i++)
{
$name='mem'.$i;
if($_POST[$name]!="")
{
$query2="insert into $query values($max,'$_POST[$name]')";
$que=mysql_query($query2,$con);
}
}
echo " please note your team id is $max <br>";
echo " your team members are : <br>";
for($i=1;$i<=$num;$i++)
{
$name='mem'.$i;
echo "$_POST[$name]<br>";
}
}
}
?>
i have done session_start(); at the beginning of the page itself. The problem is that echoing $_SESSION variables in second file is not printing anything.
someone please explain me whats going on.
thank you
You need session_start() in the second file, too.

Categories