How to Store session data of user - php

first question for the site(i am new to this site)
thought to post my most difficult problem .....
I have Login system in my site after successful login my protected page is displayed only after login i want to add $_SESSION['point'] to store the point of user.and save it to data base and the point will be increased if user click link. I want to store this increased point into my userdb.php. where all sign up information i kept.(i have not used MySql for signup Form I have used userdb.php file)my protected page php code are
<?php
if (session_id() == "")
{
session_start();
}
if (!isset($_SESSION['username']))
{
header('Location: #');
exit;
}
if (isset($_SESSION['expires_by']))
{
$expires_by = intval($_SESSION['expires_by']);
if (time() < $expires_by)
{
$_SESSION['expires_by'] = time() + intval($_SESSION['expires_timeout']);
}
else
{
unset($_SESSION['username']);
unset($_SESSION['expires_by']);
unset($_SESSION['expires_timeout']);
header('Location: #');
exit;
}
}
if (session_id() == "")
{
session_start();
}
if (session_id() == "")
{
session_start();
}
?>
My display.php to show urls
<?php
mysql_connect('Server', 'user', 'passs');
mysql_select_db('add');
$query =mysql_query('select * from addimage');
while( $row = mysql_fetch_assoc($query) )
{
echo '
<div style="min-width:300px;height:100px;border:red 5px;float:left;">'.$row['url']. '</div>';
}
?>

