Skip to main content

Today we will implement login with cookie using php script

Php login with cookie, provide username and password store it in cookie container

This tutorials is assume you have been following up on other tutorials, such as php signup page. You have signup page already, if you don't have any, then I think you need to create one. if you look at the code below this is html form already-made you can copy and paste for our testing. Now, copy the code below or write it manually and save it as index.php and run it to see a nice decorated ligin form.

<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST"> <fieldset style="border-radius:5px;"> <legend>Enter login details</legend> <label>Username</label><br> <input type="text" name="userlog" style="width:100%; padding:15px; border:none; display:block; font-size:18px; border-radius:5px;" placeholder="Please enter username" value="<?php if(isset($_COOKIE['userlog'])) { echo $_COOKIE['userlog']; }?>"> <label>Password</label><br> <input type="password" name="userpass" style="width:100%; padding:15px; border:none; display:block; font-size:18px; border-radius:5px;" placeholder="Please enter password" value="<?php if(isset($_COOKIE['userpass'])) { echo $_COOKIE['userpass']; }?>"> <p style="margin-top:5px; margin-bottom:5px; padding-top:5px; padding-bottom:5px;"> <input type="checkbox" name="remember" checked>Remember me</p> <input type="submit" name="submitLogin" value="Login" style="margin-top:15px; padding:15px; width:45%; float:left; cursor:pointer; display:block; color:white; text-align:center; background:#04AA6D; border:none; font-size:18px; border-radius:5px;"> <a href="signup.php" style="margin-top:15px; text-align:center; padding:15px; width:45%; float:right; text-decoration:none; display:block; cursor:pointer; color:white; background:#04AA6D; border:none; font-size:18px; border-radius:5px;">Register</a> </fieldset> </form>

Login the user and retrieve the protected page

The php script below, copy and paste on top of your html tag, this script should come first before anything else in your application. In this script, this script will open our database, in the table select the appropriate user and compare it with the one typed in the input field, if the two data are equally the same it open protected page for user. If it's not available in our database will open error page and display what went wrong. Now copy the code below and paste on top of your html file and save it as index.php run the page type username and password to login and view user profile.

//set login cookie <!--php if(!empty($_POST["remember"])) { setcookie ("userlog", $_POST["userlog"], time()+ (86400 * 30), "/"); setcookie ("userpass", $_POST["userpass"], time()+ (86400 * 30), "/"); } else { setcookie("userlog", ""); setcookie("userpass", ""); } //start session session_start(); //database user details $servername = "localhost"; $username = "webdesign"; $password = "web@design&33"; $dbname = "webdesign"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn--->connect_error) { die("Connection failed: " . $conn->connect_error); } //Post data from input stream if (isset($_POST["submitLogin"])) { if(empty($_POST["userlog"])) { echo "<script>alert('Please enter username.');</script>"; exit; }else{ $userlog = $_POST['userlog']; } if(empty($_POST["userpass"])) { echo "<script>alert('Please enter password.');</script>"; exit; }else{ $userpass = $_POST['userpass']; } //Select username and password $sql = "SELECT * FROM tutorials WHERE username='$userlog' AND password='$userpass'"; $result = $conn->query($sql); if ($result->num_rows === 1) { $row = $result->fetch_assoc(); } //Validate username and password if ($row['username'] === $userlog && $row['password'] === $userpass) { //Store everything in session container $_SESSION['id'] = $row['id']; $_SESSION['image'] = $row['image']; $_SESSION['fullname'] = $row['fullname']; $_SESSION['fulladdress'] = $row['fulladdress']; $_SESSION['emailaddress'] = $row['emailaddress']; $_SESSION['phonenumber'] = $row['phonenumber']; $_SESSION['username'] = $row['username']; $_SESSION['password'] = $row['password']; $_SESSION['project'] = $row['project']; $_SESSION['subscription'] = $row['subscription']; $_SESSION['gender'] = $row['gender']; $_SESSION['reg_date'] = $row['reg_date']; //If data is valid open protected page header("Location: Home.php"); exit; }else{ //If not valid open invalid page header("Location: Invalid.php"); exit; } } $conn->close(); ?>

