PHP - Moved: Securing Sessions & Cookies For In-site Third Party App Development
This topic has been moved to Ajax Help.
http://www.phpfreaks.com/forums/index.php?topic=358932.0 Similar TutorialsThis topic has been moved to PHP Freelancing. http://www.phpfreaks.com/forums/index.php?topic=347622.0 This topic has been moved to Apache HTTP Server. http://www.phpfreaks.com/forums/index.php?topic=358740.0 Hey everyone, I am new to PHP and I want to learn how to secure a PHP session properly. I wrote a few lines, but I don't know if it's secure enough. Code: [Select] <?php session_start(); if (isset($_SESSION['exists'])) { if ($agent != $_SERVER['HTTP_USER_AGENT']) { session_unset(); session_destroy(); session_regenerate_id(True); } } else { $_SESSION['exists']=1; $agent=$_SERVER['HTTP_USER_AGENT']; session_regenerate_id(); } ?> Can anybody help me correct or improve my code? Thanks in advance. Hi guys, what I'm struggling to do is 1) Users land on https://www.mysite.com/login.php 2) Users type their email and password 3) POST data submitted to http://www.3rdparty.com/login.php with cURL 4) Users redirected to http://www.3rdparty.com/index.php (logged in). I've been using this simple form to POST directly to the 3rd party site. Code: [Select] <form name="loginform" method="post" target="_blank" action="http://www.3rdparty.com/login.php"> Email <input name="email" type="text"> Password<input name="password" type="password"> <input name="submit" type="submit" id="loginbutton" value="login"></form> This works great. But now I've installed a SSL on my site and I've just realised that using the form above, the data is still POSTed as a plain text because the 3rd party site is not https. So I want to submit the form to my login.php form and let this form take the users to the 3rd party site. So at least the user inputs to my site is encrypted. My new code looks like this. Code: [Select] <form name="loginform" method="post" target="_blank" action="login.php"> Email <input name="email" type="text"> Password<input name="password" type="password"> <input name="submit" type="submit" id="loginbutton" value="login"></form> <?php if(isset($_POST['email'])) $email= $_POST['email']; if(isset($_POST['password'])) $password= $_POST['password']; if(isset($_POST['submit'])) $submit = $_POST['submit']; $Curl_Session = curl_init('http://www.3rdparty.com/login.php'); curl_setopt ($Curl_Session, CURLOPT_POST, 1); curl_setopt ($Curl_Session, CURLOPT_POSTFIELDS, "email=$email&password=$password&submit=$submit"); curl_setopt ($Curl_Session, CURLOPT_FOLLOWLOCATION, 1); $result = curl_exec ($Curl_Session); curl_exec ($Curl_Session); curl_close ($Curl_Session); print $result; ?> What this code is doing now is it's just rendering the www.3rdparty.com's login page (not logged in) on my site. When I type wrong values, it renders www.3rdparty.com's login page with an error message on it. So I think at least the values are being POSTed but it doesn't log me in. All of the cURL codes available out there seem to POST the data and fetch some results back not redirecting the users to another site. My ultimate goal is to POST the form and redirect the users to the 3rd party site's member area as well. I tried header("Location: http://www.3rdparty.com/index.php"); but it just takes user to that page without being logged in. Could anyone give me some hints? Hello , my website uses sessions to check for users if they are logged in, get data and such stuff.. But i want to add cookies in order to make users stay logged in for more time.. I do have a remember me checkbox and a function that tells me if a user is loggedin by checking if session or cookie is set and then it returns a true flag... the problem is that i dont know how to get if he is logged via session or cookies Thanks. I have attached a very simple remember me script. Could someone please have a look at it and tell me if I'm doing it correctly, or what the correct implementation would be to allow users to not use and use the remember me function? I am having a hard time getting sessions and cookies to work as I would expect. I am using codelobster editor/debugger and wampserver. My problem is that when I try to delete a cookie it shows that the cookie is still there and active. <?PHP session_start(); date_default_timezone_set('Asia/Qatar'); // I try to delete the previous cookie which was set setcookie('my_session',"",time()-3600); // here I have a function that sets a cookie log_session("username","password"); session_destroy(); ?> When I check the local variables in the debugger they are still there and not deleted and have the same value. Is my logic wrong or is it my system? I'm creating a login. When a user logs in, they can choose for the website to remember them. If they do, then the login function creates cookies. The function checks the database for the information and then stores it into an array and creates the cookies. HOWEVER when a user doesn't choose for the website to remember them, then I assume I will be using session variables. However, I am not sure how to go about it. Usually, I would create a cookie for the username and the password. Would it be safe to create session variables for the username and password to last for the session and then use these? I'm just confused how to deal with just a session.. Hi, I want to end a session when a registered user is asked to login again but enters the incorrect credentials. I'm destroying the session and taking the user back to the login page, but for some reason when s/he clicks "back" on the browser s/he is able to get back into her/his account. Any ideas? I'm trying to learn the proper workaround to enable Sessions when visitors have their cookies disabled.
When I create a PHP session page with ini_set("session.use_trans_sid", 1) and then disable my browser cookies and view browser source code, I see what I expect: a hidden input appended like this: It seems to work (sessions without cookies!). However, I don't see the long URL query strings that I used to see when I experimented with this 10 years ago, and I don't see the long PHPSESSID value appended to all the page links, and I don't see dozens of session variables appended as hidden form inputs. Rather, I just see the one PHPSESSID hidden input described above. Is this because all the session variables are stored on the server itself, and all the server needs is that one single long PHPSESSID value? Or, am I doing it wrong? :-) Edited April 4, 2019 by StevenOliver Hi guys, I want a PHP Cookie & Session to apply to both the domain and all its subdomains, except one specific subdomain which I never want the same cookies/sessions to apply to. I have the apply too all sorted, just not the exception. Any help is much appreciated. I'm brushing up on Cookies and Sessions. My book says that in order to access the same Session data, you must have Code: [Select] session_start(); on each page that uses the Session data AND the user must have accepted the Session Cookie?! So what do you do if a user has Cookies Turned Off or Declines a Session Cookie?? (I find it hard to believe that Sessions are that "delicate"?!) TomTees I am using the scripts (at the end) on a shared debian server at my web host's remote facility. Hello, On my site I offer the option an option for cookies or sessions on login. If a remember me box is selected, then a cookie will be set. My question is, how do I assign both the $_SESSION['id'] and $_COOKIE['id'] to the same variable? Thanks for the help! I'm very new to PHP and have been working on my site idea for the past couple of weeks and have been working on the basic sign up, logging in, activation and log out. The log out works fine, but when I sign in with a second username, the first user name's information comes up instead. Here's the log out script: <?php session_start(); session_unset(); session_destroy(); setrawcookie('user'); ?> I tried a bunch of other stuff but nothing seems to work. Closing the window and stuff works fine but obviously, that's not the safest method. I need advice on how to handle a php issue. I will try to simply my problem as best as I can. Index.php is used to upload multiple pictures engine.php is called each time for each picture. So if someone uploads 3 pictures engine.php is called 3 times and uploads each picture separately. What I want to be able to do is to track bulk uploads. For example, if someone uploads 10 pictures at once there would be a unique code in my database that I could query and see the results of the 10 pictures that where uploaded. Kinda like a batch. The problem is that I can't seem to create a unique code that it's used to to track batches. I have used cookies in my index.php and set it to a random variable. When my engine.php starts uploading images via POST method, it calls the cookie that was stores in index.php only to see that the value doesn't get passed. I check index.php by using echo $_COOKIE['...']; and a value does get into the cookie, but engine.php can't seem to access the cookie. (I used setcookie) Here's part of the code for the cookies (engine.php): $getmu = $_COOKIE['multiupload']; $insert_image = "INSERT INTO images (owner, dateadded, mimetype, originalfilename, filename, thumbname, filesize, description, originalip, originalwidth, originalheight, lastaccessed, tracker, mutracker) VALUES ($displayID, NOW(), '".preparedata($contenttype)."', '".preparedata($filename)."', '".preparedata($newfilename)."', '".preparedata($ranthumb)."' , '".preparedata($filesize)."', '".preparedata($imgdesc)."', '".preparedata($userip)."', '".$originalwidth."', '".$originalheight."', NOW(), '".preparedata($tracker)."', '".$getmu."')"; if I set $getmu to just any string, it seems to get inserted into the db, so it's not a syntax issue. When I use cookies, nothing gets inputed. I also tried using sessions, but since engine.php is called for each picture upload, the session changes for every picture. Any ideas or advice? I'm kinda stuck on this. The cookies should work, but they don't :/ I am about to attempt to write my first php script from scratch after a year or so of copying and adapting code. I am going to do a registration/login in system and thinking ahead, want to make sure that once someone is logged in, this information is passed from page to page (so they do not have to log in again on each page) and I would also like to provide a 'Remember Me' option. I have had a read up and from what I gather, sessions would be better for showing someone is logged in from page to page and cookies would be the only way to implement a 'Remember Me'. Would this be the best way to approach this or is/are there better ways? Thanks in advance Steve after authenticating username and password,i have a parameter like: $_SESSION['logged']=1 should i be storing this as a cookie?..if yes, then can anyone modify cookie, to have this parameter as "1", and gain access? Hello again, I posted a question earlier about an include issue which I managed to fix but now I am dealing with a completely new error message and unlike before I don't even have a basic Idea of what is going on. The error in question is - Quote An error occurred in script 'C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\IUS\Login\form_process.php' on line 10: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\IUS\Index.php:1) Date/Time: 1-10-2012 16:49:31 the code for form_process.php is as follows Code: [Select] <?php # Script 16.8 - login.php // This is the login page for the site. require_once ('login/config2.inc.php'); // Start output buffering: ob_start(); // Initialize a session: session_start(); if (isset($_POST['submitted'])) { require_once (MYSQL); // Validate the email address: if (!empty($_POST['email'])) { $e = mysqli_real_escape_string ($dbc, $_POST['email']); } else { $e = FALSE; } // Validate the password: if (!empty($_POST['pass'])) { $p = mysqli_real_escape_string ($dbc, $_POST['pass']); } else { $p = FALSE; } if ($e && $p) { // If everything's OK. // Query the database: $q = "SELECT user_id, first_name, user_level FROM users WHERE (email='$e' AND pass=SHA1('$p')) AND active IS NULL"; $r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc)); if (@mysqli_num_rows($r) == 1) { // A match was made. // Register the values & redirect: $_SESSION = mysqli_fetch_array ($r, MYSQLI_ASSOC); mysqli_free_result($r); mysqli_close($dbc); $url = BASE_URL . 'index.php'; // Define the URL: ob_end_clean(); // Delete the buffer. header("Location: $url"); exit(); // Quit the script. } else { // No match was made. echo '<p class="error">Either the email address and password entered do not match those on file or you have not yet activated your account.</p>'; } } else { // If everything wasn't OK. echo '<p class="error">Please try again.</p>'; } mysqli_close($dbc); } // End of SUBMIT conditional. ?> The process also uses config2.php so I am including the code for that in-case it helps Code: [Select] <?php # Script 16.3 - config.inc.php // ********************************** // // ************ SETTINGS ************ // // Flag variable for site status: define('LIVE', FALSE); // Admin contact address: define('EMAIL', 'email@gmail.com'); // Site URL (base for all redirections): define ('BASE_URL', 'localhost/IUS'); // Location of the MySQL connection script: define ('MYSQL', 'login/mysqli_connect.php'); // Adjust the time zone for PHP 5.1 and greater: date_default_timezone_set ('US/Eastern'); // ************ SETTINGS ************ // // ********************************** // // ****************************************** // // ************ ERROR MANAGEMENT ************ // // Create the error handler: function my_error_handler ($e_number, $e_message, $e_file, $e_line, $e_vars) { // Build the error message. $message = "<p>An error occurred in script '$e_file' on line $e_line: $e_message\n<br />"; // Add the date and time: $message .= "Date/Time: " . date('n-j-Y H:i:s') . "\n<br />"; // Append $e_vars to the $message: $message .= "<pre>" . print_r ($e_vars, 1) . "</pre>\n</p>"; if (!LIVE) { // Development (print the error). echo '<div class="error">' . $message . '</div><br />'; } else { // Don't show the error: // Send an email to the admin: mail(EMAIL, 'Site Error!', $message, 'From: you@youremail.com'); // Only print an error message if the error isn't a notice: if ($e_number != E_NOTICE) { echo '<div class="error">A system error occurred. We apologize for the inconvenience.</div><br />'; } } // End of !LIVE IF. } // End of my_error_handler() definition. // Use my error handler. set_error_handler ('my_error_handler'); // ************ ERROR MANAGEMENT ************ // // ****************************************** // ?> At first I thought it was because cookies weren't enabled but I am positive they are, so I am really at a loss as-to what's going on, there is more to the error message, though its quite long and will take me a few minutes to go through and remove/alter any sensitive information. I have two files with coding in. One of them is the HTML form file: Code: [Select] <?php <html><head><title>Car Accident Program</title></head> <body> <!----In this block of code I am creating a form with 4 text boxes and a button as well as user prompts to get user inputted values to work with----> <h4>Car Accident Report Form</h4> <form action="Car.php" method="post"> <b>First Name:<b><br> <input type="text" size = "45" name="firstname"><br> <b>Surname:<b><br> <input type="text" size = "45" name="surname"><br> <b>Age:<b><br> <input type="text" size = "45" name="age"><br> <b>Number of weeks since accident:<b><br> <input type="text" size = "45" name="weeks"><br> <input type="submit" value="Submit report"> </form> </body> </html> and the PHP/Validation file: Code: [Select] <!----In this block of code, I am creating a PHP script that gets the user inputted values and can display them in a report as well as use an IF statement to show an extra line to appear if the user enters an age below 18 or a time since accident below 1 week or if they miss out a field or more----> <?php $firstname= $_POST ['firstname']; $surname =$_POST ['surname']; $age=$_POST ['age']; $weeks=$_POST ['weeks']; //Here, I am providing various paths and the outcomes in a PHP script if (empty($_POST['firstname']) or empty($_POST['surname']) or empty($_POST['age']) or empty($_POST['weeks'])) {$msg= "You missed out one or more fields. Click on the link below to go back to the form and enter information into all of the fields";} else if (is_numeric($age) && $age<0) {$msg="You cannot be under 0 years of age";} else if (is_numeric($weeks) && $weeks<0) {$msg="The number of weeks since an accident cannot be below 0";} else if (is_numeric($age) && $age>0 && $age<18) {$msg= "You are too young to file an accident report";} else if (is_numeric($weeks) && $weeks<2) {$msg= "You cannot file an accident report that happened less than two weeks ago";} else { setcookie(" $msg= "First Name: $firstname<br>"; $msg .="Surname: $surname<br>"; $msg .= "Age: $age<br>"; $msg .="Number of weeks since accident: $weeks<br>"; $msg .="Your report has been accepted. Please click on the link below to go back to the Accident Report Page";} echo ($msg) ?> </body> </html> <html> <a href="http://localhost/Car.htm"><br><br>Click here to add/edit an Accident Report</a> I was wondering how, if suitable, I would add a cookie or session into coding like this. Any help is appreciated, Andrew |