PHP Exercise : Set a cookie to store login detail

Write a program to store the username in cookie and check whether the user have successfully login or not.


Cookies are pieces of content that are sent to a user's web browser. To set a cookie, we must call the setcookie() function before sending any other content to the browser, because a cookie is actually part of the header information.

Syntax of setcookie()
setcookie(name, value, expire, path, domain, secure, httponly);

The following example demonstrates how to store the username in a cookie and check whether that user successfully login or not -

	$submitted =  isset($_POST['username']) &&  isset($_POST['password']);
	if($submitted) {
		setcookie('username', $_POST['username']);
	<title>User Authentication</title>
	<?php if ($submitted): ?>
	<p>Hello <b><?php echo $_POST['username']; ?></b></p>
	<?php else: ?>
	<p>Login First</p>
	<?php endif; ?>

In the above code, we have set a variable to know if we submitted a login or not, and sets the username in cookie.

Related PHP Programs for Practice

PHP - Division table program
PHP - Prime Number Program
PHP - Print numbers 10 to 1 using recursion
PHP - Loop through an associative array
PHP - Differentiate between fgets, fgetss and fgetcsv
PHP - Set session on login
PHP - Convert text to speech
PHP - Copying or moving a file
PHP - Locking a file
PHP - CURL Cookie Jar
PHP - Password Hashing
PHP - Emoji Unicode Characters PHP - Age calculator
PHP - Get array key
PHP - Capitalize first letter
PHP - Set Timezone
PHP - Remove duplicates from array
PHP - Calculate percentage of total
PHP - Fibonacci Series Program
PHP - Lock a file
PHP - Insert image in database

Read more articles

General Knowledge

Learn Popular Language