?
Solved

setcookie() in php

Posted on 2011-05-10
6
Medium Priority
?
500 Views
Last Modified: 2012-05-11
Dear Experts,
I have tutorial at http://www.w3schools.com/php/php_cookies.asp to create my
first cookie, "Login", by php code.I have question. After I create "Login" cookie name
and its value by setcookie() in php, where is it stored or saved  into my server system?
what is the file name to store cookie in my server ?

And the last question is the tuturial said:
"A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values"

SO my question is  whether  browser will also save my cookie "Login" into my window XP CP location at
C:\Documents and Setting\Administorator\Local Settings\Temporary Internet Files\  folder ?
I have checked by Firefox's option and show cookie , that cookie path is at
C:\Documents and Setting\Administorator\Local Settings\Temporary Internet Files\  folder.
But I could not find any cookie file generated from my domain, for example, www.mydomain.com or mydomain.com, Why ?
I have seen in the folder there is a lot cookie file related to what the website I visited before. How those
website generated the cookie file in my at  C:\Documents and Setting\Administorator\Local Settings\Temporary Internet Files\  folder ?


Please advise
Duncan
//setcookie()
==================
<html>
<body>
<?php
$value = "mycookieloginvalue";

// send a simple cookie
setcookie("Login",$value);
?>
</body>
</html>
//Read Cookie
=================
<html>
<body>
<?php
// Print a cookie
echo $_COOKIE["Install"];
//setcookie("user", "Alex Porter", time()+3600);
// A way to view all cookies
print_r($_COOKIE);
echo 
foreach($_COOKIE as $cookie){   echo $cookie.'<br>';}

?> 
</body>
</html>

Open in new window

0
Comment
Question by:duncanb7
6 Comments
 
LVL 84

Accepted Solution

by:
Dave Baldwin earned 668 total points
ID: 35735047
You're looking in the wrong place for Firefox cookies.  They are stored in your Firefox profile in a file called "cookies.sqlite".  In Firefox, you can also go to Tools -> Options -> Privacy and view your cookies there.

"C:\Documents and Setting\Administrator\Local Settings\Temporary Internet Files\" is for Microsoft Internet Explorer.  Your personal cookies from IE will be under your user name in something like "C:\Documents and Setting\YourUserName\Local Settings\Temporary Internet Files\".
0
 
LVL 8

Assisted Solution

by:imantas
imantas earned 664 total points
ID: 35735484
setcookie() doesn't save your cookie on the server, it just sends it to the browser. If you want to store cookies on your server, try using session_open() (google for it), which creates a session and lets you store some data (PHP will take care of storage):
Set some data
<?php
session_open();
$_SESSION['message'] = 'This message will be passed to another script';
?>

Open in new window


Read the data
session_open();
echo isset($_SESSION['message']) ? $_SESSION['message'] : "You did not visit the script that sets the message";

Open in new window



Additionally, php will automatically set and read cookie named 'PHPSESSID' (default). You can also store your own cookies in $_SESSION or any other data related to the user.
0
 
LVL 111

Assisted Solution

by:Ray Paseur
Ray Paseur earned 668 total points
ID: 35736860
Please see this link:
http://us2.php.net/manual-lookup.php?pattern=session_open%28%29

The correct function is session_start() and it usually sets a cookie.  

If you are interested in learning about login concepts, this article will be helpful, I hope.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_2391-PHP-login-logout-and-easy-access-control.html

If you are interested in learning how cookies work, install this script and run it to see what PHP does with the data.  Please read the comments carefully.  Cookies are not intuitive - the $_COOKIE array is not modified by setcookie(), and the cookies set in one HTTP request are not available until the next HTTP request.  This is confusing for many programmers who are trying to use cookies for the first time!

Best regards, ~Ray
<?php // RAY_cookie_example.php


// RECEIVE FORM INPUT AND SET A COOKIE WITH THE NAME AND VALUES FROM THE FORM
// MAN PAGE: http://php.net/manual/en/function.setcookie.php
// TO SEE COOKIES IN FIREFOX, FOLLOW SOMETHING LIKE TOOLS => OPTIONS => PRIVACY => SHOW COOKIES (OR "REMOVE INDIVIDUAL")


define('COOKIE_LIFE', 60*60*24); // A 24-HOUR DAY IN SECONDS ( = 86,400 )

