Search the Community
Showing results for tags 'sessions'.
-
I have setup Google Enhanced Analytics on my website to track each stage of the checkout process. I.E. 1) Step 1 - View Cart 2) Step 2 - Add Billing Details (Checkout page in book) 3) Step 3 - Review order, add payment details This triggers when a user loads each page. However the Google analytics is showing more users are reaching Step 3 than are reaching the Step 2 (an impossible event). So I am wondering, as per the book: "The shopping part of the site purposefully does not use sessions (in order to give longevity to the customer’s cart and wish list), but the checkout process will." - Does starting a new session at Step 2 cause this issue? Has anyone else had an issue with this? Or am I barking up the wrong tree?
-
Hi Larry, I have been using your database session handler for quite some time now in my Windows 7 environment but have run into a problem when I try to use it in a new PC set up with Windows 10 and Apache/PHP 7.3.7 (64 bit). I keep getting an error: "An error occurred in script 'C:\xampp\htdocs\....php' on line 53: session_write_close(): Session callback expects true/false return value" and I am getting this error everywhere that I have used 'session_write_close()' as per page 95 of the book (that's in dozens of places). Is it perhaps not needed in Win 10 with a fairly current Apache/PHP install? Or do I need to code it differently? Any advice will be most appreciated and thanks in anticipation.
-
Right now on my website I created when someone is logged in they can go to the url in the address bar and change the id number associated with the url. for example one page I have is add_image.php?id=4 4 is the id associated with the article. If someone changes the 4 to a 7 for example. Then my page will show the other user's data on my page without them even entering that other person's login info. How do I make sure people can't see other user's data when they change the id number. I am using the scripts from this book. Maybe I missed something. I am using sessions properly as far as I can tell. I really would need some help with this. please give an example of secure code to use. thank you
-
I have followed the book closely and looked over the code to make sure it matches Larry's. However, no matter what I do, I am not able to load the session into the database when I run the sessions.php file as per the book. I was hoping on some help to figure out what the issue is. I am running PHP 5.4.10 and Mysql 5.5.29. Thanks for the help in advance! ******This is my db_sessions.inc.php file:********* <?php # Script 3.1 - db_sessions.inc.php /* * This page creates the functional interface for * storing session data in a database. * This page also starts the session. */ // Global variable used for the database // connections in all session functions: $sdbc = NULL; //diff than DBC bc this is meant for sessions... make global for session connections (does not have to be and in fact would only use one in general so change code accordingly) function open_session() { global $sdbc; $sdbc = mysqli_connect( 'localhost', 'root', 'pass', 'advPHP' ) ; return true; //always return somethign except for read function (indicate success Boolean rather than just true) } function close_session() { global $sdbc; return mysqli_close( $sdbc ); } function read_session( $sid ) { global $sdbc; $q = sprintf( 'SELECT data FROM sessions WHERE id="%s"', mysqli_real_escape_string($sdbc, $sid) ); $r = mysqli_query( $sdbc, $q ); if( mysqli_num_rows($r) == 1) { list($data) = mysqli_fetch_array($r, MYSQLI_NUM); return $data; } else { return ''; } } function write_session($sid, $data) { global $sdbc; $q = sprintf( 'REPLACE INTO sessions (id, data) VALUES("%s", %s")', mysqli_real_escape_string($sdbc, $sid), mysqli_real_escape_string($sdbc, $data) ); $r = mysqli_query($sdbc, $q); return true; } function delete_session( $sid ) { global $sdbc; $q = sprintf( 'DELETE FROM sessions WHERE id="%s"', mysqli_real_escape_string($sdbc, $sid) ); $r = mysqli_query( $sdbc, $q ); $_SESSION = []; // return mysqli_affected_rows($sdbc) ; return true; } function clean_session($expire) { global $sdbc; $q = sprintf('DELETE FROM sessions WHERE DATE_ADD (last_accessed, INTERVAL %d SECOND) < NOW()', (int) $expire); $r = mysqli_query($sdbc, $q); return true; } session_set_save_handler( 'open_session', 'close_session', 'read_session', 'write_session', 'delete_session', 'clean_session' ); session_start(); ******And this is my sessions.php file******** <?php # Script 3.2 - sessions.php /* This page does some silly things with sessions. * It includes the db_sessions.inc.php script * so that the session data will be stored in a database. */ // Include the sessions file: // The file already starts the session. require('db_sessions.inc.php'); ?><!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>DB Session Test</title> <link rel="stylesheet" href="style.css"> </head> <body> <?php print_r($_SESSION); // Store some dummy data in the session, if no data is present: if( empty($_SESSION) ) { $_SESSION['blah'] = 'umlaut'; $_SESSION['this'] = 3615684.45; $_SESSION['that'] = 'blue'; echo '<p> Session data stored. </p>'; } else { echo '<p>Curren session contains <pre>' . print_r($_SESSION, 1) . '</pre> </p>'; } if( isset($_GET['logout']) ) { session_destroy(); echo '<p>Session destroyed.</p>'; } else { echo '<a href="sessions.php?logout=true"> Log Out </a>'; } echo '<p> Session data: <pre>' . print_r($_SESSION, 1) . '</pre></p>'; echo '</body> </html>'; session_write_close(); ?>
-
Hi, I recently restructured a website along the modularization lines (page 44 onwards). The content modules all start with a check to see if the BASE_URL constant has been defined and redirect the user if it has not been defined. This is clear and works just fine in the visitor-accessible part of the site. In the administration part of my website, the modules also check to make sure that an administrator is using the script via a check to a session set up like page 82 onwards. I am having trouble with 'headers already sent' and understand why this is happening and know how to fix that. But my question is do I need both the BASE_URL constant check as well as the administrator/session check in the admin content scripts? There are no financials in the website and also no sensitive data in the database though I need to ensure that non-administrators cannot use the admin scripts. Your thoughts/advice will be welcomed. Cheers from Oz.
- 2 replies
-
- security
- modularization
-
(and 1 more)
Tagged with:
-
Hi all I've been tearing my hair out with this for too long so I'm asking for help. I've been working through the book and everything is going well until this chapter. I believe I have created the sessions as I should. I can log in and out and I've added session_start(); to every page that needs to be restricted by login (password.php, view_users.php, etc). Yet, when I log out I can still view the pages. Is there nothing else I should add to the pages for them to work? No include for login_functions.inc.php, for example? I'm new to this (did you guess?) so I may be missing something so obvious that it wasn't thought worth mentioning. The only mention of how to make the other pages work is this on page 354, as far as I can see: " For the Login/Logout links to work on the other pages (register.php, index.php, etc.), you’ll need to add the session_start() command to each of those. " Thanks for any help you can give me. Mat
-
So I have gone through Chapter 12 a few times. This chapter shows you how to make a login functions first using cookies and then using sessions. I have no problem with creating the login functions with the cookies method using the provided scripts with this book. However when I get to the Session section the provided scripts do not work for me. When I get to Script 12.9 things stop working for example After logging in, I am supposed to be redirected to loggedin.php, which will welcome the user by name using the stored session value. It does not happen for me. Here is my cookies website that works with books files http://www.trueacewebdesign.com/larry-php/website-login-w-cookies/index.php Here is the session files website with the books files that does not work http://www.trueacewebdesign.com/larry-php/website-login-w-sessions/index.php Here is the a zip file of all the session files that has everything in place. http://www.trueacewebdesign.com/website-login-w-sessions.zip I am still a newbie to PHP. However from my understanding I do not need to turn on any special configuration for sessions to work. Note I have successfully used sessions on the same host last month form a different book so I know its not my configuration. Did I miss a step in the book? I don’t see how that is possible since I am using the files unedited from the book. Thank you JP
- 12 replies
-
- ch.12
- script 12.9
-
(and 2 more)
Tagged with:
-
Hi All I'm on page 41 (in Security Fundamentals). Referring to: "For sensitive data being stored, but not stored in a database, change your sessions directory, and use the Web root directory's parent folder (see Figure 2.5)." Could someone elaborate on what this means? I'm not sure what a sessions directory is. When it refers to "sessions", is it talking about session variables that we can create?... like if I wanted to store the logged-in users first name in $_SESSION['userFirstName']? Is temporarily storing potentially sensitive data in session variables not secure? I'm pretty new at this, so please use plenty of laymen terms Thank you so much.
-
Edit: Nevermind do not worry about this thread. Apparently my action attribute for my login form should have been "index.php?p=login". When I give correct login info, it works correctly so I just need to fix the conditional for when the login info is incorrect. Okay so I tried setting up a modular website with the standard header + left sidebar, content, and right sidebar + footer. I also want to include the ability to register / login and put up a "Home | Login" or "Home | Settings" links up at the to of the header depending on whether someone is logged in or not. Now, for some reason when someone logs in successfully and the $_SESSION array is supposed to take in the data from the users table and then head to index.php, it seems that the $_SESSION array is not being set at all... it is empty. I am trying to figure out exactly what is going wrong here. Here is part of my login page: if(mysqli_num_rows($user_check_result) == 1) { //start of valid single match $_SESSION = mysqli_fetch_array($user_check_result, MYSQLI_ASSOC); //update most recent log in $last_logged_query = "UPDATE users SET last_logged_in = NOW() WHERE user_id = {$_SESSION['user_id']} LIMIT 1"; $last_logged_result = dbc_query ($dbc, $last_logged_query); if(mysqli_affected_rows($dbc) != 1) { //if one row was not affected $notes['last_logged_in_failure'] = "There was an error recording the login."; }//end of one row not being affected mysqli_free_result($user_check_result); if(isset($last_logged_result)) mysqli_free_result($last_logged_result); mysqli_close($dbc); $exit_url = BASE_URL . '/index.php'; header("Location: $exit_url"); exit(); } Also, since the else clause after this if clause is not being executed, and the page is being redirected to index.php I assume that the $_SESSION variable is being set. For some reason the redirect seems to be losing the $_SESSION array when it goes over to index.php. I even had to separate the login.php script into a login.inc.calc.php script to be executed befor ethe header.php file and a login.inc.out.php to be executed after the header.php file since a redirect has to occur before HTML output. A rar file of everything (except images) from my site (only 11kb because I just started it) is located here: http://ipredict.danconia.us/ipredict.danconia.us.rar This whole modular thing is making things a bit confusing and I'm wondering whether it's really worth it... if it might not be worth it to go back to the non-modular way of doing things. On the other hand I don't want to back down from a good challenge. Any help would be appreciated. Thank you! Edit: Also, for the record the first real line in index.php is a require('./includes/config.inc.php'); and that config file's first line is start_session(); so I just don't get why that wouldn't be occurring: /* * index.php (homepage) for http://iPredict.danconia.us * Script created by Kylan Hurt * http://kylan.danconia.us */ require('./includes/config.inc.php'); $errors = array(); $notes = array();
-
One method for passing attractive variables between scripts is to append them to an URL like so: <a href="edit.php?x=1">edit</a> The issue being that "x=1", while provocatively visible in the URL, is easily coerced to become "x=99", or some other arbitrary value of dark intent and high suspicion. Is it merely that I have yet to find the session-based solution for this in the book? Obvious session assignments, i.e., registering a user name as a session variable, are straightforward. But the example listed above seems to present a different sort of challenge. ~ David
-
Hi all! I've followed the authentication tutorials here, but i wonder if Yii has a workaround for using both cookies and sessions for authentication. I want to allow use of the "remember me" button, but still save the roles, emails and such in sessions for security. Acording to the yii-manual the CBaseUserIdentity::setState will use cookies if its enabled, and use sessions if its set to false. Im thinking about a solution where you save a sha1($username $password) in the cookie, and make a method that gathers the other information in a auto-load-if-logged-in sort of way, but im not sure how secure it is, and if it might put to much unnessesary stress on the DB-server. Anyone made anything like that work, or has any idea? Edit: tags turned out wrong, cant seem to edit them. authentication spelled wrong, and also stuck together with cookies tag.
- 1 reply
-
- autenticationcookies
- sessions
-
(and 1 more)
Tagged with:
-
Hi, still teaching myself, Larry's books are great. As I am not in the computer field, when I go to places like PHP.net for info I usually can't figure out what they are really trying to say to me. I hope that my question below is proper for this forum, if not please excuse my question and I will respectfully withdraw it. I bought the PHP 5 Advanced book really to learn OOP, something very new to me. I am able to work through Larry's examples an do eventually get things to work when I modify the examples, to be sure I understand how the coding works. I took Script 3.1 db_sessions.inc.php and decided to turn it into an object, originally I wasn't able to get it to work no matter what I tried. On PHP.net I saw: "When using objects as session save handlers, it is important to register the shutdown function with PHP to avoid unexpected side-effects from the way PHP internally destroys objects on shutdown and may prevent the write and close from being called. Typically you should register 'session_write_close' using the register_shutdown_function() function." I tried to figure out what this meant but wasn't able to make my script work, until I found an example on the Internet in a chat room that initiated the the function like this below, not by just sending the objects, but by passing each of them in a different array along with a '$this' as a separate array item: session_set_save_handler( array($this,'OpenSession'), array($this,'CloseSession'), array($this,'ReadSession'), array($this,'WriteSession'), array($this,'DestroySession'), array($this,'GarbageCollectionSession')); Then everything worked, "CloseSession, ReadSession, WriteSession, DestroySession and GarbageCollectionSession are all objects that do their respective tasks. Can someone tell me why passing them as arrays with item [0] = "$this", and then item [1] = "TheObject" works, and also what kind of parameter have I passes. I would have not guessed that I could pass an array to a function in that manner without first assigning it to a variable? I am using XAMPP, PHP 5.3.8 and am on a Windows 7 PC. Any insight would be appreciated. Tony
-
I'm developing my site with shared hosting ssl certificate. As Larry describes in the book, I'm trying to use the session id from the http pages after I get to the https pages, and be able to go back and forth. From home page I click login, I log in and my code tries to redirect to loggedin page. But between login and loggedin there is a new id generated. That is what I think is happening. So that causes my loggedin page to fail because test says user is not logged in. And this will also cause everything else to fail but this is the first thing I'm testing. Here is the code I am using, at the start of each page: (I pass $sid in the url) // Start output buffering: ob_start(); // Start the session: // if the session is available from the url use that otherwise start a new session if ($_SERVER['REQUEST_METHOD']=='GET') { if (isset($_GET['sid'])) { $sid = $_GET['sid']; if ($sid > 0) { // I set it zero when there is none echo "
- 3 replies
-
- session ids
- sessions
-
(and 2 more)
Tagged with:
-
Not sure if I am getting this, I followed along and still I am seeing the PHPSESSID here is the code <?php // Script 9.8 - logout.php /* * * Session ID is still present * I am using a Edit this Cookie * A Chrome Add On for working with * Cookies, still seeing the * PHPSESSID | localhost */ // Need the session session_start(); // Delete the session variable unset($_SESSION); // Reset the session array $_SESSION = array(); session_destroy(); // Define the page title and include the header define('TITLE', 'Log Out!'); require('_includes/header.html'); echo '<h2>Log Out Page!</h2>'; require('_includes/footer.html'); ?> Why am I still seeing the session ID ? Thanks so much!
-
I am having trouble getting my scripts to work when it coes to sessions without cookies. I have amended the login.php script as per the book and then amended the remaining scripts header.html, loggedin.php and logout.php as described in the book but find when entering a valid email address and password I am returned straight to the index.php page. Please can you assist me in understanding what I am doing wrong, I have been trying to work through it and resolve it my self for the last 2 days. I have MySQL Server 5.5, php 5.3.6 and Windows 7 Home 64bit running on my own computer using the localhost server. Please find attached my scripts. Login.php <?php # Script 9.16 - login.php // Send nothing to the browser before session_start() line! // Check if the form has been submitted. if (isset($_POST['submitted'])) { require_once ('../secure/mysql_connect.php'); // Connect to the db. $errors = array(); // Initialise error array. // Check for an email address. if (empty($_POST['email'])) { $errors[] = 'You forgot to enter an email address.'; } else { $e = escape_data($_POST['email']); } // Check for a password. if (empty($_POST['password'])) { $errors[] = 'You forgot to enter a password.'; } else { $p = escape_data($_POST['password']); } if (empty($errors)) { // If everything is OK. /* Retrieve the user_id and first name for the email/password combination */ $query = "SELECT user_id, first_name FROM users WHERE email='$e' AND password=SHA('$p')"; $result = @mysql_query($query); // Run the query. $row = mysql_fetch_array ($result, MYSQL_NUM); // Return a record, if applicable. if ($row) { // A record was pulled from the database. // Set the session data and redirect. session_name ('YourVisitID'); ini_set('session.use_cookies', 0); // Don't use cookies. session_start(); $_SESSION['user_id'] = $row[0]; $_SESSION['first_name'] = $row[1]; // Redirect the user to the loggedin.php page. // Start defining the URL. $url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']); // Check for trailing slash. if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\')) { $url = substr($url, 0, -1); // Chop off the slash. } // Add the page. $url .= '/loggedin.php?' . SID; // Add the session name & ID. header("Location: $url"); exit(); // Quit the script. } else { // No record matched the query. $errors[] = 'The email address and password entered do not match those on file.'; // Public message. $errors[] = mysql_error() . '<br /><br />Query: ' . $query; // Debugging message. } } // End of if(empty($errors)) if. mysql_close(); // Close the database connection. } else { // Form has not been submitted. $errors = NULL; } // End of main submit conditional. // Begin the page now. $page_title = 'Login'; include('./includes/header.html'); if (!empty($errors)) { // Print any error messages. echo '<h1 id="mainhead">Error!</h1> <p class="error">The following error(s) occurred:<br />'; foreach ($errors as $msg) { // Print each error. echo "- $msg<br />\n"; } echo '</p><p>Please try again.</p>'; } // Create the form. ?> <h2>Login</h2> <form action="login.php" method="post"> <p>Email Address: <input type="text" name="email" size="20" maxlenght="40" value="<?php if (isset($_POST['email'])) echo $_POST['email']; ?>"/></p> <p>Password: <input type="password" name="password" size="20" maxlength="20"/></p> <p><input type="submit" name="submit" value="Login"/></p> <p><input type="hidden" name="submitted" value="TRUE"/> </form> <?php include ('./includes/footer.html'); ?> Header.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR...ransitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title><?php echo $page_title; ?></title> <style type="text/css" media ="all">@import "./includes/layout.css";</style> </head> <body> <div id="wrapper"><!-- Goes with the CSS layout. --> <div id="content"><!-- Goes with the CSS layout. --> <div id="nav"><!-- Links section --> <h3>Menu</h3> <ul> <li class="navtop"><a href="index.php?<?php SID; ?>" title="Go to Home Page">Home</a></li> <li><a href="register.php" title="Register?<?php SID; ?>">Register</a></li> <li><?php // Create a login/logout link. if ((isset($_SESSION['user_id'])) && (!strpos($_SERVER['PHP_SELF'], 'logout.php'))) { echo '<a href="logout.php?<?php SID; ?>" title="Logout">Logout</a>'; } else { echo '<a href="login.php?<?php SID; ?>" title="Login">Login</a>'; } ?></li> </ul> </div> <!-- Script 9.8 - header.html --> <!-- Start of page specific content --> Loggedin.php <?php # Script 9.17 - loggedin.php # User is redirected here from login.php. session_name ('YourVisitID'); ini_set('session.use_cookies', 0); session_start(); // Start the session. // If no session value is present redirect the user. if(!isset($_SESSION['user_id'])) { // Start defining the url. $url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']); // Check for a trailing slash. if ((substr($url, -1) == '/') OR (substr($url, -1) =='\\')) { $url = substr($urll, 0, -1); // Chop off the slash. } $url .= '/index.php'; // Add the page. header ("Location: $url"); exit(); // Quit the script. } // Set the page title and include the HTML header. $page_title = 'Logged In!'; include ('./includes/header.html'); // Print a customised message. echo "<h1>Logged In!</h1> <p>You are now logged in, {$_SESSION['first_name']}!</p> <p><br /><br /></p>"; include ('./includes/footer.html'); ?> logout.php <?php # Script 9.18 - logout.php // This page lets the user log out. session_name('YourVisitID'); ini_set('session.use_cookies', 0); session_start(); // Access the existing session. // If no cookie is present, redirect the user. if(!isset($_SESSION['user_id'])) { //Start defining the url. $url = "http://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']); // Check for a trailing slash. if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\')) { $url = substr($url, 0, -1); // Chop of the slash. } $url .= '/index.php'; // Add the page. header("Location, $url"); exit(); } else { // Cancell the session. $_SESSION = array(); // Destroy the variables. session_destroy(); // Destroy the session itself. } // Set the page title and include the HTML header. $page_title = 'Logged Out!'; include ('./includes/header.html'); // Print a customised message. echo "<h1>Logged Out!</h1> <p>You are now logged out!</p> <p><br /><br /></p>"; include ('./includes/footer.html'); ?>
-
Hi Larry, I'm Greg and I wrongly addressed some question on the "comments" section of your book. Apologise. At your suggestion I address my questions here. You created and refactor several times the registration, login, logout scripts… however, there is not even one page to serve as example of page for authenticated users. The solution suggested is to check for the presence of a session variable. Will this be safe enough? Should we change the default name for the session or regenerate the session it? Will help to have a nonce system implemented? Will help to encrypt some session variable (with salt) and check for that value? In my opinion such a sample page should have been present, namely: restrict access to a page for authenticated users. I would be interested of what you’re thinking about this subject. I’ve noticed the common way of thinking is to check for a session value like “first name” (not the ID or email as these could provide important information to an attacker). If there is no session value for first name than the user is not logged in. It seems very simple to me. Somebody may easily guess the first name’s session name (could be something like $_SESSION['first_name'] and generate a PHPSID=something and it looks the attacker have got access to the page without being in fact authenticated. In my opinion you should have finished what you’ve started (user authentification module) and create a good script tackling this matter (with session timeout, regenerate session id at minimum). Thank you,Greg