You can write your login PHP like,
<?php
// if PHP > 5.4: if (PHP_SESSION_NONE == session_status()) {
if ('' == session_id()) {
session_start();
}
if (isset($_SESSION['expires_by'])) {
$expires_by = intval($_SESSION['expires_by']);
if (time() < $expires_by) {
$_SESSION['expires_by'] = time() + intval($_SESSION['expires_timeout']);
} else {
session_destroy();
}
}
if (!isset($_SESSION['username'])) {
Header('Location: ' . $_SERVER['REQUEST_URI']);
exit();
}
?>
Then to click on the URLs you could perhaps use jQuery and AJAX. You should declare a class like "link-block" in your CSS, and write the URLs like this
echo '<div class="link-block">'.$row['url'].'</div>';
and add a click handler to those DIVs in the page's onReady Javascript, after including jQuery scripts:
$('.link-block').on('click', function(e) {
$.post('/increase-points.php', { }, function(retval){
if (retval.newpoints) {
$('#point-block').html(retval.newpoints);
}
});
});
The increase-point handler needs to open the session, which is the same code as you have above (so you can put it into an external include "session.php"), and open the database connection (another include...), then:
UPDATE usertable SET points = points + 1 WHERE user_id = {$_SESSION['user_id']};
or if you have a username only (ensure it's properly escaped)
...WHERE username = '{$escapedSessionUsername}';
By the way, I need to add the standard mysql_* deprecation disclaimer.
After which, you might return the current points to be displayed into a DIV with id of "points-block":
You have <span id="points-block"></span> points.
by returning it in JSON after querying them from the database (or you can keep them in session and update both DB and session; it saves you one query)
// This in /update-points.php
$retval = array('newpoints' => $updated_points);
Header('Content-Type: application/json;charset=utf8');
die(json_encode($retval));
You can do this in other ways too, but I saw no anchor in your link div, so I guess you want something dynamic, which mostly means AJAX.

Related

Multiple steps form with sessions security

Hi i'm developing a multi steps form with php using session and i've been wondering if there is a way for the user to alter session variables for example on the first page i have something like this :
<?php
session_start();
if(isset($_POST['submit'])){
$_SESSION['name'] = $_POST['name'];//and so on
}
?>
and the other page has something like :
<?php
session_start();
$name = $_SESSION['name'];
?>
my question is can the user modify the value of the session variable on the second page
Since you're populating the session variable with the value of a POST variable, they can continue to resubmit the first form as much as they want with arbitrary values.
You can use application logic to defeat this:
<?php // form1
session_start();
if (empty($_SESSION['step'])) {
$_SESSION['step'] = 1;
}
if ($_SESSION['step'] > 1) {
header("Location: form2.php");
exit; // This exit is very important, don't neglect it
}
if (isset($_POST['submit'])){
$_SESSION['name'] = $_POST['name'];//and so on
$_SESSION['step'] = 2;
}
And then
<?php // form2
session_start();
if (empty($_SESSION['step'])) {
header("Location: form1.php");
exit;
}
if ($_SESSION['step'] > 2) {
header("Location: form3.php");
exit;
}
if ($_SESSION['step'] < 2) {
header("Location: form1.php");
exit;
}
$name = $_POST['name'];
By using application logic, you can control the flow of your visitors within your application.
If you're asking if users can change $_SESSION variables outside of any code you've written, the answer is usually no. See also: this answer.

How to condition a user to fill the form than to oppen an specific site up

i have a multi step form and want to condition users on specific sites on my web .
This mean i want that only after submitting my form a client in my case can see the redirected page ,
And that with a kinda tim-out for that page to . this redirected page need to show only to those people who fill the form first even when users copy the link and give that link to somebody else the link should not work or should direction in a error. i have archived the last part partly
Here is all my code :
On the form.php i have this :
<?php
session_start(); $_SESSION['form_finished'] = true;
?>
On the proces.php i have this :
$emotion = $_POST['emotion'];
if($emotion == 'Basic Pack') {
session_start();
$_SESSION['form_finished'] = true;
header('Location: /new/basicc.php');
} elseif($emotion == 'Deluxe Pack') {
header('Location: html6.php');
} elseif($emotion == 'Premium Pack') {
header('Location: html7.php');
}
and destination site in this case basicc.php' this :
<?php
session_start();
if(!$_SESSION['form_finished']) {
header("HTTP/1.0 404 Not Found");
exit;
}
?>
This code is working partly because if the user on the form.php site if he just copy the basicc.php link on the address bar he can see the basic.php site imadtitly without having to fill the form , and i want that to condition him to do that and than the page to show up .
I hope i was clear thanks in advance
If proces.php is where submitting the form redirects then remove $_SESSION['form_finished'] = true; from form.php and keep it in proces.php only.
ETA: For the timer:
<script>
var remainingSeconds = 600; // how many second before redirect
function counter() {
if (remainingSeconds == 0) { clearInterval(countdownTimer); window.open('form.php', '_SELF'); // return to form page
} else { remainingSeconds--; }
}
var countdownTimer = setInterval('counter()', 1000); // 1000 is the interval for counting down, in this case 1 second
</script>
In this case, you will have to add back the statement in form.php but set it to false $_SESSION['form_finished'] = false;
ETA2: Forgot to mention that you should also add $_SESSION['form_finished'] = false; in basicc.php.
Yes you could just use a simple session for this case. Example:
If in your form action, if the form processing is in process.php. You could initialize there the session.
session_start();
$emotion = $_POST['emotion'];
$_SESSION['form_finished'] = true; // set session
// then your other process etc. etc.
if($emotion == 'Basic Pack') {
header('Location: /new/basicc.php');
} elseif($emotion == 'Deluxe Pack') {
header('Location: html6.php');
} elseif($emotion == 'Premium Pack') {
header('Location: html7.php');
}
And then on the destination files: /new/basicc.php and others, check that session existence:
/new/basicc.php and others:
if(isset($_SESSION['form_finished'])) { // so after redirection check this
//
// hello, i came from process.php
unset($_SESSION['form_finished']); // and then UNSET it! this is important
} else {
echo 'not allowed'; // if this is not set, the page is directly accessed, not allowed
exit;
}
I think the best solution is that you should only use one page, no need for sessions ;)
Try to have a particular variable set to false, send your form to the server using a POST method <form method=post> and on your server, change this variable to true and render the same page again.
In the example below, I'm checking if the user has entered his name in the form. ;)
<!-- In form.php -->
<?php
$formSubmitted = false;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST["name"])) {
//Do what you need to do with form data, for example:
$name = filter_var($_POST["name"],FILTER_SANITIZE_STRING);
//Maybe do some checks on the data (or add to database) and when successful:
if($name != '')
{
$formSubmitted = true; // Set variable to true
}
}
?>
<?php if($formSubmitted): ?>
Hello <?php echo $name; ?>! <!-- Show all other HTML things you want to show -->
<p> This is a message only for people who submitted the form! </p>
<?php else: ?>
<form action='form.php' method='POST'>
<input name='name' type='text'>
</form>
<?php endif; ?>
I hope it'll be useful and hopefully a different way to look at the problem. For multi-step, this could easily accommodate more variables to see which step the user is on ;)
Good luck :)

