{"id":3321,"date":"2024-08-06T11:59:55","date_gmt":"2024-08-06T14:59:55","guid":{"rendered":"https:\/\/horatech.shop\/?p=3321"},"modified":"2024-11-29T14:18:54","modified_gmt":"2024-11-29T17:18:54","slug":"como-fazer-um-sistema-de-login-seguro-em-php","status":"publish","type":"post","link":"https:\/\/horatech.shop\/en\/como-fazer-um-sistema-de-login-seguro-em-php\/","title":{"rendered":"How to make a secure login system in PHP"},"content":{"rendered":"<p>Ensuring the security of your PHP login system is fundamental to protecting user data and the integrity of your site. <\/p>\n\n\n\n<p>In this guide, we'll show you step by step how to implement a <strong>login system<\/strong> robust and secure, from the initial configuration of the development environment to the best security practices.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"1024\" height=\"768\" src=\"https:\/\/i0.wp.com\/horatech.shop\/wp-content\/uploads\/2024\/09\/Como-fazer-um-sistema-de-login-seguro-em-PHP.webp?resize=1024%2C768&#038;ssl=1\" alt=\"\" class=\"wp-image-3322\" srcset=\"https:\/\/i0.wp.com\/horatech.shop\/wp-content\/uploads\/2024\/09\/Como-fazer-um-sistema-de-login-seguro-em-PHP.webp?resize=1024%2C768&amp;ssl=1 1024w, https:\/\/i0.wp.com\/horatech.shop\/wp-content\/uploads\/2024\/09\/Como-fazer-um-sistema-de-login-seguro-em-PHP.webp?resize=300%2C225&amp;ssl=1 300w, https:\/\/i0.wp.com\/horatech.shop\/wp-content\/uploads\/2024\/09\/Como-fazer-um-sistema-de-login-seguro-em-PHP.webp?resize=768%2C576&amp;ssl=1 768w, https:\/\/i0.wp.com\/horatech.shop\/wp-content\/uploads\/2024\/09\/Como-fazer-um-sistema-de-login-seguro-em-PHP.webp?w=1200&amp;ssl=1 1200w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><figcaption class=\"wp-element-caption\"><em>Creating a login system in php<\/em><\/figcaption><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Why is a Secure Login System Important?<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>The importance of security<\/strong><\/h3>\n\n\n\n<p>When it comes to creating a PHP login system, security is not an option, but a necessity. A secure login system protects your users' sensitive information and prevents confidential data from being accessed by malicious people. Without the right security measures, your application can become an easy target for hackers.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Main threats to login systems<\/strong><\/h3>\n\n\n\n<p>There are several threats that can compromise a login system, among them:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Brute force attacks:<\/strong> repeated attempts to guess passwords.<\/li>\n\n\n\n<li><strong>SQL injection:<\/strong> insertion of malicious code via input fields.<\/li>\n\n\n\n<li><strong>Session theft:<\/strong> capturing session cookies to impersonate another user.<\/li>\n\n\n\n<li><strong>Cross-Site Scripting (XSS):<\/strong> execution of malicious scripts in the user's browser.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Benefits of a secure system<\/strong><\/h3>\n\n\n\n<p>Implementing a secure login system has many benefits:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Data protection:<\/strong> ensures that personal and sensitive information remains secure.<\/li>\n\n\n\n<li><strong>User confidence:<\/strong> users feel more secure when using your application.<\/li>\n\n\n\n<li><strong>Legal compliance:<\/strong> helps to comply with data protection regulations.<\/li>\n\n\n\n<li><strong>Risk reduction:<\/strong> minimizes the chance of successful attacks and their consequences.<\/li>\n<\/ul>\n\n\n\n<p>A secure login system is the first line of defense against cyber threats. It not only protects user data, but also strengthens your application's reputation.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Configuring the Development Environment<\/h2>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"1024\" height=\"768\" src=\"https:\/\/i0.wp.com\/horatech.shop\/wp-content\/uploads\/2024\/09\/configurando-o-ambiente.webp?resize=1024%2C768&#038;ssl=1\" alt=\"\" class=\"wp-image-3323\" srcset=\"https:\/\/i0.wp.com\/horatech.shop\/wp-content\/uploads\/2024\/09\/configurando-o-ambiente.webp?resize=1024%2C768&amp;ssl=1 1024w, https:\/\/i0.wp.com\/horatech.shop\/wp-content\/uploads\/2024\/09\/configurando-o-ambiente.webp?resize=300%2C225&amp;ssl=1 300w, https:\/\/i0.wp.com\/horatech.shop\/wp-content\/uploads\/2024\/09\/configurando-o-ambiente.webp?resize=768%2C576&amp;ssl=1 768w, https:\/\/i0.wp.com\/horatech.shop\/wp-content\/uploads\/2024\/09\/configurando-o-ambiente.webp?w=1200&amp;ssl=1 1200w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><figcaption class=\"wp-element-caption\"><em>setting up the environment<\/em><\/figcaption><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>PHP and MySQL installation<\/strong><\/h3>\n\n\n\n<p>To begin with, it is essential to have PHP and MySQL installed on your system. You can download PHP directly from the official website and MySQL from the official MySQL website. Make sure you download the correct version for your operating system.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Configuring the server<\/strong><\/h3>\n\n\n\n<p>After installing PHP and MySQL, you'll need to set up a local server. The easiest way to do this is to use packages such as XAMPP or WAMP, which come with Apache, PHP and MySQL ready to use. Simply download, install and start the server.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Checking versions and dependencies<\/strong><\/h3>\n\n\n\n<p>Before you start coding, it's important to check that all versions and dependencies are correct. You can do this by running the following commands in the terminal:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>php -v\nmysql --version<\/code><\/pre>\n\n\n\n<p>This ensures that you are using the latest and most compatible versions of PHP and MySQL. Also, check that you have the necessary PHP extensions installed, such as <code>mysqli<\/code> e <code>pdo_mysql<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Creating the Database<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Basic database structure<\/strong><\/h3>\n\n\n\n<p>First, we need to create the database structure that will store the user information. Let's create a table called <code>users<\/code> with the following fields:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>CREATE TABLE users (\n  ID INT UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT,\n  login VARCHAR(30) NOT NULL,\n  password VARCHAR(40) NOT NULL,\n  PRIMARY KEY (ID)\n) ENGINE=MyISAM;<\/code><\/pre>\n\n\n\n<p>This table has three columns: <code>ID<\/code>, which is the primary key and will be incremented automatically; <code>login<\/code>, which will store the username; and <code>password<\/code>, which will store the user's password.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Creating the necessary tables<\/strong><\/h3>\n\n\n\n<p>In addition to the table <code>users<\/code>In addition, we can create other tables for extra functionality, such as login attempts. For example, a table for storing login attempts could be created like this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>CREATE TABLE login_attempts (\n  attempt_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,\n  user_id INT NOT NULL,\n  attempt_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n) ENGINE=InnoDB;<\/code><\/pre>\n\n\n\n<p>This table helps to monitor and limit login attempts, preventing brute force attacks.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Setting user permissions<\/strong><\/h3>\n\n\n\n<p>To increase security, it is important to define specific permissions for database users. Create a user with limited privileges:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>CREATE USER 'sec_user'@'localhost' IDENTIFIED BY 'passwordSegura123';\nGRANT SELECT, INSERT, UPDATE ON `your_database`.* TO 'sec_user'@'localhost';<\/code><\/pre>\n\n\n\n<p><strong>Tip:<\/strong> Use a strong and unique password for the database user. This helps protect your information from unauthorized access. With these permissions, even if someone manages to access the database, they won't be able to delete or modify critical data.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Implementing the Login Form<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>HTML structure of the form<\/strong><\/h3>\n\n\n\n<p>Let's create the basic structure of the HTML login form. This form will collect the user's username and password. Here's a simple example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n&lt;head&gt;\n    &lt;title&gt;User login&lt;\/title&gt;\n&lt;\/head&gt;\n&lt;body&gt;\n    &lt;form method=&quot;POST&quot; action=&quot;\/en\/login.php\/&quot; data-trp-original-action=&quot;login.php&quot;&gt;\n        &lt;label for=&quot;login&quot;&gt;Login:&lt;\/label&gt;\n        &lt;input type=&quot;text&quot; name=&quot;login&quot; id=&quot;login&quot; required&gt;&lt;br&gt;\n        &lt;label for=&quot;senha&quot;&gt;Password:&lt;\/label&gt;\n        &lt;input type=&quot;password&quot; name=&quot;senha&quot; id=&quot;senha&quot; required&gt;&lt;br&gt;\n        &lt;input type=&quot;submit&quot; value=&quot;To enter&quot;&gt;\n    &lt;input type=&quot;hidden&quot; name=&quot;trp-form-language&quot; value=&quot;en&quot;\/&gt;&lt;\/form&gt;\n&lt;\/body&gt;\n&lt;\/html&gt;<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Adding JavaScript for password hashing<\/strong><\/h3>\n\n\n\n<p>To increase security, it is good practice to hash the password on the client side before sending it to the server. This can be done with JavaScript. Let's use the SHA-512 library for this. First, add the library's script to your HTML:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;script type=\"text\/javascript\" src=\"sha512.js\"&gt;&lt;\/script&gt;<\/code><\/pre>\n\n\n\n<p>Then create a JavaScript function to hash the password:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;script type=\"text\/javascript\"&gt;\nfunction hashSenha(form, password) {\n    var p = document.createElement(\"input\");\n    form.appendChild(p);\n    p.name = \"hashed_senha\";\n    p.type = \"hidden\";\n    p.value = sha512(password.value);\n    password.value = \"\";\n    form.submit();\n}\n&lt;\/script&gt;<\/code><\/pre>\n\n\n\n<p>And modify the form to use this function:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;form method=&quot;POST&quot; action=&quot;\/en\/login.php\/&quot; onsubmit=&quot;hashSenha(this, this.senha);&quot; data-trp-original-action=&quot;login.php&quot;&gt;\n    &lt;label for=&quot;login&quot;&gt;Login:&lt;\/label&gt;\n    &lt;input type=&quot;text&quot; name=&quot;login&quot; id=&quot;login&quot; required&gt;&lt;br&gt;\n    &lt;label for=&quot;senha&quot;&gt;Password:&lt;\/label&gt;\n    &lt;input type=&quot;password&quot; name=&quot;senha&quot; id=&quot;senha&quot; required&gt;&lt;br&gt;\n    &lt;input type=&quot;submit&quot; value=&quot;To enter&quot;&gt;\n&lt;input type=&quot;hidden&quot; name=&quot;trp-form-language&quot; value=&quot;en&quot;\/&gt;&lt;\/form&gt;<\/code><\/pre>\n\n\n\n<p><strong>Form design best practices<\/strong><\/p>\n\n\n\n<p>A good form design is not only aesthetically pleasing, but also improves usability and security. Here are some tips:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Use clear and concise labels:<\/strong> Make sure that the form fields are clearly labeled.<\/li>\n\n\n\n<li><strong>Input validation:<\/strong> Validate user data on both the client and server side.<\/li>\n\n\n\n<li><strong>Immediate feedback:<\/strong> Inform users immediately if there is an error in filling out the form.<\/li>\n\n\n\n<li><strong>Accessibility:<\/strong> Ensure that the form is accessible to all users, including those who use screen readers.<\/li>\n<\/ul>\n\n\n\n<p><strong>Tip:<\/strong> Always use HTTPS to ensure that the data transmitted between the client and the server is secure.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Secure Login Processing<\/h2>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"1024\" height=\"768\" src=\"https:\/\/i0.wp.com\/horatech.shop\/wp-content\/uploads\/2024\/09\/adicionando-funcionalidades.webp?resize=1024%2C768&#038;ssl=1\" alt=\"\" class=\"wp-image-3325\" srcset=\"https:\/\/i0.wp.com\/horatech.shop\/wp-content\/uploads\/2024\/09\/adicionando-funcionalidades.webp?resize=1024%2C768&amp;ssl=1 1024w, https:\/\/i0.wp.com\/horatech.shop\/wp-content\/uploads\/2024\/09\/adicionando-funcionalidades.webp?resize=300%2C225&amp;ssl=1 300w, https:\/\/i0.wp.com\/horatech.shop\/wp-content\/uploads\/2024\/09\/adicionando-funcionalidades.webp?resize=768%2C576&amp;ssl=1 768w, https:\/\/i0.wp.com\/horatech.shop\/wp-content\/uploads\/2024\/09\/adicionando-funcionalidades.webp?w=1200&amp;ssl=1 1200w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><figcaption class=\"wp-element-caption\"><em>adding functionalities<\/em><\/figcaption><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Sanitizing user entries<\/strong><\/h3>\n\n\n\n<p>Before anything else, it is essential to sanitize user entries. This means cleaning and validating the data that the user enters into the login form. Use functions such as <code>htmlspecialchars()<\/code> e <code>mysqli_real_escape_string()<\/code> to prevent SQL and XSS injections.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Checking credentials in the database<\/strong><\/h3>\n\n\n\n<p>After sanitizing the data, the next step is to check the credentials in the database. Use statements prepared with <code>mysqli<\/code> to avoid SQL injections. Here's a basic example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>if ($stmt = $mysqli-&gt;prepare(\"SELECT id, username, password, salt FROM members WHERE email = ? LIMIT 1\")) {\n    $stmt-&gt;bind_param('s', $email);\n    $stmt-&gt;execute();\n    $stmt-&gt;store_result();\n    $stmt-&gt;bind_result($user_id, $username, $db_password, $salt);\n    $stmt-&gt;fetch();\n    $password = hash('sha512', $password.$salt);\n    if($stmt-&gt;num_rows == 1) {\n        if($db_password == $password) {\n            \/\/ Login successful\n        } else {\n            \/\/ Incorrect password\n        }\n    } else {\n        \/\/ User not found\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Managing sessions securely<\/strong><\/h3>\n\n\n\n<p>Managing sessions securely is crucial to protecting the user's account. Always regenerate the session ID after logging in with <code>session_regenerate_id()<\/code>. In addition, store important information such as the IP address and user agent to verify the authenticity of the session.<\/p>\n\n\n\n<p><strong>Remember:<\/strong> Never store passwords in plain text. Always use hashing and preferably a salt<\/p>\n\n\n\n<p>to strengthen security.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Additional Practices to Strengthen Security<\/h2>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"1024\" height=\"768\" src=\"https:\/\/i0.wp.com\/horatech.shop\/wp-content\/uploads\/2024\/09\/validando-o-sistema.webp?resize=1024%2C768&#038;ssl=1\" alt=\"\" class=\"wp-image-3324\" srcset=\"https:\/\/i0.wp.com\/horatech.shop\/wp-content\/uploads\/2024\/09\/validando-o-sistema.webp?resize=1024%2C768&amp;ssl=1 1024w, https:\/\/i0.wp.com\/horatech.shop\/wp-content\/uploads\/2024\/09\/validando-o-sistema.webp?resize=300%2C225&amp;ssl=1 300w, https:\/\/i0.wp.com\/horatech.shop\/wp-content\/uploads\/2024\/09\/validando-o-sistema.webp?resize=768%2C576&amp;ssl=1 768w, https:\/\/i0.wp.com\/horatech.shop\/wp-content\/uploads\/2024\/09\/validando-o-sistema.webp?w=1200&amp;ssl=1 1200w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><figcaption class=\"wp-element-caption\"><em>validating the system<\/em><\/figcaption><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Account blocking after several attempts<\/strong><\/h3>\n\n\n\n<p>Implement a temporary blocking system after several failed login attempts. This can be done by counting login attempts over a period of time and, when a limit is exceeded, temporarily blocking the account.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Use of HTTPS and SSL<\/strong><\/h3>\n\n\n\n<p>Always use HTTPS and SSL to protect communications between the client and the server. This helps prevent attacks such as man-in-the-middle, where transmitted data can be intercepted.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Multi-factor authentication<\/strong><\/h3>\n\n\n\n<p>For an extra level of security, consider implementing multi-factor authentication (MFA). This can include something the user knows (password), something they have (SMS token) or something they are (fingerprint).<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Conclusion<\/strong><\/h2>\n\n\n\n<p>By following these steps, you'll be well on your way to creating a secure and robust PHP login system. <\/p>\n\n\n\n<p>Security must always be a priority, as it protects not only user data, but also the reputation and integrity of your application.<\/p>","protected":false},"excerpt":{"rendered":"<p>Garantir a seguran\u00e7a do sistema de login em PHP \u00e9 fundamental para proteger os dados dos usu\u00e1rios e a integridade do seu site. Neste guia, vamos te mostrar passo a passo como implementar um sistema de login robusto e seguro, desde a configura\u00e7\u00e3o inicial do ambiente de desenvolvimento at\u00e9 as melhores pr\u00e1ticas de seguran\u00e7a. Por [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":3322,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[1],"tags":[],"class_list":["post-3321","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-programacao"],"blocksy_meta":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/horatech.shop\/wp-content\/uploads\/2024\/09\/Como-fazer-um-sistema-de-login-seguro-em-PHP.webp?fit=1200%2C900&ssl=1","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/horatech.shop\/en\/wp-json\/wp\/v2\/posts\/3321","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/horatech.shop\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/horatech.shop\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/horatech.shop\/en\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/horatech.shop\/en\/wp-json\/wp\/v2\/comments?post=3321"}],"version-history":[{"count":3,"href":"https:\/\/horatech.shop\/en\/wp-json\/wp\/v2\/posts\/3321\/revisions"}],"predecessor-version":[{"id":3798,"href":"https:\/\/horatech.shop\/en\/wp-json\/wp\/v2\/posts\/3321\/revisions\/3798"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/horatech.shop\/en\/wp-json\/wp\/v2\/media\/3322"}],"wp:attachment":[{"href":"https:\/\/horatech.shop\/en\/wp-json\/wp\/v2\/media?parent=3321"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/horatech.shop\/en\/wp-json\/wp\/v2\/categories?post=3321"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/horatech.shop\/en\/wp-json\/wp\/v2\/tags?post=3321"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}