Browsing the protected page called welcome to our homepage

Now, if every thing goes well we will retrieve a specific users from our database, especially a valid user that has been registered. It will retrieve general information about registered user such as: id, image, fullname, fulladdress, emailaddress, phonenumber, username, password, project, subscription, gender, registered date. Now, copy or write the below code manually and save it as success.php this will retrieve user profile.

<!--php session_start(); if (isset($_SESSION['id']) && isset($_SESSION['image']) && isset($_SESSION['fullname']) && isset($_SESSION['fulladdress']) && isset($_SESSION['emailaddress']) && isset($_SESSION['phonenumber']) && isset($_SESSION['username']) && isset($_SESSION['password']) && isset($_SESSION['project']) && isset($_SESSION['subscription']) && isset($_SESSION['gender']) && isset($_SESSION['reg_date'])) { ?--> <!--DOCTYPE html--> <html> <head> p { margin:20px; padding:20px; } </head> <body> <!--php echo '<p-->'.$_SESSION["id"].'</p>'; ?> <p><img alt="Image" loading="lazy" src="&lt;?php echo $_SESSION[&#39;image&#39;]; ?&gt;" width="400"></p> <!--php echo '<h2-->'.$_SESSION["fullname"].'</h2>'; echo '<p>'.$_SESSION["fulladdress"].'</p>'; echo '<p>'.$_SESSION["emailaddress"].'</p>'; echo '<p>'.$_SESSION["phonenumber"].'</p>'; echo '<p>'.$_SESSION["username"].'</p>'; echo '<p>'.$_SESSION["password"].'</p>'; echo '<p>'.$_SESSION["project"].'</p>'; echo '<p>'.$_SESSION["subscription"].'</p>'; echo '<p>'.$_SESSION["gender"].'</p>'; echo '<p>'.$_SESSION["reg_date"].'</p>'; echo "<a href='logout.php'>Logout</a>"; </body> </html> <!--php }else{ header("Location: index.php"); exit(); } ?-->

After login attempt failure in our database

While trying to login, if the username and password doesn't exist, we will re-direct the user to invalid page. Remember that we stored whatever details they type in our input field in cookie container. Now, retrieve that username and password telling them that he or she can't login and what they can do to be able to login. Copy and paste below code or write it manually, save it as invalidpage.php

<h2 style="color:red; text-align:center;">Attention please!</h2> <hr> <h3>The below details are not valid:</h3> <p><b>Your username: <!--php if(isset($_COOKIE["userlog"])) { echo $_COOKIE["userlog"];}?--></b></p> <p><b>Your password: <!--php if(isset($_COOKIE["userpass"])) { echo $_COOKIE["userpass"];}?--></b></p> <h4>To be able to login you need to register: </h4> <ol> <li>Provide profile picture</li> <li>Provide full name</li> <li>Provide full address</li> <li>Provide email address</li> <li>Provide phone number</li> <li>Provide username</li> <li>Choose password</li> <li>Select project type</li> <li>Select gender option</li> </ol> <p>There is no already made account which you can initialize to login. You need to register and obtain new account.</p> <p><a style="margin:0; padding:15px; background:#04AA6D; font-size:18px; font-weight:bold; text-align:center; display:block; border-radius:10px; text-decoration:none; color:white;" href="logout.php">Login or register</a></p>

Deleting session container after storing items in it or logout

After using session containers it's a good practice to clear everything in it leaving it empty. In the below script, this script will help logout users that was previously logged in. Now, copy and paste below code or write it manually save the code as logout.php for your testing.

<!--php session_start(); session_unset(); session_destroy(); header("Location: index.php"); ?-->

Summary