Jquery login form driving me crazy

So I have a home page where a user can log in. Once they log in I need them to redirect them to index.php that just pulls there information. The Jquery makes a call to index.php where it runs a check against Mysql, if the user doesn't exist it alerts not a valid user. Now if it does I need to send them back to index.php.
Hers is index.php
<?php
include_once 'includes/membersclass.php';
session_start();
$member = new MEMBERS();
if(!isset($_SESSION['id'])) {
if($_POST['action'] == true) {
$result = $member->login($_POST);
if($result) {
$_SESSION['id'] = $result;
echo $_SESSION['id'];
} else {
return false;
}
}
if($_POST['signup'] == 'true') {
$result = $member->signup($_POST);
if($result) {
$_SESSION['id'] = $result;
} else {
header("Location: root.php");
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel='stylesheet' type='text/css' href='css/members.css' />
</head>
<body>
<div id="calendar_container">
<?php $member->drawCalendar(2, 2011); echo $_SESSION['id']; ?>
</div>
</body>
</html>
As you can see Jquery makes the initial call to index.php with a post and get the response back. I set the session to store the user id. On the same page is where the users profile will show. How do I get back here on successful login. Am I even doing it right, should this be separate from the PHP to begin with. Uggghhh, please help.
The question is a bit vague, but if I understand correctly you want to reload the index.php page after a successful login.
if(!isset($_SESSION['id'])) {
if($_POST['action'] == true) {
$result = $member->login($_POST);
if($result) {
$_SESSION['id'] = $result;
echo $_SESSION['id'];
} else {
return false;
}
}
If I'm not mistaken, this piece of code checks if user is already logged in. If not, your checking if the previous Jquery page has given either an 'action' (which I assume is a login call) or a 'signup' (which I assume is to create a new account).
In this case, if 'action' is chosen, you check if the user exists ($result = $member->login($_POST);) and if he does, you create the session ID, and the index-page should show the profile.
Since the $_SESSION['id'] has only been assigned after the page has loaded, it does not check if the $_SESSION['id'] has been assigned again. So you have to reload the page to do this:
if(!isset($_SESSION['id'])) {
if($_POST['action'] == true) {
$result = $member->login($_POST);
if($result) {
$_SESSION['id'] = $result;
echo $_SESSION['id'];
header("Location: index.php");
} else {
return false;
}
}
Now it will call the index.php again, it goes past the if(!isset($_SESSION['id'])) part, since this time the session is created, and to the code (which is not yet present here?) that will take care of the profile.
I have to assume quite a bit here, but tell me how close I am.
PS:
if($_POST['action'] == true)
and:
if($_POST['signup'] == 'true')
Once you have true without quotes, once with. I think you just want to check which one is set? This will suffice:
if(isset($_POST['signup']))
and
if(isset($_POST['action']))
Makes the code more consistent and less prone to errors.

Redirecting cookieless sessions in PHP without clicking a link

I've been fighting with the cookieless sessions solution. Of course cookieless sessions solution is amazing. I have a trouble in implementing it because I can't read the session information after redirecting to another page.
Here's my test code in testcode.php
<?php
ini_set('session.use_trans_sid', '1');
session_start();
if (isset($_GET['pagecode'])) {
session_id($_GET['pagecode']);
print_r($_SESSION); // **cannot read session information here**
exit();
}
if (isset($_SESSION['cookieconfirmed']) && $_SESSION['cookieconfirmed'] == 1) {
} else {
/** Checks if the user's browser is cookie-enabled **/
if (isset($_GET['redirected'])) { // if the page has gotten redirected
$_SESSION['cookieconfirmed'] = 1; // confirmed the cookie-disability
if (isset($_COOKIE['testcookie'])) {
header ('location: testcode.php');
} else {
header('location: testcode.php?pagecode=' . session_id());
}
} else {
setcookie('testcookie', 'OK'); //sets a test cookie.
header('location: testcode.php?redirected=1'); // redirects the page to check cookie-disability
}
exit(0);
}
?>
As you can see this code doesn't work. but if i redirect to another page by clicking a link it works well. Here's the code in testcode.php:
<?php
ini_set('session.use_trans_sid', '1');
session_start();
if (isset($_GET['pagecode'])) {
session_id($_GET['pagecode']);
print_r($_SESSION); // **able to read session information here**
exit();
}
if (isset($_SESSION['cookieconfirmed']) && $_SESSION['cookieconfirmed'] == 1) {
} else {
/** Checks if the user's browser is cookie-enabled **/
if (isset($_GET['redirected'])) { // if the page has gotten redirected
$_SESSION['cookieconfirmed'] = 1; // confirmed the cookie-disability
if (isset($_COOKIE['testcookie'])) {
header ('location: testcode.php');
} else {
echo 'Click here to continue';
}
} else {
setcookie('testcookie', 'OK'); //sets a test cookie.
header('location: testcode.php?redirected=1'); // redirects the page to check cookie-disability
}
exit(0);
}
?>
How can I get this to work without clicking a link?
ini_set('session.use_trans_sid', '1');
You have to have this on every single one of your PHP pages - you can't do it just within the session handling script. If it's not on when PHP generates a page, it won't insert the session ID into forms and urls on that page. As such, it'd be better if you put this into your php.ini, or at least httpd.conf/.htaccess (as a php_value) to make it a global option for all scripts.
PHP function for this is :
function append_sid($link) {
if(session_id() !== NULL && !isset($_COOKIE['PHPSESSID'])) {
if(strpos($link, "?") === FALSE) {
return $link . "?PHPSESSID=" . session_id();
} else {
return $link . "&PHPSESSID=" . session_id();
}
} else {
return $link;
}
}
Javascript Function for this is:
function append_sid(link) {
<?php if(session_id() !== NULL && !isset($_COOKIE['PHPSESSID'])) { ?>
var session_id = '<?php echo session_id ?>';
if(link.indexOf('?') == -1) {
return link + '?PHPSESSID=' + session_id;
} else {
return link + '&PHPSESSID=' + session_id;
}
<?php } else { ?>
return link;
<?php } ?>
}
A caveat – passing session id by URL requires the session.session.use_trans_sid tio be set to 1.
php_value session.use_trans_sid = 1 in the .htaccess file. You can also try the function:
ini_set('session.use_trans_sid', '1')

Making a Function-Activated Link Appear Without Having to Refresh Browser

I'm trying to use the code below to make the <a href='http://www...com/.../footervote.php'>Vote</a> link appear if a user logs in and a user shows up in the function getEditorsList(). The vote link only appears if the browser is refreshed.
Any idea how I could make the vote link appear without having to refresh the browser?
Thanks in advance,
John
index.php:
<?php
require_once "header.php";
//content
include "login.php";
// more content
require_once "footer.php";
?>
In header.php:
<?php
error_reporting(0);
session_start();
require_once ('db_connect.inc.php');
require_once ("function.inc.php");
$seed="0dAfghRqSTgx";
$domain = "...com";
$editors = getEditorsList();
foreach($editors as $editor)
{
$editorids[] = $editor['loginid'];
}
if(in_array($_SESSION['loginid'], $editorids))
{
echo "<div class='footervote'><a href='http://www...com/.../footervote.php'>Vote</a></div>";
}
?>
login.php:
<?php
if (!isLoggedIn())
{
if (isset($_POST['cmdlogin']))
{
if (checkLogin($_POST['username'], $_POST['password']))
{
show_userbox();
} else
{
echo "Incorrect Login information !";
show_loginform();
}
} else
{
show_loginform();
}
} else
{
show_userbox();
}
?>
Do you set $_SESSION['loginid'] after your in_array query? If you render header.php first, in_array returns false (although the session has been started, but loginid will be set a few lines down the road in login.php).
Move this:
if(in_array($_SESSION['loginid'], $editorids))
{
echo "<div class='footervote'><a href='http://www...com/.../footervote.php'>Vote</a></div>";
}
from header.php to login.php like this:
else {
show_userbox();
if (in_array...
}
If the link is present but hidden you use some DHTML (JQuery / Scriptaculous) to set the display/visibility attributes correctly.
If the link is not present in the original html (preferable for security reasons) then when the login occures fire off an AJAX request that returns javascript that will insert the link in the correct location (parent element).

Categories