// IF THE FORM HAS BEEN POSTED
if (!empty($_POST))
{

    // TIDY UP THE POST INPUT - CLEAN AND NOT MORE THAN 16 BYTES
    $name = substr(clean_string($_POST["name"]),0,16);
    $data = substr(clean_string($_POST["data"]),0,16);

    // BE SURE WE HAVE USEFUL INFORMATION
    if ( ($name == '') || ($data == '') ) die("MISSING INPUT: PLEASE <a href=\"{$_SERVER['PHP_SELF']}\">TRY AGAIN</a>");



    // CHOOSE THE COOKIE NAME AND VALUE
    $cookie_name    = $name;
    $cookie_value   = $data;



    // ESTABLISH THE COOKIE LIFE - CHOOSE ONE OF THESE FOR THE COOKIE
    // USE THIS TO MAKE COOKIE EXPIRE AT END OF BROWSER LIFE
    $cookie_expires = 0;

    // USE THIS TO MAKE A PERSISTENT COOKIE.  DEFINE COOKIE_LIFE IN SECONDS.  date('Z') IS UTC OFFSET IN SECONDS
    $cookie_expires = time() + date('Z') + COOKIE_LIFE;



    // MAKE THE COOKIE AVAILABLE TO ALL DIRECTORY PATHS IN THE WWW ROOT
    $cookie_path	= '/';



    // MAKE THE COOKIE AVAILABLE TO ALL SUBDOMAINS - DOMAIN NAME STARTS WITH DOT AND OMITS WWW (OR OTHER SUBDOMAINS).
    $x = explode('.', strtolower($_SERVER["HTTP_HOST"]));
    $y = count($x);
    if ($y == 1) // MAYBE 'localhost'?
    {
        $cookie_domain = $x[0];
    }
    else // SOMETHING LIKE 'www2.atf70.whitehouse.gov'?
    {
        // USE THE LAST TWO POSITIONS TO MAKE THE HOST DOMAIN
        $cookie_domain = '.' . $x[$y-2] . '.' . $x[$y-1];
    }



    // MAKE THE COOKIE AVAILABLE TO HTTP, NOT JUST HTTPS
    $cookie_secure    = FALSE;



    // HIDE COOKIE FROM JAVASCRIPT (PHP 5.2+)
    $cookie_http      = TRUE;



    // SET THE COOKIE
    if (setcookie($cookie_name, $cookie_value, $cookie_expires, $cookie_path, $cookie_domain, $cookie_secure, $cookie_http))
    {
        echo "<br/>SUCCESS!  THE COOKIE HAS BEEN SET AND WILL BE AVAILABLE TO THE NEXT PAGE LOAD \n";
    }
    else
    {
        echo "<br/>FAILURE!  THE COOKIE WAS NOT SET AS EXPECTED \n";
    }



    // AT THIS POINT, THE COOKIE HAS BEEN SET, BUT IT IS _NOT_ AVAILABLE TO THIS SCRIPT.
    // THE COOKIE WILL NOT BE AVAILABLE TO OUR SERVER UNTIL THE NEXT SCRIPT!
    // THIS IS BECAUSE THE BROWSER SENDS THE COOKIE TO OUR SCRIPT BEFORE OUR SCRIPT STARTS RUNNING.
    echo '<pre>$_COOKIE CONTAINS '; var_dump($_COOKIE); echo "</pre>\n";
    echo '<pre>$_POST CONTAINS ';   var_dump($_POST);   echo "</pre>\n";
    echo "<br/>THE COOKIE HAS BEEN SET WITH THESE VALUES: \n";
    echo "<br/>COOKIE NAME: $cookie_name \n";
    echo "<br/>COOKIE VALUE: $cookie_value \n";
    echo "<br/>COOKIE EXPIRES: $cookie_expires ";
    echo " == " . date('r') . "\n";
    echo "<br/>COOKIE PATH: $cookie_path \n";
    echo "<br/>COOKIE DOMAIN: $cookie_domain \n";
    echo "<br/>COOKIE SECURE: "; var_dump($cookie_secure); echo " \n";
    echo "<br/>COOKIE HTTP: ";   var_dump($cookie_http);   echo " \n";

    echo "<br/>";
    echo "<br/>TO SEE THE COOKIES, IF ANY, <a href=\"{$_SERVER['PHP_SELF']}\">CLICK HERE</a> \n";
    echo "<br/>";
}

// END OF SETTING THE COOKIE - DROP OUT OF PHP INTO HTML TO CREATE THE FORM
?>

<form method="post">
COOKIE NAME: <input name="name" /><br/>
COOKIE DATA: <input name="data" /><br/>
<input type="submit" />
</form>

<?php
// SHOW THE COOKIE ARRAY, IF ANY
echo '<pre>$_COOKIE CONTAINS '; var_dump($_COOKIE); echo "</pre>\n";



// UNRELATED FUNCTION TO FORCE A STRING TO CHARACTERS ONLY
function clean_string($string)
{
    return trim(preg_replace('/[^A-Z0-9_]/i', '', $string));
}

// SHOW THE SCRIPT CODE
// die(highlight_file(__FILE__, TRUE));

Open in new window

0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 13

Author Closing Comment

by:duncanb7
ID: 35739076
Thanks for your reply for
a good start
0
 
LVL 13

Author Comment

by:duncanb7
ID: 35739610
Dear Imants,
there is no session_open function in php
there is only session_start(0 in php.

Please advise
0
 
LVL 8

Expert Comment

by:imantas
ID: 35742329
Sorry, session_start was the function I was talking about. It's just that some time went by since I've programmed with PHP, so I forgot the name. Should've google it before posting.
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

When crafting your “Why Us” page, there are a plethora of pitfalls to avoid. Follow these five tips, and you’ll be well on your way to creating an effective page.
A while back, I ran into a situation where I was trying to use the calculated columns feature in SharePoint 2013 to do some simple math using values in two lists. Between certain data types not being accessible, and also with trying to make a one to…
In this tutorial viewers will learn how to embed videos in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: "<!DOCTYPE html>": Use the <video> tag to insert a video. Define the src as the URL of your video; this is similar to …
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
Suggested Courses
Course of the Month13 days, 16 hours left to enroll

807 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question