what means these examples about session fixation? - php

the first example
<?php
session_start();
if(!isset($_SESSION['count'])) $_SESSION['count'] = 0;
else ++$_SESSION['count'];
echo $_SESSION['count'] . "<br />";
?>
the second example
<?php
session_start();
if(!isset($_SESSION['initiated']))
{
session_regenerate_id();
$_SESSION['initiated'] = 1;
}
if(!isset($_SESSION['count'])) $_SESSION['count'] = 0;
else ++$_SESSION['count'];
echo $_SESSION['count'] . "<br />";
I can find the only different is if I use two different URLs(eg: http//localhost/test?PHPSESSID=123; http//localhost/test?PHPSESSID=456) the first script will count up again from zero, but the second will continue count
so what do two examples mean? and what does it want to tell me?

Sorry, my first answer was too hasty. Check This out. PHP.net says:
"session_regenerate_id() will replace the current session id with a new one, and keep the current session information."

session_regenerate_id() if it can, will submit a cookie to keep the session details.
Think of it as a extended session for the user. So that if the user closes their browser, the user session can be recalled.

Related

Pagination in PHP during passing a value at the first time when the page loads

This is a simple code which I am using in PHP. But the problem is every time I run the page, it says undefined index page. But after clicking a href link, it works perfectly. Can anyone help me out how to resolve the error?
Actually the $_GET['page'] isn't having a value at the first time when the page loads. But I need this to execute the query to take out data from the database. Here's the code:
<?php
require 'db_connect.php';
$page=$_GET["page"];
if($page=="" || $page=="1") {
$page1=0;
} else {
$page1=($page*5)-5;
}
$sql="SELECT * FROM tbl_product WHERE deletion_status=1 limit $page1,5";
$res=mysqli_query($db_connect,$sql);
while($row=mysqli_fetch_assoc($res)) {
echo $row['product_id']." ".$row['product_name'];
echo "<br>";
}
$sql1="SELECT * FROM tbl_product WHERE deletion_status=1";
$res1=mysqli_query($db_connect,$sql1);
$count=mysqli_num_rows($res1);
echo'<br>';
//echo $count;
$a=$count/5;
echo'<br>';
$a=ceil($a);
for($b=1;$b<=$a;$b++){
?><?php echo " "; echo $b;?><?php
}
?>
Before trying to use the value, check if it exists:
$page = "1";
if (isset($_GET["page"])) {
$page = $_GET["page"];
}
That way it's initialized with a default value, but if a value has been provided it will use that one instead.
Simply check whether $_GET['page'] is set or not, and assign the initial $page value accordingly.
So change $page=$_GET["page"]; to
$page=isset($_GET["page"]) ? $_GET["page"] : "1";

How can I manage the lifetime of my PHP sessions?

I am quite new to PHP, so I'm working on a simple project to practise. However, I can't manage to make the session management work properly.
What I want is that when the browser is closed, the data (the current page the user is at) is saved for an hour. If the user returns within an hour, he should see the same page he left, and if he return after an hour, he should see the first question.
When all questions have been answered, he should see a score-screen, with a "Try Again" button that preferably destroys/kills/deletes the session and starts a new one, directing the user to the first question.
If I leave out line 3-8 my code works as expected, I run throught the questions until I get stuck at the score-screen with a non-working "Try Again" button, I can only go back to the first question by closing and reopening the browser.
With these lines, the page runs through the questions fine but when I restart the browser, it starts at the first question. When I close the browser without doing anything and open the page a second time, I find the page I left at first. I close and open the browser again and I find the correct page again, I do it again and I'm back to question 0. No matter how often I then restart the browser, I stay at question 0.
When I look at the cookies in my browser, I have the same cookie all the time, one that started at 14 december 2015 18:48:45. However, the experation time isn't correct either, as that is 26 november 2061 13:37:29, instead of an hour later. What am I doing wrong?
Here is my code:
<?php
/* Sart (new) session*/
if (isset($_GET['TryAgain'])){
session_start();
$_SESSION = array();
session_destroy();
}
session_set_cookie_params(time()+3600);
session_start();
/*-------------------------------------------------------------------*/
/* IMPORT DATABASE: $qs[i]=question text, $as[i]=array(choices per question),
$as[i][i]=array('t'=>choice text, 'c'=>BOOLEAN) */
require_once('config.php');
$dbh = new PDO("mysql:dbname=$db;host=$host", $user, $password);
$questions = $dbh->prepare('select * from questions');
$questions->execute();
$choices = $dbh->prepare('select * from choices');
$choices->execute();
$qs = array();
$as = array();
foreach($questions as $row) {
$i = $row['q_nr'];
$qs[$i] = $row['q_text'];
}
foreach($choices as $row) {
$qi = $row['q_nr'];
$ci = $row['c_nr'];
$as[$qi][$ci] = array('t'=>$row['c_text'],'c'=>$row['correct']);
}
/*-------------------------------------------------------------------*/
/*INITIALIZE SESSION VARIABLES*/
/* Creates counter-variable if not set -------- (ini value is 0)*/
if(!isset($_SESSION['counter'])) {
$_SESSION['counter'] = 0;
}
/* Creates score-variable if not set -------- (ini value is 0)*/
if(!isset($_SESSION['score'])) {
$_SESSION['score'] = 0;
}
/*-------------------------------------------------------------------*/
/* SET COUNTER, SCORE AND DONE*/
/* Check if answer previous question has been submitted*/
if (isset($_GET['a'])) {
$submitted = true;
} else {
$submitted = false;
}
/* Set counter*/
if ($submitted){
$_SESSION['counter'] += 1;
}
$cqi = $_SESSION['counter'];
/* Set score*/
if ($submitted) {
if ($as[$cqi-1][$_GET['a']]['c']){
$_SESSION['score'] += 1;
}
}
$score = $_SESSION['score'];
/* Check done*/
if($cqi >= count($qs)){
$done = true;
} else {
$done = false;
}
echo 'cqi: '.$cqi;
echo 'done: '.$done;
/*-------------------------------------------------------------------*/
?>
<!-- START HTML!!! -->
<html>
<head>
</head>
<body>
<br><br>
<?php
if($done){
echo 'You finished the quiz. <br> Your score is: '.$score;
echo "<form action='index.php' method='get'>";
echo "<input type='hidden' name='TryAgain' value=true>";
echo "<input type='submit' value='Try again!'>";
echo "</form>";
} else {
echo $qs[$cqi];
echo "<form action='index.php' method='get'>";
$cci = 0;
foreach($as[$cqi] as $cc){
echo "<input type='radio' name='a' value=".$cci.">".
$cc['t']."<br>";
$cci++;
}
echo "<input type='submit' value='Next question'>";
echo "</form>";
echo "<br><br>Current score: ".$score;
}
?>
</body>
</html>
Please help me, I really am stuck with this.
-Edit-
I tried again omitting line 3-8 and keeping session_set_cookie_params(600);, to test this function as simply as possible. I tested it the same way as cited above, reopening my browser time and time again and noting down which question I got (q. 0 or 1). I got a seemingly random pattern, of first question 0 and the question I should be on, 1, in which 0 is often the most prevalent. I am quite sure it is random, as I removed the cookie and redid the test multiple times and each time I saw a different pattern. The cookie does expire now at the right time though.
I also tried the ini_set('session.cookie_lifetime', 600); instead of session_set_cookie_params(600); function, as suggested in the other question, but I still had random results. And I don't think it is a good idea for me to try and create a login system if I even can't get this right...

issue in session variables

I am new to php.
I want to use form data that are sent through <form method="POST" action="formdata.php"> to formdata.php be used in another file called main.php. For this I ucerated session variables in formdata.php
Hers's my code in formdata.php
<?php
session_start();
include_once("connect.php");
$n=$_POST['name'];
$p=$_POST['password'];
$sql=mysql_query**strong text**("SELECT * FROM member WHERE `userName`='$n' AND `password`='$p'");
if(mysql_num_rows($sql)==1){
$_SESSION['user']=mysql_fetch_array(mysql_query("SELECT * FROM member WHERE `userName`='$n' AND `password`='$p'"));
if($_SESSION['user']){
$user=$_SESSION['user'];
$_SESSION['userN']="$user(['userName'])";;
$_SESSION['level']="$user(['level'])";
//header("location:mainPage.php");
echo $user['level'];
echo $_SESSION['level'];
}
}
else{
echo "invalid user name or password" ;
}
?>
But when I echo $user['level'];
echo $_SESSION['level']; all I get printed is 3Array(['level']). Here echo $user['level'] gives the desired out put 3, but echo $_SESSION['level'] gives an array as Array(['level']). What can I do to make it print 3?
My next question is I want to use this level value in another php file (main.php). I lerant that session variables are global. So can I use $user['level'] or should I use $_SESSION['level']. In main.php I want to check the condition
if($user['level'] == 3) {
echo "level 3 user";
}
The issue is this line: $_SESSION['userN']="$user(['userName'])";;
You're setting $_SESSION['userN'] equal to whatever $user is in string form which is Array, and (['username']).
Why are you even setting userN? $_SESSION should already contain the user in question, and you can just retrieve it anywhere to get the contents.
This should be all you need:
<?php
session_start();
include_once("connect.php");
$n=mysql_escape_string($_POST['name']);
$p=mysql_escape_string($_POST['password']);
$sql = mysql_query("SELECT * FROM member WHERE `userName`='$n' AND `password`='$p'");
if(mysql_num_rows($sql)==1)
{
//You can reuse the original $sql here. No need to run another query.
$_SESSION['user']=mysql_fetch_array($sql);
//If mysql_num_rows($sql) returns 1, $_SESSION['user'] should always be equal to a user array (Which is true).
header("location:mainPage.php");
}
else{
echo "invalid user name or password" ;
}
?>
On the other page (mainPage.php), just use session_start(), and check to see what is inside $_SESSION. This script should give you a jump start:
<?php
session_start();
print_r($_SESSION);
//This will get the level you're looking for
$level = $_SESSION['user']['level'];
?>
It should contain the user/level and any other information you need.

Hits Counter code error set cookie

I have a PHP code for hits counter with cookies:
$id = intval($_GET['id']);
if(!isset($_COOKIE['visited'])) {
echo "not set";
setcookie("visited",$id,time()+3600);
mysql_query("UPDATE movie SET movie_views = ( movie_views + 1) WHERE id = $gid ");
}
Now the problem is that when I refresh the page, it counts 1 hit everytime and doesn't wait for 1 hour.
I think your requirements are:
1) Someone visits your site with an ID of a record passed as part of the URL ($_GET).
a) IF they visit after some elapsed 'time interval' then the 'ID' is recorded.
b) If they have visited before and the 'time interval' has not expired then the request to record the 'id' is ignored.
The 'time interval' is recorded in a COOKIE called 'visited'.
You record the details in a database - i store the id in a $_SESSION variable. It is for demonstration only.
I show the method only. It is not meant to be efficient. It is designed to be debugged very easily. It reports every step and state.
I use a 'time interval' of 20 seconds.
I have a working example at: viper-7.com?id=9/. Note: the $_GET[id] parameter is passed on the 'viper-7' URL! you can change it to ensure the code works. It will reject your new id until the 20 seconds have elapsed.
The code (it is commented):
<?php
session_start(); // Testing only - store last ID in $_SESSION['id']!
define ('VOTE_DELAY', '20'); // seconds
// show 'visited cookie or if missing...
if (isset($_COOKIE['visted'])) {
echo '<pre>';
var_dump($_COOKIE['visited']); // show all cookies currently active
echo '</pre>';
}
else {
echo '<br />No current $_COOKIE[visited] found!';
echo '<br />';
}
// DEBUG - show current ID
echo '<br />Current Session ID: ', !empty($_SESSION['id']) ? $_SESSION['id'] : 'none';
echo '<br />';
// process whether visited in the last interval (20 seconds)
if (isset($_COOKIE['visited'])) {
echo '<br />active Cookie: ', $_COOKIE['visited'],' - will leave now...';
return; // no more voting until cookie expires
}
// no id provided - is error
if (empty($_GET['id'])) {
echo '<br />no valid $_GET[id] provided : will leave - NO Visited Cookie set ';
return; // do nothing
}
$id = $_GET['id']; // store new id in the session rather than the database
echo "<br />New VALID visit: will store cookie for: ", $id, ' in the $_SESSION[id] variable';
setcookie("visited", "$id", time() + VOTE_DELAY); // set the 'visited cookie
$_SESSION['id'] = $id; // store in session rather than the database.
// mysql_query("UPDATE movie SET movie_views = ( movie_views + 1) WHERE id = $gid ");
echo "<br /> new cookie set...";
I have no idea why your code does not work.
Also, if the client deletes the 'visited' cookie then they can get the 'id' recorded as often as they wish. You will need to analyse the records in the database to ensure 'recordings of 'id' are valid.

