Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php cookies and session variables and ip address

I posted a similar question before, but never really got an answer that helped me, so I'm looking to try again. As a disclaimer, I know that a lot of the information in here doesn't follow perfect coding practices, but it is for exercise purposes only. I've tried a million things and nothing seems to be working because I'm not really sure where everything should go! I desperately need some (any!) help so thanks in advance if you can offer anything!

I'm trying to create a simple form / page that uses some basic cookie and session stuff to produce some user-specific data. I was moving along good until I came across a few problems that I can’t figure out. On my first page everything is good except for I just want the NAME of the browser the user is using. (for example, I want just the simple title: Firefox instead of the whole long version of the browser.) I've seen this be done so I think it’s possible, I just don’t know how to do it!

My real problems come up right about here, because I'm not exactly sure how to store the IP address, browser info and the current date/time (which I want shown on page 2) as session variables. Tried a few things I found, but I don’t think I was doing it right.

I also worked endlessly on trying to store the username and passwords as two separate cookies each...suggestions? Finally, what do I need to do to have a location header (used to call form_data.php) with output buffering?

(Not sure this will be that helpful, considering I probably did everything wrong! LOL) This is a totally stripped-down version of my code. Tried to post my cleanest version, even though it doesn't have much info, so that you could easily see what I was trying to do.

main file code:

<?php 
header('Location: form_data.php'); 


 setcookie('username', $_POST['username']); 
 setcookie('password', $_POST['password']); 
 //I know this isn't working.   
 //honestly I just left this in here as to show where I had been 
 //trying to save the cookie data. Pretty obvious how bad my 
 //trial and error with this went! 

 } 
?> 


<?php 

 $_SESSION['ip'] = $_SERVER['REMOTE_ADDR']; 
echo " By the way, your IP address is: </b>".$_SESSION['ip']."<br />"; 
 echo " You already know this, but the browser you are currently using 
 to view this page is:<br/>";  //What is the correct function that I should be using here? 
 echo "<form action=\"form_data.php\" method=\"post\">"; 
 echo "username:<input type=\"text\" name=\"username\" size=\"20\" value=\"\"><br/>"; 
 echo "password:<input type=\"password\" name=\"password\" size=\"20\" value=\"\"><br/>"; 
 echo "<input type=\"submit\" value=\"Submit, please\" />"; 
 echo "<br /><input type=\"hidden\" name=\"submitted\" value=\"true\" />"; 
 ?> 

form_data.php

  <?php 

   echo "Hello, ".$username;//I'm trying to get the cookie data for the username 
   echo "Your password is ".$password; //Samething here (want cookie data) 
   echo "The date and time you entered this form is: ".date("F j, Y")." -- ".date("g:i a"); 
   echo "<br/>Your IP:".$_SESSION['ip'] = $_SERVER['REMOTE_ADDR']; 
   echo "<br/>Your broswer:".;//I want full broswer data here...dont know how to do it. 
   //Overall, was this the way to get the session variables for IP, date/time and browser? 
   echo  "Thank you for filling out this form!"; 
   ?> 
like image 384
clk Avatar asked Jun 28 '11 01:06

clk


People also ask

What is the difference between session and cookie in PHP?

Cookies are client-side files on a local computer that hold user information. Sessions are server-side files that contain user data. Cookies end on the lifetime set by the user. When the user quits the browser or logs out of the programmed, the session is over.

Where is session and cookie data stored in PHP?

Cookie is a small piece of data stored on the client-side(browser) and session is a text file stored on the server-side, whose name is stored in the cookie.

Are session variables the same as cookies?

A session stores the variables and their values within a file in a temporary directory on the server. Cookies are stored on the user's computer as a text file. The session ends when the user logout from the application or closes his web browser. Cookies end on the lifetime set by the user.

How session and cookies are used for session management in PHP?

PHP provides a cookie-based implementation for session management. The $_SESSION array is used for storing session data. PHP automatically generates a session ID and sends a session cookie containing this session ID to the client machine.


2 Answers

To get the browser, use the get_browser() function:

$browserinfo = get_browser($_SERVER['HTTP_USER_AGENT']);
$browsername = $browserinfo['browser'];

