{"id":4,"date":"2014-07-16T03:57:51","date_gmt":"2014-07-16T03:57:51","guid":{"rendered":"http:\/\/www.scriptut.com\/?p=4"},"modified":"2024-05-26T14:02:26","modified_gmt":"2024-05-26T14:02:26","slug":"login-logout-system-using-in-php-for-beginners","status":"publish","type":"post","link":"https:\/\/scriptut.com\/php\/login-logout-system-using-in-php-for-beginners\/","title":{"rendered":"Creating a Simple Login\/Logout System in PHP for Beginners"},"content":{"rendered":"\n<p>Setting up a login and logout system in PHP is straightforward, making it an ideal project for beginners. This guide will walk you through the steps to create a basic authentication system. We will create four files and a MySQL table to handle the user login and logout functionality.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Files Overview<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>login.php<\/code><\/li>\n\n\n\n<li><code>authenticate.php<\/code><\/li>\n\n\n\n<li><code>index.php<\/code><\/li>\n\n\n\n<li><code>logout.php<\/code><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">MySQL Table Creation<\/h2>\n\n\n\n<p>First, we need to create a MySQL table to store user data. Use the following SQL script to create a <code>users<\/code> table:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>CREATE TABLE IF NOT EXISTS `users` (\n  `id` int(11) NOT NULL AUTO_INCREMENT,\n  `username` varchar(50) NOT NULL,\n  `password` varchar(150) NOT NULL,\n  `name` varchar(50) NOT NULL,\n  `active` int(11) NOT NULL,\n  PRIMARY KEY (`id`)\n) ENGINE=MyISAM;\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Step 1: Creating the Login Form (<code>login.php<\/code>)<\/h2>\n\n\n\n<p>We start by creating a login form where users can input their username and password.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;!DOCTYPE html>\n&lt;html lang=\"en\">\n&lt;head>\n    &lt;meta charset=\"UTF-8\">\n    &lt;title>Login&lt;\/title>\n&lt;\/head>\n&lt;body>\n    &lt;form action=\"authenticate.php\" method=\"post\">\n        &lt;table width=\"100%\" cellpadding=\"4\" cellspacing=\"0\" border=\"0\">\n            &lt;tr>\n                &lt;td>Username:&lt;\/td>\n                &lt;td>&lt;input type=\"text\" name=\"username\" required>&lt;\/td>\n            &lt;\/tr>\n            &lt;tr>\n                &lt;td>Password:&lt;\/td>\n                &lt;td>&lt;input type=\"password\" name=\"password\" required>&lt;\/td>\n            &lt;\/tr>\n            &lt;tr>\n                &lt;td>&lt;\/td>\n                &lt;td>&lt;input type=\"submit\" value=\"Login\">&lt;\/td>\n            &lt;\/tr>\n        &lt;\/table>\n    &lt;\/form>\n&lt;\/body>\n&lt;\/html>\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Form Action<\/strong>: The form&#8217;s action is set to <code>authenticate.php<\/code>, which means the data will be submitted to <code>authenticate.php<\/code> for processing.<\/li>\n\n\n\n<li><strong>Input Fields<\/strong>: Two fields are created for username and password. Both fields are required for submission.<\/li>\n\n\n\n<li><strong>Submit Button<\/strong>: A submit button is provided to send the form data.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Step 2: Authenticating the User (<code>authenticate.php<\/code>)<\/h2>\n\n\n\n<p>This file will handle the authentication logic.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;?php\nsession_start();\n$conn = new mysqli('localhost', 'root', 'pass', 'test');\n\nif ($conn->connect_error) {\n    die('Connection failed: ' . $conn->connect_error);\n}\n\nif ($_SERVER&#91;'REQUEST_METHOD'] == 'POST') {\n    $username = trim($_POST&#91;'username']);\n    $password = trim($_POST&#91;'password']);\n\n    if ($username != '') {\n        $stmt = $conn->prepare(\"SELECT * FROM users WHERE username = ? AND active = 1\");\n        $stmt->bind_param('s', $username);\n        $stmt->execute();\n        $result = $stmt->get_result();\n        $user = $result->fetch_assoc();\n\n        if ($user &amp;&amp; password_verify($password, $user&#91;'password'])) {\n            $_SESSION&#91;'user_id'] = $user&#91;'id'];\n            $_SESSION&#91;'username'] = $user&#91;'username'];\n            header('Location: index.php');\n            exit;\n        } else {\n            header('Location: login.php?err=1');\n            exit;\n        }\n    }\n}\n?>\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Session Start<\/strong>: We start a session to store user data upon successful login.<\/li>\n\n\n\n<li><strong>Database Connection<\/strong>: A connection to the MySQL database is established.<\/li>\n\n\n\n<li><strong>POST Check<\/strong>: We check if the form was submitted via POST.<\/li>\n\n\n\n<li><strong>User Validation<\/strong>: We retrieve the user record from the database and verify the password using <code>password_verify()<\/code>.<\/li>\n\n\n\n<li><strong>Session Variables<\/strong>: If the user is authenticated, their ID and username are stored in session variables.<\/li>\n\n\n\n<li><strong>Redirection<\/strong>: Upon successful authentication, the user is redirected to <code>index.php<\/code>. If authentication fails, the user is redirected back to the login page with an error.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Step 3: Creating the Index Page (<code>index.php<\/code>)<\/h2>\n\n\n\n<p>This page is accessible only to logged-in users.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;?php\nsession_start();\nif (!isset($_SESSION&#91;'user_id'])) {\n    header('Location: login.php');\n    exit;\n}\n?>\n&lt;!DOCTYPE html>\n&lt;html lang=\"en\">\n&lt;head>\n    &lt;meta charset=\"UTF-8\">\n    &lt;title>Home&lt;\/title>\n&lt;\/head>\n&lt;body>\n    &lt;p>You are now logged in&lt;\/p>\n    &lt;a href=\"logout.php\">Logout&lt;\/a>\n&lt;\/body>\n&lt;\/html>\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Session Check<\/strong>: We check if the user ID is set in the session. If not, the user is redirected to the login page.<\/li>\n\n\n\n<li><strong>Logged In Message<\/strong>: A simple message is displayed indicating that the user is logged in.<\/li>\n\n\n\n<li><strong>Logout Link<\/strong>: A link is provided to log out.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Step 4: Creating the Logout Script (<code>logout.php<\/code>)<\/h2>\n\n\n\n<p>This script handles the user logout process.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;?php\nsession_start();\nsession_unset();\nsession_destroy();\nheader('Location: login.php');\nexit;\n?>\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Session Handling<\/strong>: The session is started, and then all session variables are unset, and the session is destroyed.<\/li>\n\n\n\n<li><strong>Redirection<\/strong>: The user is redirected to the login page after logging out.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Conclusion<\/h3>\n\n\n\n<p>With these steps, you have created a basic login\/logout system in PHP. This system includes:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>A login form for user input.<\/li>\n\n\n\n<li>An authentication script to verify user credentials.<\/li>\n\n\n\n<li>A protected page accessible only to authenticated users.<\/li>\n\n\n\n<li>A logout script to end the user session.<\/li>\n<\/ul>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Learn how to create a simple and secure login\/logout system in PHP with this step-by-step guide for beginners. This tutorial covers creating a user login form, authenticating users, managing sessions, and handling logout functionality using PHP and MySQL.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3],"tags":[10,7,8,6,9],"class_list":["post-4","post","type-post","status-publish","format-standard","hentry","category-php","tag-global-variables","tag-login","tag-logout","tag-php-2","tag-session-data"],"_links":{"self":[{"href":"https:\/\/scriptut.com\/wp-json\/wp\/v2\/posts\/4","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/scriptut.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/scriptut.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/scriptut.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/scriptut.com\/wp-json\/wp\/v2\/comments?post=4"}],"version-history":[{"count":3,"href":"https:\/\/scriptut.com\/wp-json\/wp\/v2\/posts\/4\/revisions"}],"predecessor-version":[{"id":397,"href":"https:\/\/scriptut.com\/wp-json\/wp\/v2\/posts\/4\/revisions\/397"}],"wp:attachment":[{"href":"https:\/\/scriptut.com\/wp-json\/wp\/v2\/media?parent=4"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/scriptut.com\/wp-json\/wp\/v2\/categories?post=4"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/scriptut.com\/wp-json\/wp\/v2\/tags?post=4"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}