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.

Solution

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.

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

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




Read more articles


General Knowledge



Learn Popular Language