As the PHP developer, you must have come across COOKIES in PHP. In this article, we will see what are COOKIES in PHP and how to use it. So without any further ADO, let’s begin.
What are Cookies in PHP ?
Cookies in PHP belong to one of the superglobal variables of PHP. Cookies are small storage that stores some data on your browser.
Use-case scenario

The most useful use-case scenario would be login. Suppose you have a website where you have a feature of login and once the user logged in he would be able to see few features. Now one comes every time to your website and enters username and password to login but if you put this login details in cookies user will not have to enter username and password next time.
How to use Cookies ?
Now you know what is cookies and what could be use cases of cookies. Now lets see how to use them in code.
To set cookies in PHP setcookie()
function is used and to access the same cookies $_COOKIE
or $_REQUEST
superglobal variable is used.
Lets see how to set cookies.
$username = 'username';
$password = 'password';
setcookie("user_cookiename", $username , time()+60*60*24*24); // expire in 30 days
setcookie("pwd_cookiename", $password, time()+60*60*24*30); // expire in 30 days
So in the above example, you can see we have username and password in $username
and $password
variables. setcookie()
function accepts here 3 parameters which are
- cookie name – The name we will use to access its value.
- cookie value – Value for this cookie.
- expiry time – When cookie should expire would be passed here if you pass nothing cookie will be expired once you closed the browser.
Lets see how to access above cookies.
So as mentioned above you can access cookies either be using $_COOKIE
or $_REQUEST
superglobal variable.
echo $_COOKIE["user_cookiename"];
echo $_REQUEST["user_cookiename"];
echo $_COOKIE["pwd_cookiename"];
echo $_REQUEST["pwd_cookiename"];
After all $_COOKIE
is an array, You can use print_r()
to see all availale values.
print_r($_COOKIE);
output:
array(
user_cookiename => username,
pwd_cookiename => password
)
So thats all about what are COOKIES in PHP and how to use it. Hope this article would help you. In case of any queries write into the below comment section.
