PHP setrawcookie() function

Definition and usage

The setrawcookie() function does not URL-encode the cookie value and sends an HTTP cookie.

Cookies are variables sent from the server to the browser. Cookies are usually small text files embedded by the server into the user's computer. Whenever the computer requests a page through the browser, this cookie is sent.

The name of the cookie is specified as the same-named variable. For example, if the sent cookie is named "name", an automatic variable $user will be created, containing the value of the cookie.

Cookies must be assigned before any other output is sent.

If successful, the function returns true, otherwise it returns false.

Syntax

setcookie(name,value,expire,path,domain,secure)
Parameters Description
name Required. Specify the name of the cookie.
value Required. Specify the value of the cookie.
expire Optional. Specify the expiration time of the cookie.
path Optional. Specify the server path of the cookie.
domain Optional. Specify the domain of the cookie.
secure Optional. Specify whether to transmit the cookie through a secure HTTPS connection.

Tips and comments

Note:You can access the value of the cookie named "user" through $HTTP_COOKIE_VARS["user"] or $_COOKIE["user"].

Note:setrawcookie() with setcookie() Almost completely the same, the difference is that the cookie value is not automatically URL-encoded when sent to the client.

Instance

Example 1

Set and send cookie:

<?php
$value = "my cookie value";
// Send a simple cookie
setrawcookie("TestCookie",$value);
?>
<html>
<body>
...
...
<?php
$value = "my cookie value";
// Send a cookie that expires in 24 hours
setrawcookie("TestCookie",$value, time()+3600*24);
?>
<html>
<body>
...
...

Example 2

Search for different methods of cookie values:

<html>
<body>
<?php
// Output individual cookie
echo $_COOKIE["TestCookie"];
echo "<br />";
echo $HTTP_COOKIE_VARS["TestCookie"];
echo "<br />";
// Output tutti i cookie
print_r($_COOKIE);
?>
</body>
</html>

Output:

my cookie value
my cookie value
Array ([TestCookie] => my cookie value)

Esempio 3

// Elimina un cookie impostando la data di scadenza a una data/ora passata

<?php
// Imposta la data di scadenza a un'ora fa
setrawcookie ("TestCookie", "", time() - 3600);
?>
<html>
<body>
...
...

Esempio 4

Creare un array cookie:

<?php
setrawcookie("cookie[three]","cookietre");
setrawcookie("cookie[two]","cookiedue");
setrawcookie("cookie[one]","cookieuno");
// Output cookie (dopo il ricarico della pagina)
if (isset($_COOKIE["cookie"]))
  {
  foreach ($_COOKIE["cookie"] as $name => $value)
    {
    echo "$name : $value <br />";
    }
  }
?>
<html>
<body>
...
...

Output:

tre : cookietre
due : cookiedue
uno : cookieuno