How to create Cookies by using PHP???

Discussion in 'Scripts, 3rd Party Apps, and Programming' started by tlife143, Jul 3, 2009.

  1. tlife143

    tlife143 New Member

    I want a help on creation of cookies....

    How to create a cookies and how to access that cookie information???

    Plz help me!!!

    Wen i use setcookie(name,value,expiry);

    It's giving an error tht "Cannot modify header information - headers already sent by"
    Last edited: Jul 3, 2009
  2. garrettroyce

    garrettroyce Generally Helpful Member Community Support

  3. Scoochi2

    Scoochi2 New Member

    simply put, setcookie() must be used before ANYTHING is output to the page.
    for example, the following will not work because there is a newline before the PHP engine is engaged:

    The following will work however, despite it not being the first bit of code (because nothing else was output before it):

    if (isset($_GET['name']))
    $name $_GET['name'];

    if (isset(
    $age $_GET['age'];

    $calcage $age+5;

    if (
    $output "$name, in 5 years you will be $calcage years old!";
    $output 'please submit name & age';

  4. Twinkie

    Twinkie Banned

    Modifying headers, such as locations and cookies, must be done before any output because the headers are sent as soon as you write to the page, as already said. That is why I find it helpful to put the body of php before everything, and use output control functions to write what has been written to after the body tag, shown below.

    function ErrorHandler() {
    $flags "There has been an error!";



    //PHP Code writes body.

    $html ob_get_clean();


    if (isset($flags)) {
    "<div style=\"color: red; height: 400px;\">" $flags "</div>";


    That way if there is an error anywhere on the page, you could better handle it. You could even redirect a user to an error page. Otherwise, you would have to be worried about where the error occurred.
    Last edited: Jul 3, 2009
  5. marshian

    marshian New Member

    $_COOKIE["name"] contains the data in a cookie with the name "name". This information is not available when the cookie has just been set. In other words, the page has to be reloaded for $_COOKIE to be updated.
  6. drf1229

    drf1229 New Member

    What he (or she) said :)
  7. daman371

    daman371 New Member

    Not true. setcookie usually has to be used elsewhere because. You do have to call ob_start(); before everything else on the page.
  8. Scoochi2

    Scoochi2 New Member

    Completely not true. ob_start() will simply prevent anything being output, and instead saves everything until it is flushed.
    In my example I saved a string to a variable and then output that, basically performing the same function.

    You can get away with NEVER using ob_start, and still create cookies.

Share This Page