This script was prepared with all the seriousness in the world, if you are struct anywhere, don't hesitate to ask questions, we are open to answer your question at any time. Thank you for reading this articles.

Comments

Latest post

We will take a closer look on how to bind webpage in python programming language

Today we will take a closer look on how to run python in your webpage under windows operating system. Let's assume you have installed xampp in your windows operating system and have python program installed as well. If you have not done so, then go on to installed xampp in your computer together with python program. Remember to select software version compactible to your computer. When you are ready with these two software, then copy the code below: #!"C:\Users\Administrator\AppData\Local\Programs\Python\Python311-32\python.exe" print ("Content-Type: text/html\n") print (" ") print (" ") print (" ") print (" ") print (" Hello world! ") print (" Welcome to my first python webpage ") print (" ") print (" ") Save the above code as index.py in C:\xampp\htdocs the path should be: C:\xampp\htdocs\index.py On your browser address bar you can type http://localhost/index.py, ...

Our today post will focus on how to implement php class and method

A class is a container for objects, and object is items in class. Class is container that we can store all kinds of obejects, such as variable, function etc. Today we will implement class and objects , property, set, get and the rest. If you look at the php class below, this is exactly how to declare empty php class. Php class container with public objects, function set parameters and gets parameters. In php class below, we created two functions, one to set a value and one to get the value, pass the instance object and its value. Now you can copy the below code for your testing. name = $name; } function getname() { return $this->name; } } $username = new KcFuns(); $username->setname('Kenan Chiquado'); echo "Output:"; echo "Username is: ".$username->getname(); echo "----------------------------------"; ?> Php class several objects function and parameters In our second php class implementation, we will lo...

Today we will look into how to implement cUrl in php application

Passing json file via cUrl in php We will implement passing json file via cUrl and submit to next server. cUrl is all about special communication between two or more server. Such as server1.com sending data to server2.com. A lot of beginner had always ask endless question about what is cUrl and what cUrl actually does. A simple answer there is: cUrl is a special communication between two or more server. Now, if you look at json code below, it has been neatly written and indented and ready for testing. Launch your notepad copy the json data below and save it as data.json place it in a folder where you saved other php file. { "id": "1", "image": "image\/chiquado.jpg", "fullname": "Kenan Chiquado", "fulladdress": "Udah, Igbo-eze North LGA, Enugu state, Nigeria", "emailaddress": "2348130802790", "phonenumber": "presschiquado@gmail.com...

Our today post will focus on how to implement php hits counter

PHP counter step 1: Have you ever wonder how you can monitor, view or learn how many times your website is been processed by visitors. How many times your website is been browse by your visitors? If your answer is 'no', then it's time to learn all these. You can learn how many times browser processed your website by binding certain php script on top of your webpage. Now, if you look at our php script below, this script will help you count how many times your website was processed at any given moment. To apply our php script below, you can copy and paste this script on top of your webpage before html declaration. PHP counter step 2: Again, the below script, you can copy and put it in a separate file. All you need to do is check time to time and see the digits number your script return. That's exactly how many times your website was processed. Example of the counter: Hits counter While applying our tutorials, if our code spot error, don't hesit...

In today post we will focus on how to create php script that could upload picture to server

Before writing script to upload files to server, you have to check ensure that php file upload is set to 'On' in php.ini. Open C:\xampp\php\php.ini file locate the line that says upload_file = On and also change the php upload max setting, example: php_max_upload = 100m. Now save the file, restart the server and start writing php script to upload your file. Step 1: Below is the html code to implement our practice of file upload. You can write it manually or copy and paste. " enctype="multipart/form-data" method="POST"> Uploader Step 2: Php command to target the upload folder, php comman to get file name, php command to check upload status, and php command to validate file extension. Below is our sample code: Step 3: We will use php global object called $_POST to get the image object. And check if the file is image or not, if it's not image the upload status will be set to zero. Below is our sample code: if(isset(...