Create a login in PHP
Firstly, keep in mind that you can have several ways to create a login in PHP; in this section, we will do one, and I will explain it.
Let’s start with the style of the login, so that it has a certain visual consistency. In this case, I will do it within style tags.
<style> form{ background-color:#d5d5d5; padding:10px 20px; width:600px; border-radius: 5px; } form .form_sector{ margin-bottom: 5px; } form .form_label{ display: inline-block; width:100px; } form .form_input{ display: inline-block; width:450px; } form .form_submit{ width:550px; text-align: right; } form .form_submit input{ display: inline-block; width:150px; } input{ width:100%; } .warning{ width:550px; background-color:#ffe861; border-radius: 15px; padding: 10px; } .success{ width:550px; background-color:#a2ffb9; border-radius: 15px; padding:10px; } </style>
Keep in mind that you probably won’t do the above, since CSS frameworks like Bootstrap or even simpler ones like PureCSS have a very good style for forms.
The Form
The form can be created in several ways; this will depend on how we use CSS. Here, we will use the classic one.
<form action="<?php $_SERVER['PHP_SELF']?>" method="post"> <div class=""><h2>Login</h2></div> <div class="form_sector"> <div class="form_label"><label for="name">Name:</label></div> <div class="form_input"><input type="text" name="name" id="name" /></div> </div> <div class="form_sector"> <div class="form_label"><label for="password">Password:</label></div> <div class="form_input"><input type="text" name="password" id="password" /></div> </div> <div class="form_sector"> <div class="form_submit"><input type="submit" value="confirm"/></div> </div> </form>
Notice that in the form we use $_SERVER['PHP_SELF']
, this will make it so that we send the data to the same page we are on. I particularly prefer to send the data to another PHP page, for example, process_login.php.
In this case, we will do it with $_SERVER['PHP_SELF']
, but keep in mind that making a separate file separates the visual part from the logical part.
Let’s continue by looking at our PHP part. I won’t include everything in the style tag, but keep in mind that it goes above the following:
<?php $form = false; if (!isset($_POST["name"]) || $_POST["name"] == "") { $form = true; } if (!isset($_POST["password"]) || $_POST["password"]=="") { $form = true; } ?> <?php if($form): ?> <form action="<?php $_SERVER['PHP_SELF']?>" method="post"> <div class=""><h2>Login</h2></div> <div class="form_sector"> <div class="form_label"><label for="name">Name:</label></div> <div class="form_input"><input type="text" name="name" id="name" /></div> </div> <div class="form_sector"> <div class="form_label"><label for="password">Password:</label></div> <div class="form_input"><input type="text" name="password" id="password" /></div> </div> <div class="form_sector"> <div class="form_submit"><input type="submit" value="confirm"/></div> </div> </form> <?php else: $message= ""; $status; $checkname = preg_match("$[a-z0-9_-]{3,16}$",$_POST['name']); if ($checkname !== false && $checkname == 0) { $message .="Your username is not allowed"; $status="warning"; } $checkpassword =preg_match("$(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$",$_POST['password']); if ($checkpassword !== false && $checkpassword == 0) { $message .="your password is not allowed"; $status="warning"; } if ($checkname && $checkpassword) { $message .="// aqui va el chequeo de si existe en la base de datos"; $status="success"; } echo "<div class=\"$status\">"; echo "$message"; echo "</div>"; endif; ?>
Analyzing the code (create a login in PHP)
Now it’s time to analyze the code of the page. For this, I will separate the main parts.
Knowing if I have to show the form
$form = false; if (!isset($_POST["name"]) || $_POST["name"] == "") { $form = true; } if (!isset($_POST["password"]) || $_POST["password"]=="") { $form = true; }
In these lines, we are checking if the variables $_POST['name']
and $_POST['password']
exist, and we also check if they are empty strings. If the data sent by POST does not exist or is empty, the value of $form
will be false.
Next lines of code:
<?php if($form): ?> <form action="<?php $_SERVER['PHP_SELF']?>" method="post"> <div class=""><h2>Login</h2></div> <div class="form_sector"> <div class="form_label"><label for="name">Name:</label></div> <div class="form_input"><input type="text" name="name" id="name" /></div> </div> <div class="form_sector"> <div class="form_label"><label for="password">Password:</label></div> <div class="form_input"><input type="text" name="password" id="password" /></div> </div> <div class="form_sector"> <div class="form_submit"><input type="submit" value="confirm"/></div> </div> </form>
I decide if the form is shown.
Validation
I perform the form check with regular expressions on the data. This part is called validation; in Laravel and other frameworks, you can find it by that name (validation).
You can opt for third-party validation; on Packagist, there is a wide variety.
If you don’t use a framework or a third-party package, you can also create a class that performs the validation. That way, you can call validation(class name)
and do $validation->name($_POST['name'])
.
In addition to performing the validations, we also have the decision of whether we will process the data or not, and finally, the message to the user.
<?php else: $message= ""; $status; $checkname = preg_match("$[a-z0-9_-]{3,16}$",$_POST['name']); if ($checkname !== false && $checkname == 0) { $message .="Your username is not allowed"; $status="warning"; } $checkpassword =preg_match("$(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$",$_POST['password']); if ($checkpassword !== false && $checkpassword == 0) { $message .="your password is not allowed"; $status="warning"; } if ($checkname && $checkpassword) { $message .="// aqui va el chequeo de si existe en la base de datos"; $status="success"; } echo "<div class=\"$status\">"; echo "$message"; echo "</div>"; endif; ?>
Before the check on database
Here we decide whether to enter our database and check if the user exists or not. Keep in mind that the database connection part is not done because there are multiple database management systems and several ways to connect to some of them.
After the validations, we have:
if ($checkname && $checkpassword) { // aqui va el chequeo de si existe en la base de datos //En caso de success muestro un mensaje de logueado con exito $message .="Login success"; $status="success"; }
In this case, we will force it to be successful because we are not checking if the user is in the database; we will do that in another post.
This part can also be placed in the validation class, ensuring that it passes the validation class.
Then, if the validation class does not return a validation error, we continue with the database check. Therefore, we could have several messages and statuses, being ‘success’ when the user passes the validation and it is verified that the user is who they claim to be. In other cases, the status would be ‘error’ or ‘warning’
Success message or error message depending on if we could login
echo "<div class=\"$status\">"; echo "$message"; echo "</div>"; endif; ?>
I don’t think it needs to be explained, as it is the message that will be given. $status only defines which class will use the style, and $message is the message
We could improve our message a bit by adding an if statement that checks if $status != “”. This will prevent our div from being printed on the screen if the $status variable does not yet have a value of ‘success’ or ‘error’.
I am thinking about whether I should include the user check in MySQL or make a related post so that it is not too long. If you want, you can give me your opinion on X (formerly Twitter).
The part that checks if the variables exist could also go inside a validation class, making the code much clearer.