How to create session for sql query result in php

I want to create session for the record tag_id here is my sql code please help me how i create session for this value..
<?php
$sql_tagid=mysql_query("SELECT * FROM tag_new WHERE EMAIL_ID='$sessionemail' AND CUST_ID='$id'") or die(mysql_error());
while($tagid=mysql_fetch_array($sql_tagid)){
echo $tagid['tag_id'];
}
?>
First you need to start session
session_start();
after that add variable to session
$_SESSION['tag'] = $tag['tag_id']
after that you can check by print session
print_r($_SESSION); you value in session or not
$_SESSION['tag'] = $tagid['tag_id']
Try this, if you have mutliple tag id then use it $_SESSION['tag_id'][], if you have only one $_SESSION['tag_id']
session_start();
while($tagid=mysql_fetch_array($sql_tagid)){
$_SESSION['tag_id'][] = $tagid['tag_id'];
}
var_dump($_SESSION['tag_id']);
<?php
session_start(); // To assign a session variable you have to start the session
$sql_tagid=mysql_query("SELECT * FROM tag_new WHERE EMAIL_ID='$sessionemail' AND CUST_ID='$id'") or die(mysql_error());
while($tagid=mysql_fetch_array($sql_tagid))
{
$_SESSION['tag_id'] = $tagid['tag_id']; // assign tag_id value to session variable
echo $tagid['tag_id'];
}
?>
For getting the value of session on another page say page1.php then you have to do :-
page1.php
<?php
session_start();
echo $_SESSION['tag_id'];
?>

Categories