Your session and cookie storage will never work because you are making a header("Location"); call before attempting to set cookies. You cannot send any output before setting cookies or establishing a session.

Before any output to the screen, call session_start();

// attach to your session (or create if it doesn't exist)
// You must call session_start() on every page where you intend to access or set session vars
// and it must be called before any output (including whitespace at the top)
session_start();

// Store some stuff...
$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];

// Store user info in session, not cookie
$_SESSION['username'] = $_POST['username'];

// Set a cookie
// Not a super secure token, but better than user/pass in cookies.
// Point here is just to show that it must be done before any output or before the redirection header.
$_SESSION['token'] = sha1(time() . rand() . $_SERVER['SERVER_NAME']);
setcookie('token', $_SESSION['token']);
// In practice, you'd want to store this token in a database with the username so it's persistent.

// Now do the redirection:
// Supposed to be an absolute URL by the HTTP spec
header("Location: http://example.com/form_data.php");

// exit right after the redirection to prevent further processing.
exit();

ADDENDUM after comments

While you work, make sure PHP displays all errors on screen. Be sure to turn off display_errors when your code goes onto a live public server.

error_reporting(E_ALL);
ini_set('display_errors', 1);

To retrieve values from cookies as you said in your question you didn't know how to do, use the $_COOKIE superglobal:

// On the page that sets it...
setcookie('somename', 'somevalue', expiry, domain);

// On the page that retrieves it...
echo $_COOKIE['somename'];
like image 73
Michael Berkowski Avatar answered Oct 28 '22 10:10

Michael Berkowski


> I'm trying to create a simple form /
> page that uses some basic cookie and
> session stuff to produce some
> user-specific data.

Sessions do use cookies under the cover(only store session_id inside cookie/set_cookie) and I advice you to use only sessions because cookies can leak information(store all the information inside cookie on that user's computer) which could be dangerous while session uses the server's filesystem/database or whatever you like when you override session_set_save_handler.


> On my first page everything is good
> except for I just want the NAME of the
> browser the user is using.

Like Michael said you can use get_browser for that:

Attempts to determine the capabilities of the user's browser, by looking up the browser's information in the browscap.ini file.

Like the PHP page says it tries to determine and you should NOT rely on this information for anything important because it can be wrong(you can fool the system, if you like). What I mean is you should not use it to validate/proof something.


> My real problems come up right about
> here, because I’m not exactly sure how
> to store the IP address, browser info
> and the current date/time (which I
> want shown on page 2) as session
> variables.

More information to retrieve the IP address can be read here(proxy-server could mislead you a little bit maybe?). To store that information just store it inside a session by first issuing session_start() on top of every page(before outputting anything) that wants to use sessions(only those to not set cookies on every page which makes page a little slower) and next store the current time inside a session variable by doing something along the lines of $_SESSION['time'] = date(DATE_RFC822);. You can read more about retrieving the time at date() page.

So the code on page 1 looks something like:

<?php

session_start();

$_SESSION['ip'] = getRealIpAddr(); # no php function => See http://roshanbh.com.np/2007/12/getting-real-ip-address-in-php.html
$_SESSION['time'] = date(DATE_RFC822);

Then on page 2 you could retrieve this information using something like:

<?php

session_start();

echo $_SESSION['ip']; // retrieve IP

> I also worked endlessly on trying to
> store the username and passwords as
> two separate cookies
> each...suggestions?

Don't store them inside a cookie(only using set_cookie and not using sessions to store information) but store them inside a session for extra security. But sessions are also vulnerable to session fixation so after storing something critical inside your session you should regenerate session id and never output/show that information to the browser/user to prevent any leakage.


> Finally, what do I need to do to have
> a location header (used to call
> form_data.php) with output buffering?

Like Michael said you should be using header function and exit to terminate script after that

<?php
header("Location: http://www.example.com/"); /* Redirect browser */

/* Make sure that code below does not get executed when we redirect. */
exit;
?>

P.S: Never store any really sensitive information like creditcard(use paypal or something) numbers or anything in your own database. I also advice you not to store passwords inside your database but use something like openId(Google's) for example to handle your authentication for extra security.

like image 28
Alfred Avatar answered Oct 28 '22 09:10

Alfred