Jump to content

Search the Community

Showing results for tags 'sessions'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


  • Welcome to PHP Freaks
    • Announcements
    • Introductions
  • PHP Coding
    • PHP Coding Help
    • Regex Help
    • Third Party Scripts
    • FAQ/Code Snippet Repository
  • SQL / Database
    • MySQL Help
    • PostgreSQL
    • Microsoft SQL - MSSQL
    • Other RDBMS and SQL dialects
  • Client Side
    • HTML Help
    • CSS Help
    • Javascript Help
    • Other
  • Applications and Frameworks
    • Applications
    • Frameworks
    • Other Libraries
  • Web Server Administration
    • PHP Installation and Configuration
    • Linux
    • Apache HTTP Server
    • Microsoft IIS
    • Other Web Server Software
  • Other
    • Application Design
    • Other Programming Languages
    • Editor Help (PhpStorm, VS Code, etc)
    • Website Critique
    • Beta Test Your Stuff!
  • Freelance, Contracts, Employment, etc.
    • Services Offered
    • Job Offerings
  • General Discussion
    • PHPFreaks.com Website Feedback
    • Miscellaneous

Find results in...

Find results that contain...

Date Created

  • Start


Last Updated

  • Start


Filter by number of...


  • Start





Website URL








Donation Link

  1. Hi Freaks, I'm looking for advice if someones willing to give it. Here's the situation -> I've been working on a project, I started to learn PHP specifically to complete this idea I had. My code has evolved a lot over time as I've started understanding more. Up until today I've been working on it with just the registration functionality, no login. I had my username hardcoded into the $user_obj instantiation. I decided I wanted to try to make category subscription functionality and doing that I realized I was better off finishing the login form first so as to get a users subscriptions into a session variable at login. This has brought about the issue of getting an unassigned variable warning from the User class when not logged in. How I made all my other classes was putting a $user in the __construct parameter for each class. I now feel this may have been a rookie error since I'm having problems with error messages especially undefined array keys and variables when there isn't a session started. It's become a bit of a mess. So the advice I'm looking for and hoping to find here is how you folks handle non $_SESSION sessions, when a user is just scrolling the site not logged in. Did I make a mistake requiring $user for each class __construct? should I move the $user parameter to only the methods that require them? Is there a simpler solution that my inexperience causes to elude me? What would you folks do in this situation?
  2. I was just researching how to make a proper logout form, seems easy enough. I noticed that a lot of the examples started with session_start(). Are they saying to start it again before destroying it? I don't understand those examples, also a few examples didn't even destroy it but just unset() everything. I also moved my session_start() from config.php to my login handler, it seemed more logical to me. So 2 questions: What IS the proper way to handle a logout - a) start session again to destroy it right away b) just destroy it c) simply unset everything? My heart chooses b) but I've been wrong many times with things that I thought made sense. Also, the session_start() - config.php or login.php? Is there a performance or security difference I should be considering? Good weekend to you all. TIA for responses.
  3. Hey guys, I wanted to share something with everyone. I hope this is helpful. This is basically a native solution to easily store PHP session data in a MySQL database. Session variables contain data that is saved for a specific user by associating the user with a unique identity. Typically, PHP would store session variables in a local file system on the server by default. While this may be acceptable to many people who are running small to moderate PHP applications, some larger applications that require load balancing would need to be run on multiple servers with a load balancer. In such cases, each server running PHP would need a way to ensure that sessions continue to work properly. One common way to achieve this is to override where PHP opens, reads, writes, and destroys the session variables so that it can perform these operations on a table inside of a MySQL database. When this is performed, the web application can gain advantages such as session management, session logging, and session interactions. I have provided my source code for your reference here: https://github.com/dominicklee/PHP-MySQL-Sessions Hope this helps someone out!
  4. Hi all ! I have an index file which begins as <?php error_reporting(E_ALL); define('INCLUDE_CHECK',true); require_once 'fran_load.php'; session_start(); // works fine with session_start() //sess_start(); // was working fine earlier but is now problematic header("Content-Security-Policy-Report-Only: default-src 'self' img-src 'self' data: https://www.google.com/ https://ajax.googleapis.com/ https://www.gstatic.com/ http://localhost/xampp/franchisee/; report-uri http://localhost/xampp/franchisee/reports/reportcspviolation.php"); // mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); $mysqliDriver = new mysqli_driver(); $mysqliDriver->report_mode = MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT; $timezone = "Asia/Calcutta"; if(function_exists('date_default_timezone_set')) date_default_timezone_set($timezone); // set_exception_handler('exception_handler'); . . . and an email activation request page.verifymail.php which begins as <?php error_reporting(E_ALL); session_start(); header("Content-Security-Policy-Report-Only content=default-src 'self' https://www.google.com/recaptcha/ https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/"); define('INCLUDE_CHECK',true); require_once 'fran_load.php'; /* echo "<pre>"; echo $_SESSION['user_token']; echo "</pre>"; exit(); */ $message = ''; $terminate = false; . . . sess_start() is function sess_start() { $session_name = 'sec_session_id'; // Set a custom session name $secure = false; // Set to true if using https. $httponly = true; // This stops javascript being able to access the session id. ini_set('session.use_only_cookies', 1); // Forces sessions to only use cookies. $cookieParams = session_get_cookie_params(); // Gets current cookies params. session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly); // 0, /, ''. session_name($session_name); // Sets the session name to the one set above. session_start(); // Start the php session } Earlier all seemed to work well, but suddenly there is an issue. On submitting the form with action = "verifymail.php" which sends from the index.php to verifymail.php, i find that the $_SESSION variable is blank, thereby not maintaining the session on that page. I am setting some session variables in the form before it is submitted. I commented out sess_start() on index.php and simply used session_start() and all seems to work fine. I would like to use sess_start, since I am setting the cookie timeout and other values therein, if I can. Please can someone suggest why this is happening and how it can be overcome to use sess_start(). Thanks all.
  5. I'm editing the Woocommerce e-mail files, and have got a session working. When it's echoed on the e-mail it appears as expected - "1 Day Health & Safety Awareness Chelmsford". However the if statement is not working. This is shown below, can anyone tell me where I'm going wrong? if (strpos($_SESSION['ahsname'], 'safety awareness') !== false) { // This is what I want to happen, the session should (and does) contain the string shown above //include( get_template_directory() . '/instructions/chelmsford-hsa-ahs.html'); echo "YES"; }else{ // This should not happen but it does! echo "NO "; echo $_SESSION['ahsname']; // the session is echoed with the bit I'm checking for included as mentioned above }
  6. So I have a code that is suppose to save form sessions and then redirect to another website. It does redirect but the sessions are never saved when I go back to my site. And yes, I do have session_start() at the very top of the page. And also, the sessions do get saved on locahost server but not live server. Do you know why this is happening? Here's the code example. if(isset($_POST['submit'])) { $name = trim($_POST['name']); $email = trim($_POST['email']); $_SESSION['name'] = $name; $_SESSION['email'] = $email; $errors = array(); $db->beginTransaction(); if(empty($name)) { $errors[] = 'Name is required.'; } if(empty($email)) { $errors[] = 'Email is required.'; } if(empty($errors)) { $db->commit(); $new_url = 'https://www.google.ca/'; ?> <script> window.location.href = '<?php echo $new_url; ?>'; </script> <?php exit(); } else { $db->rollBack(); } }
  7. Hi, The 'admin' section of my website stopped working a couple of months ago and I'm just trying to fix it - I was getting an error about Session_Register being deprecated and I'm now trying to knife and fork my way around it with results from various google searches. I'm an advanced SQL user but only occasionally dabble with PHP so any help would be appreciated. So, basic set up, login page checks credentials against the DB, a session cookie is set and you're let into the admin area - my script is looping me back to the login page as my !isset is true.....because I can't figure out how to set it with the new functions! This is the login include..... <?php $host="database.lcn.com"; // Host name $username="blahblah"; // Mysql username $password="blahblah"; // Mysql password $db_name="blahblah_db"; // Database name $tbl_name="users"; // Table name // Connect to server and select databse. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); // username and password sent from form $myusername=$_POST['username']; $mypassword= md5($_POST['pass']); // To protect MySQL injection (more detail about MySQL injection) $myusername = stripslashes($myusername); $mypassword = stripslashes($mypassword); $myusername = mysql_real_escape_string($myusername); $mypassword = mysql_real_escape_string($mypassword); $sql="SELECT * FROM users WHERE is_obv = '1' and username='$myusername' and password='$mypassword'"; $result=mysql_query($sql); // Mysql_num_row is counting table row $count=mysql_num_rows($result); // If result matched $myusername and $mypassword, table row must be 1 row if($count==1){ // Register $myusername, $mypassword and redirect to file "login_success.php" $_SESSION['username'] = $myusername; $_SESSION['pass'] = $mypassword; header("location:../admin"); } else { header("location:http://www.web.co.uk/ooops"); } ?> and this is the 'login_success' include that I include on each protected page.... <? session_start(); if(!isset($_SESSION['username'])){ header("location:http://www.web.co.uk/login"); } ?> Darren
  8. Hi, I have created a webpage that so far was working using SESSIONS. As soon as the user successfully logs in, i save some variables inside a SESSION array and pass them to the mainpage.php script (or any other script that needs these variables). Now i want to implement "REMEMBER ME" feature. I know that i need to store the variables i want into a COOKIE and then access the cookie to get the variables i want. How do i restructure my code now? In case of not selecting REMEMBER ME: I check to see if a SESSION is set and i use only the SESSION variables? In case of selecting REMEMBER ME: I check to see if a cookie is set and then retrieve the variables from COOKIE array? If thats the case i will need to check every script to check this? Is there an easier way to configure it? Regards, Chris
  9. I've got a session $_SESSION['product'.$i.''] that I am trying to echo out. The auto increment on it is working, the $i is auto incremented. So if I do: $i = $_SESSION['count']; echo $_SESSION['product'.$i.'']; echo " ("; echo $_SESSION['count']; echo ") "; It will come up as "Ham Pizza (4)" if it is the 4th time I have done the process and so on. If I echo the sessions out like below: echo $_SESSION['product1']; echo $_SESSION['product2']; echo $_SESSION['product3']; It will come out with the associated product names in the order I done them, eg: Ham PizzaMargheritaBBQ Pizza What I want to know is how to echo them all out at the same time. This is so a user can see what is in their cart, and when I get to it, the checkout too. Any help please?
  10. Hi, I've been going out of my mid for almost a week now trying to figure out how to make this work... I want multiple users to have their own individual usernames and passwords and be able to log in and view certain pages that non-registered guests can't see. I've set up my databases and usernames and passwords. I've actually gotten my login code to work now and then, but in trying to get sessions to work and not allow just anyone to manually type in the addresses of certain pages I've managed to mess that up and it doesn't work now either. I've been to MANY different sites and used examples but just can't get the login to work properly nor figure out how to get the sessions to check for a logged in user. My code so far...I've taken out my real password login,php <?php $connection = mysql_connect('localhost', 'root', 'mypassword'); if (!$connection){ die("Database Connection Failed" . mysql_error()); } $select_db = mysql_select_db('login'); if (!$select_db){ die("Database Selection Failed" . mysql_error()); } if (isset($_POST['username']) and isset($_POST['password'])){ $username = $_POST['username']; $password = $_POST['password']; $username = stripslashes($username); $password = stripslashes($password); $username = mysql_real_escape_string($username); $password = mysql_real_escape_string($password); $query = mysql_query("select * from members where password='$password' AND username='$username'", $connection); $result=mysql_query($sql); $count=mysql_num_rows($result); if($count==1){ session_register("username"); session_register("password"); $_SESSION["authorized"] = true; header("location:membersarea.php"); } else header ("Location: login.html"); } ?> And this is what I put at the top of each secured page... membersarea.php <?php session_start(); if ($_SESSION["authorized"] = true) { } else { header("Location: login.html"); } ?> Thanks in advance!
  11. Hi, I have my login system working fine with sessions. Now I want to use access levels. So if user 1 with access level 1 logs in, he redirects to profile.php. If user 2 with access level 2 logs in, he redirects to main_stats.php. Here is what I have so far for my login.php, however it is not reading the $user_id nor the $access_id: http://codepad.viper-7.com/Ck0Tsr Wondering if anyone can help?
  12. Hello users: I am exploring the delightful world of PHP for web applications. I am in the stage where I need to use SESSIONS and COOKIES and MYSQL for a user/membership/profile structure. I understand most of the grammar behind PHP and am excited to apply this in application. I am searching for recommendations and comments about using: 1. COOKIES 2. SESSIONS 3. MYSQL/SQL Almost every website has an authentication mechanism, profile, and use information. My website required this similar structure, but I have been having some problems completing all of the technical steps for production. If anyone has code samples or places where I can review code on this topic, that would be wonderful. I am specifically searching for more advanced topics in these area for general robustness. Please kindly send me a message or respond to this post. Regards, Diamond
  13. Hi all, I'm trying to build a simple shopping cart, there are only 8 products and I want to save the quantity value into a section for each product (product1, product2, etc). I'm having a problem where the I can't get the session value to increase by one if the same item is added to the cart again. Here is the code I have so far, am I missing something or is there a php setting that would cause this not to work. <?php session_start(); // setup if(!isset($_SESSION['product1'])) $_SESSION['product1'] = 0; if(!isset($_SESSION['product2'])) $_SESSION['product2'] = 0; if(!isset($_SESSION['product3'])) $_SESSION['product3'] = 0; if(!isset($_SESSION['product4'])) $_SESSION['product4'] = 0; if(!isset($_SESSION['product5'])) $_SESSION['product5'] = 0; if(!isset($_SESSION['product6'])) $_SESSION['product6'] = 0; if(!isset($_SESSION['product7'])) $_SESSION['product7'] = 0; if(!isset($_SESSION['product8'])) $_SESSION['product8'] = 0; // add product if(mysql_escape_string($_GET['add']) != '') { $addItem = mysql_escape_string($_GET['add']); $_SESSION["product$addItem"] = $_SESSION["product$addItem"] + 1; } echo "product$addItem = ".$_SESSION["product$addItem"]; ?> Thanks!
  14. Hi! I have read like crazy to find a tutorial on a login page without My_SQL. Anyway I am working on a easy login/logged out page with sessions. Here is the login page with tree users in an array. The things that I need some hints to solve is, when clicking on login the error message don't show. Instead the script goes to the logged in page right away. And when you write the wrong password you get loged in anyway. I am not sure how or if it's possible to write a varible to a file this way. But I tried and recived a parse error with the txt varible. When searching for topics I get more confused with the My_SQL varibles. I am near a breaking point at cracking the first step on PHP, but need some advice. <?php $page_title = 'Logged in'; //Dynamic title include('C:/wamp/www/PHP/includes/header.html'); ?> <?php session_start(); //A array for the sites users with passwords $users = array( 'Dexter'=>'meow1', 'Garfield'=>'meow2', 'Miro'=>'meow3' ); //A handle to save the varible users to file on a new line from the last entry $handle = fopen("newusers.txt, \n\r") $txt = $users; fclose($handle); if(isset($_GET['logout'])) { $_SESSION['username'] = ''; header('Location: ' . $_SERVER['PHP_SELF']); } if(isset($_POST['username'])) { if($users[$_POST['username']] == $_POST['password']) { $_SESSION['username'] = $_POST['username']; }else { echo "Something went wrong, Please try again"; } } ?> <?php echo "<h3>Login</h3>"; echo "<br />"; ?> <!--A legend form to login--> <fieldset><legend>Fill in your username and password</legend> <form name="login" action="777log.php" method="post"> Username: <br /> <input type="text" name="username" value="" /><br /> Password: <br /> <input type="password" name="password" value="" /><br /> <br /> <input type="submit" name="submit" value="Login" /> </fieldset> </form> <?php //Footer include file include('C:/wamp/www/PHP/includes/footer.html'); ?> The logged in page <?php //Header $page_title = 'Reading a file'; include('C:/wamp/www/PHP/includes/header.html'); ?> <?php session_start(); //Use an array forthe sites users $users = array( 'Dexter'=>'meow1', 'Garfield'=>'meow2', 'Miro'=>'meow3' ); // if(isset($_GET['logout'])) { $_SESSION['username'] = ''; echo "You are now loged out"; //The user is loged out and returned to the login page header('Location: ' . $_SERVER['PHP_SELF']); } if(isset($_POST['username'])) { //Something goes wrong here when login without any boxes filled if($users[$_POST['username']] == $_POST['password']) { $_SESSION['username'] = $_POST['username']; }else { echo "Something went wrong, Please try again"; $redirect = "Location: 777.php"; } } ?> <?php if($_SESSION['username']): ?> <p><h2>Welcome <?=$_SESSION['username']?></h2></p> <p align="right"><a href="777.php">Logga ut</a></p><?php endif; ?> <p>Today Ben&Jerrys Chunky Monkey is my favorite!</p> <?php //Footer include('C:/wamp/www/PHP/includes/footer.html'); ?>
  15. Newb here. My form works with sessions and the video loads etc, data submits, etc. all that is good. But i've gotten lost in the complexity of the build it seems and my html has become malformed I think. As a result each submission or page reload inserts another form inside the form inside the form etc etc etc. It some sort of weird looping madness or something. I'm very new to classes and how they work and i can't find where the madness is coming from. To duplicate the error, fill out the form and submit (the video won't play in firefox so use safari or chrome to test). I've been trying to resolve this for hours - i'm very lost in the complexity. <?php # '../' == sub-folder. use './' == root require '../inc_0700/config_inc.php'; #provides configuration, pathing, error handling, db credentials echo '<link rel="stylesheet" type="text/css" href="w05c09_gojiraIncidentReport.css">'; //END CONFIG AREA ---------------------------------------------------------- # Read the value of 'action' whether it is passed via $_POST or $_GET with $_REQUEST if(isset($_REQUEST['act'])){$myAction = (trim($_REQUEST['act']));}else{$myAction = "";} switch ($myAction){//check 'act' for type of process case "display": # 2)Display user's name! showObjects(); break; case "clear": # 3 Clear the session data clearObjects(); showForm(); break; default: # 1)Ask user to enter their name showForm(); } function showForm(){# shows form so user can enter their name. Initial scenario get_header(); #defaults to header_inc.php echo '<script type="text/javascript" src="' . VIRTUAL_PATH . 'include/util.js"></script> <script type="text/javascript"> function checkForm(thisForm){//check form data for valid info if(empty(thisForm.YourName,"Please Enter Your Name")){return false;} return true;//if all is passed, submit! } </script> <video id="bgVideo" preload="auto" autoplay="true" loop="loop" muted="muted" volume="0" poster="_bgGrfxs/bg_vidGlobe.jpg"> <source src="_bgVideo/bg_vidLoop.mp4" type="video/mp4"/> <source src="_bgVideo/bg_vidLoop.ogv" type="video/ogg"/> </video> <!-- This image stretches exactly to the browser width/height and lies behind the video--> <div id="bodyDummy"> <!-- <h3 align="center"">' . smartTitle() . '</h3>--> <br /> <br /> <br /> <br /> <br /> <br /> <form align="center" action="' . THIS_PAGE . '" method="post" onsubmit="return checkForm(this);"> <img width="10%" src="img_logo-panPacificDefenseCenter.png" alt="Kaiju Incident Reporter"/> <br /> <h2 style="color: #ff6d26;">Incident Report Form</h2> <br /> <!-- incWho? --> <br /> <b>Reporting Officer ID:</b><br /> <input type="text" name="incWho" placeholder="Please enter your full name here" /> <br /> <br /> <!-- incWhat --> <b><a id="orange" href="http://godzilla.wikia.com/wiki/Main_Page">Massive Unidentified Terrestrial Organism encountered:</a></b><br /> <select type="text" name="incWhat" data-placeholder="Select Incident Location..." class="chzn-select" multiple style="width:354px;" tabindex="40"> '; include 'ddlist-Kaiju.php'; echo '</select> <br /> <br /> <!-- incWhen = date of incident --> <b>Date of Incident:</b><br /> <input type="text" name="incWhen" placeholder="Please enter your full name here" /> <br /> <br /> <!-- incWhere --> <b>Incident Location:</b><br /> <select type="text" name="incWhere" data-placeholder="Select Incident Location..." multiple style="width:354px;" tabindex="111"> '; include 'ddlist-countriesInternational.php'; echo '</select> <br /> <br /> <!-- incWhy --> <b>Incident notes:</b><br /> <textarea name="incWhy" cols="54" rows="3" placeholder="Please enter any details you can recall of the incident - if incident is still occurring run" ></textarea> <br /> <br /> <!-- incScale --> <b>Rate the severity of the incident (0 to 5):</b> <br /> <br /> <input type="range" data-show-value="true" data-hightlight="true" data-popup-enabled="true" name="incScale" min="0" max="5" value="0" onchange="updateTextInput(this.value);"> <br /> <br /> <input id="go" type="submit" value="Go!"> </p> <input type="hidden" name="act" value="display" /> </form> <br /> <p style="#444"><i>Once you have completed your incident report, Run! For the love god man run, run for the hills and be safe!</i></p> '; get_footer(); #defaults to footer_inc.php echo '</div><!-- END bodyDummy -->'; } function showObjects() {#form submits here we show entered name //dumpDie($_POST); //if the session is not started, that could be a problem get_header(); #defaults to footer_inc.php if(!isset($_SESSION)){session_start();} echo "<br />"; if(!isset($_SESSION['kSession'])) {//if no session exists, create it $_SESSION['kSession']= array(); } //we need to add post data here $_SESSION['kSession'] [] = new incReport($_POST['incWho'], $_POST['incWhat'], $_POST['incWhen'], $_POST['incWhere'], $_POST['incWhy'], $_POST['incScale']); $totalScale = 0; foreach($_SESSION['kSession'] as $incReport)//loop thru each array item { echo $incReport; $totalScale += $incReport->incScale; } $totalReports = count($_SESSION['kSession']); $aveRating = $totalScale/$totalReports; echo '<div style="margin: auto; padding:0 10px; background-color:#ff6d26;width: 300px";><p style="color:white;">Average Incident Severity:</p> <h1 style="color:white;";>'; echo "$aveRating"; echo'</h1></div>'; if ($aveRating == 5){ echo '<p>Five: We suggest you make peace with this, your final moment.. enjoy the sunset before that giant foot comes down on you.</p>';} if ($aveRating == 4){ echo '<p>Four: The end is near, run man run, she isn\'t worth it, save yourse<p>lf.</p>';} if ($aveRating == 3){ echo '<p>Three: And your still there? Seriously?</p>';} if ($aveRating == 2){ echo '<p>Two: Take a picture, it will last longer. Now. Run for the hills!</p>';} if ($aveRating == 1){ echo '<p>One: Have you considered running?</p>';} if ($aveRating == 0){ echo '<p>Zero: This would be a good time to consider moving to a safer vantage point.</p></form></div><!--end dummy-->';} //get_footer(); #defaults to footer_inc.php //------end of work area-------// get_header(); #defaults to footer_inc.php if(!isset($_POST['incWho']) || $_POST['incWhat'] == ''){//data must be sent feedback("No form data submitted"); #will feedback to submitting page via session variable myRedirect(THIS_PAGE); } if(preg_match('[^A-Za-z0-9]', $_POST['incWho'])){//data must be alphanumeric only feedback("Only letters & numbers are allowed."); #will feedback to submitting page via session variable myRedirect(THIS_PAGE); } $myName = strip_tags($_POST['incWho']);# here's where we can strip out unwanted data } function clearObjects(){ //echo "clearing objects here"; if(!isset($_SESSION)){session_start();} unset($_SESSION['kSession']); feedback("session cleared"); } class incReport{ public $incWho = ""; public $incWhat = ""; public $incWhen = ""; public $incWhere = ""; public $incWhy = ""; public $incScale = ""; function __construct($incWho, $incWhat, $incWhen, $incWhere, $incWhy, $incScale){ $this->incWho=$incWho; $this->incWhat=$incWhat; $this->incWhen=$incWhen; $this->incWhere=$incWhere; $this->incWhy=$incWhy; $this->incScale=$incScale; } function __toString(){ static $kID = 1;//kaiju incident number $myReturn = '<video id="bgVideo" preload="auto" autoplay="true" loop="loop" muted="muted" volume="0" poster="_bgGrfxs/bg_vidGlobe.jpg"> <source src="_bgVideo/bg_vidLoop.mp4" type="video/mp4"/> <source src="_bgVideo/bg_vidLoop.ogv" type="video/ogg"/> </video> <div id="bodyDummy"> <br /> <br /> <br /> <br /> <br /> <br /> <form><p> Incident ID: kID00' . $kID ; //works $kID++; //iterate report $myReturn .= ' | Incident Reported by: ' . $this->incWho . ' ' ;//works $myReturn .= ' | Massive Terrestial Organsim Observed: ' . $this->incWhat . ' ' ;//shows where... $myReturn .= ' | Date of Incident: ' . $this->incWhen . ' ' ; //works $myReturn .= ' | Incident Location: ' . $this->incWhere . ' '; //shows what $myReturn .= ' | Incident Details: ' . $this->incWhy. ' '; // working $myReturn .= ' | Incident Severity: ' . $this->incScale . '</p> <p align="center"><a href="' . THIS_PAGE . '">File Report, then Run!</a> | <a href="' . THIS_PAGE . '?act=clear">Reset</a></p> ' ; return $myReturn; } }
  16. I was wondering what most of you guys use to prevent against SQL injection? This is what I am currently using. function transform_HTML($string, $length = NULL){ $string = trim($string); $string = utf8_decode($string); $string = htmlentities($string, ENT_NOQUOTES); $string = str_replace("\"", """, $string); $string = str_replace("#", "#", $string); $string = str_replace("$", "$", $string); $string = str_replace("%", "%", $string); $string = str_replace("&", "&", $string); $string = str_replace("'", "'", $string); $string = str_replace("(", "(", $string); $string = str_replace(")", ")", $string); $string = str_replace("*", "*", $string); $string = str_replace("+", "+", $string); $string = str_replace(",", ",", $string); $string = str_replace("-", "-", $string); $string = str_replace("/", "/", $string); $string = str_replace(":", ":", $string); $string = str_replace(";", ";", $string); $string = str_replace("<", "<", $string); $string = str_replace("=", "=", $string); $string = str_replace(">", ">", $string); $string = str_replace("?", "?", $string); $string = str_replace("@", "@", $string); $string = str_replace("[", "[", $string); $string = str_replace("]", "]", $string); $string = str_replace("^", "^", $string); $string = str_replace("_", "_", $string); $string = str_replace("`", "`", $string); $string = str_replace("{", "{", $string); $string = str_replace("|", "|", $string); $string = str_replace("}", "}", $string); $string = str_replace("~", "~", $string); $length = intval($length); if ($length > 0){ $string = substr($string, 0, $length); } return $string; } Which then gets called by: if ($action == 'login'){ // Login Action $_SESSION['loginerror'] = FALSE; $myusername = transform_HTML($_POST['login-username'], 21); $mypassword = transform_HTML($_POST['login-password'], 21); $sql="SELECT * FROM $table[users] WHERE username='$myusername' and password=MD5('$mypassword')"; $result=mysqli_query($db, $sql); // Mysql_num_row is counting table row $count=mysqli_num_rows($result); // If result matched $myusername and $mypassword, table row must be 1 row if($count==1){ // Login Stuff } Is there a more efficient way, or more secure way of doing this?
  17. Hi, I'm looking for help with my sessions and table data So far I have 2 tables, one named: userlogin which contains log in information listed by 'user_id' my next table is called userinfo which at the moment just contains user name and address, again listed by 'user_id' Currently I have a log in page, and a home page. The log in page uses the information from the userlogin table to verify that the user has an account and they have entered the correct information. Now this is were it gets tricky, (for me at least) as on this homepage i'm trying to display the information from the userinfo table which relates to the user_id from the userlogin table, relating to their unique information. The purpose of this is to be able to display information for my clients, all without having hundreds of separate pages and having only one page, which displays the information based upon who has logged in. Here is my loginpage code // Use session variable on this page. This function must put on the top of page. session_start(); $_SESSION['userName'] = 'Root'; ////// Login Section. $Login=$_POST['Login']; if($Login){ // If clicked on Login button. $username=$_POST['username']; $password=$_POST['password']; // Encrypt password with md5() function. // Connect database. //connect $con = mysql_connect("*****","*****","*****"); if (!$con) { die('Could not connect: ' . mysql_error()); } //datebase mysql_select_db("*****, $con); // Check matching of username and password. $result=mysql_query("select * from userlogin where username='$username' and password='$password'"); if(mysql_num_rows($result)!='0'){ // If match. session_register("username"); // Craete session username. header("location:home.php"); // Re-direct to main.php exit; }else{ // If not match. $message="--- Incorrect Username or Password ---"; } } // End Login authorize check. ?> and here is my homepage code. <?php session_start(); if(isset($_SESSION['userName'])) ?> // Connect database. //connect $con = mysql_connect("****","*****","******"); if (!$con) { die('Could not connect: ' . mysql_error()); } //datebase mysql_select_db("*****", $con); //select $user_id = $_GET['user_id']; $result = mysql_query("SELECT userinfo.user_id, userlogin.user_id FROM userinfo INNER JOIN userlogin ON userinfo.user_id=userlogin=user_id"); while($row = mysql_fetch_array($result)) { echo $row['name'] . ' ' ; echo $row['address'] . ' '; } ?> Sorry if this seems confusing, as unfortunately my php skills aren't brilliant, but basically i'm just looking for help creating a log in feature, which then links the user the their profile, with their data present. Thanks in advance!
  18. When I try to login with my username and password, nothing happens. I only get an error from this line in login.php: "if ($_POST['action']=='logout') {" So what could be wrong? Login.php: <?php session_start(); /*Om användaren har tryck på loggut-knappen så verkställs sessionen.*/ if ($_POST['action']=='logout') { session_unset(); } if (! isset($_SESSION['username'])) { if (isset($_POST['username'])) { $username = addslashes($_POST['username']); $pswd = addslashes($_POST['pswd']); /*Här försöker vi koppla upp mot databasen*/ mysql_connect('localhost', 'root', '') or die("Kan inte koppla upp mot db-servern"); mysql_select_db("db_film") or die("Kan inte koppla upp mot db"); /*Här hämtas namn, användarnamn och lösenord från tabellen users i databasen. Om de inskrivna värdena stämmer överens med uppgifterna i databasen så skickas vi till publishpost.php. */ $query = "SELECT username FROM users WHERE username='$username' AND pswd=md5('$pswd')"; echo "<pre>$query</pre>"; $result = mysql_query($query); if (mysql_num_rows($result) == 1){ // $_SESSION['firstname'] = mysql_result($result,0,"firstname"); $_SESSION['username'] = mysql_result($result,0,"username"); $user = $_POST['username']; $salt = "somestring"; $_SESSION['token'] = md5($salt . $user . $salt); $token = $_SESSION['token']; header("location: publishpost.php"); } /*Om uppgifterna inte stämmer så stannar användaren kvar på login.php och en text skrivs ut som talar om att man inte har blivit inloggad.*/ else { $username = $_SESSION['username']; header("location: login.php"); echo ("Du är inte inloggad"); } } } ?> Checklogin.php: <?php /* En session för att logga in */ session_start(); $user = $_SESSION['username']; $salt = "somestring"; $token = md5($salt . $user . $salt); if (isset($_SESSION['name']) AND $_SESSION['token'] == $token) { $name = $_SESSION['name']; } else { header("location: login.php"); } ?>
  19. Hello. I've gotten my self really confused with server end checks for users being logged in. I create a session in PHP by using a straight forward ajax request and check the database against the user & pass sent to the server. I then set a session like this: $_SESSION['uid'] = $row['uid']; But i want to check this session in NodeJS aswell so i don't have to keep validating the user when they send data on a socket. The script i have is like this: socket.on('sendMessage', function(data,callBack){ var userID = //assign $_SESSION['uid'], possible? if(!userID){ console.log('User not logged in!'); } else { var message = sanitize(data['message']).escape(); var query = connection.query('SELECT name FROM users WHERE uid = ?', [userID], function(err,results){ if(err){ console.log('Query Error: '+err); } else if(results.length == 1){ var username = results[0].name; console.log(username+' sent a message!'); } }); }); How do i use the session in this situation - i can't work out how to do it =/ Please help, really confused!
  20. alright so I have muliple different files and I think I know where my error is. I want to have my page set so that when a client logs in they they set the logged variable to 1 and not 0. So far whenever I log in the variable is staying at 0 there must be an issue. here is the global.php file <?php include_once("connect.php"); session_start(); if(isset($_SESSION['username'])) { header("Location: index.php"); //checking if sessions are set. if(isset($_SESSION['username'])){ $session_username = $_SESSION['username']; $session_pass = $_SESSION['pass']; $session_id = $_SESSION['id']; //check if the member exists $query = mysql_query("SELECT * FROM clients WHERE id='$session_id' AND password='$session_pass'LIMIT 1") or die("Could not check member"); $count_count = mysql_num_rows($query); if($count_count > 0){ //logged in stuff here $logged = 1; }else{ header("Location: logout.php"); exit(); } }else if(isset($_COOKIE['id_cookie'])){ $session_id = $_COOKIE['id_cookie']; $sessions_pass = $_COOKIE['pass_cookie']; //check if the member exists $query = mysql_query("SELECT * FROM clients WHERE id='$session_id' AND password='$session_pass'LIMIT 1") or die("Could not check member"); $count_count = mysql_num_rows($query); if($count_count > 0){ while($row= mysql_fetch_array($query)){ $session_username = $row['username']; } //create sessions $_SESSION['username']=$session_username; $_SESSION['id']=$session_id; $_SESSION['pass']=$session_pass; //logged in stuff here $logged = 1; }else{ header("Location: logout.php"); exit(); } }else{ //if the user is not logged in $logged = 0; } } ?> here is the login.php script <?php include_once("scripts/global.php"); if(isset($_POST['email'])){ $email = $_POST['email']; $pass = $_POST['pass']; $remember = $_POST['remember']; //error handeling if((!$email)||(!$pass)){ $message = 'Please insert both fields'; }else{ // secure the data $email = mysql_real_escape_string($email); $pass = sha1($pass); $query = mysql_query("SELECT * FROM clients WHERE email='$email' AND password='$pass' LIMIT 1" ) or die("Could not check member"); $count_query = mysql_num_rows($query); if($count_query == 0){ $message = 'The information you entered is incorrect'; }else{ //start session $_SESSION['pass'] = $pass; while($row = mysql_fetch_array($query)){ $username = $_row['username']; $id = $row['id']; } $_SESSION['username'] = $username; $_SESSION['id'] = $id; if($remember == "yes"){ //create cookies setcookie("id_cookie",$id,time()+60*60*24*100,"/"); setcookie("pass_cookie",$pass,time()+60*60*24*100,"/"); } header("Location: home.php"); } } } ?>
  21. alright, this is a big screwy problem that I am trying to fix. The first thing is that I have a global php document loading into all php documents. The code is as follows: <?php session_start(); if(isset($_SESSION['username'])) { header("Location: index.php"); exit(); include_once("connect.php"); //checking if sessions are set. if(isset($_SESSION['username'])){ $session_username = $_SESSION['username']; $session_pass = $_SESSION['pass']; $session_id = $_SESSION['id']; //check if the member exists $query = mysql_query("SELECT * FROM clients WHERE id='$session_id' AND password='$session_pass'LIMIT 1") or die("Could not check member"); $count_count = mysql_num_rows($query); if($count_count > 0){ //logged in stuff here $logged = 1; }else{ header("Location: logout.php"); exit(); } }else if(isset($_COOKIE['id_cookie'])){ $session_id = $_COOKIE['id_cookie']; $sessions_pass = $_COOKIE['pass_cookie']; //check if the member exists $query = mysql_query("SELECT * FROM clients WHERE id='$session_id' AND password='$session_pass'LIMIT 1") or die("Could not check member"); $count_count = mysql_num_rows($query); if($count_count > 0){ while($row= mysql_fetch_array($query)){ $session_username = $row['username']; } //create sessions $_SESSION['username']=$session_username; $_SESSION['id']=$session_id; $_SESSION['pass']=$session_pass; //logged in stuff here $logged = 1; }else{ header("Location: logout.php"); exit(); } }else{ //if the user is not logged in $logged = 0; } } ?> Now this page is loaded into my log-in page here: <?php include_once("scripts/global.php"); if(isset($_POST['email'])){ $email = $_POST['email']; $pass = $_POST['pass']; $remember = $_POST['remember']; //error handeling if((!$email)||(!$pass)){ $message = 'Please insert both fields'; }else{ // secure the data $email = mysql_real_escape_string($email); $pass = sha1($pass); $query = mysql_query("SELECT * FROM clients WHERE email='$email' AND password='$pass' LIMIT 1" ) or die("Could not check member"); $count_query = mysql_num_rows($query); if($count_query == 0){ $message = 'The information you entered is incorrect'; }else{ //start session $_SESSION['pass'] = $pass; while($row = mysql_fetch_array($query)){ $username = $_row['username']; $id = $row['id']; } $_SESSION['username'] = $username; $_SESSION['id'] = $id; if($remember == "yes"){ //create cookies setcookie("id_cookie",$id,time()+60*60*24*100,"/"); setcookie("pass_cookie",$pass,time()+60*60*24*100,"/"); } header("Location: home.php"); } } } ?> Now the first error is that I get is: Warning: mysql_real_escape_string(): No such file or directory in /misc/12/000/267/023/7/login.php on line 13 Warning: mysql_real_escape_string(): A link to the server could not be established in /misc/12/000/267/023/7/login.php on line 13 Warning: mysql_query(): No such file or directory in /misc/12/000/267/023/7/login.php on line 15 Warning: mysql_query(): A link to the server could not be established in /misc/12/000/267/023/7/login.php on line 15 Could not check member Now in result when I dont have global.php loaded and have connect.php loaded.- logging in works but there is no session set and the information from their row in the table is not available. Thanks
  22. Ok , so I am developing a web application that's going to let people connect through Facebook , Twitter or Google plus ... Now , the api code is located in three respective different folders , facebook folder for the facebook api , twitter folder for twitter and google_plus.. The thing is , I'm trying to make people be able to log through Twitter and access the application .. and give them the option to also logon through Facebook after logging through Twitter and keep the twitter-based data after they logged through Facebook , I would basically like them to be able to view both their twitter and facebook feeds mixed together at the same time ... I tried to implement sessions , but it looks like if they log through Facebook after logging through twitter first , the Twitter session variable content become NULL and only facebook session data is displayed .. How can I manipulate the sessions so that twitter data can be kept when a user log through facebook as well ? Below is what I did to test the data .. <?php session_set_cookie_params('3600'); session_start(); require('../database/connection.php'); require_once('../twitter/twitteroauth/twitteroauth.php'); require_once('../twitter/config.php'); include_once '../facebook/fbmain.php'; // Here I'll test the $_SESSION variable to see if twitter data is kept after a user logs through facebook as well .. but twitter data become NULL instead and the $_SESSION array only show facebook data .. How can I make twitter session data STAY after someone logs through facebook as well ? var_dump($_SESSION); var_dump(session_id()); /* If access tokens are not available redirect to connect page. */ if (empty($_SESSION['facebook_id']) && (empty($_SESSION['access_token']['oauth_token']) || empty($_SESSION['access_token']['oauth_token_secret']))) { header('Location: ./clearsessions.php'); } else { /* Get user access tokens out of the session. */ $access_token = $_SESSION['access_token']; /* Create a TwitterOauth object with consumer/user tokens. */ $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']); /* If method is set change API call made. Test is called by default. */ $content = $connection->get('account/verify_credentials'); $json = json_encode($content); $data = json_decode($json,true); $screen_name = $data["screen_name"]; $name = $data["name"]; $image_url = $data['profile_image_url']; $_SESSION['screen_name'] = $screen_name; $_SESSION['image_url'] = $image_url; $query = "SELECT * FROM Users WHERE username ='$screen_name'"; $result = mysql_query($query); $result_count = mysql_num_rows($result); if($result_count == 0) { $insert = "INSERT INTO Users(username) VALUES('$screen_name')"; $result_insert = mysql_query($insert); } } if(isset($_SESSION['oauth_token']) && isset($_SESSION['oauth_token_secret']) && isset($_SESSION['facebook_id'])){ $user = $_SESSION['facebook_id']; } ?>
  23. **Sessions or Cookies Hi, As the title of the topic says... I'm working on a project and I need to make a login system for an admin panel. And I'm not sure which one to use. Sessions or cookies? And an other question. I managed to make it so the login creates a coockie of the username and IP combined. But I don't know how I can call it. Since Here's my Login code that creates the cookies: class auth { function user_info_check( $username, $password ) { global $db; $sql = " SELECT * FROM users WHERE username = '".$username."'"; if(!$result = $db->query($sql)){ die('There was an error running the query [' . $db->error . ']'); } if ( $result->num_rows < 1 ) die('Account dosen\'t exists'); $row = $result->fetch_assoc(); $pass1 = $row['password']; $user1 = $row['username']; $permission = $row['permission']; if ( $username != $user1 ) { die('Account dosen\'t exists'); } if ( $password != $pass1 ) { die('Wrong Password'); } return array($username,$permission); } function login() { global $username, $password; // Returns the User's Username and Permission $info = $this->user_info_check($username,$password); setcookie($info[0]."-permission", $info[1], time()+3600); setcookie("user-".$info[0], $username, time()+3600); } } The user_info_check() uses the username and password from the login form, to get the requested data, which is the username and permission. But my problem is... if I create the session named "user-Andor" for example, Andor is the username, How can I call it if I don't have the username saved anywhere? Thanks!
  24. Hey guys, No this may very well be a silly question and if it is, I'm certain to have a decent bit of embarrassment, as I'm somewhat of a veteran when it comes to PHP but I've only just started to look for a viable solution to this particular hiccup. Is there a way in the PHP Header file to include "print $_SESSION ['username']", without it causing a syntax error? I'll provide more context by embedding my code! <?php if ((isset($_SESSION['user_id']))&&(!strpos($_SERVER['PHP_SELF'],'logout.php'))) { print '<span> <a href="login/" id="link-login">Log in</a> <span class="pre-login-or">or</span> <a href="register/" id="link-register">Register</a></span>'; } else{ print 'Benvenutti $_SESSION ['username'], al Torneo di Briscola due mila tredici'; }?> That in itself will cause an unexpected T_STRING syntax error... the only option I can see is by employing the use of an iframe and linking the source to a separate PHP document with the "Welcome" text, but I was hoping there was another was to achieve this with the iframe.
  25. Hi guys !! If ever a guys was confused, I am today, having read sessions and security and realizing nothing is secure with sessions. There is no such thing as absolute security in sessions and login scripts. So today I read about about the common types of attacks - especially session fixing. This is what I could make ( I think I must have understood just about 15% of it ) out and I have some questions accordingly which I'll be glad to have sorted by the Gurus here !! 1. Sessions fixation involves there being a Session_ID stored either as cookie, sent as a URL or as a hidden field. The cookie being the most secure yet prone to maximum tampering. ( ironic - that's what the article said). Not withstanding the other hazards, I would like to question what if i designed a login session using only sessions and not involving any cookies or URL or hidden fields, how secure would that be against session fixation? I hope there's nothing stupid about that statement. I just want to know if that prevents session fixation. I think that's all I want to know for now and will come out with other questions as and when I proceed on this issue and read more. Thanks very much.
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.