Can you check my code if I wrote like a professional?
- connection page.
- form sign page.
- plan page.
- log out page.
First I create the database and tables, then the connection file, then the form sign in page, then the plan page, finally the log out page
Database educate (create table users):
CREATE TABLE users(
id INT AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
password VARCHAR(100) NOT NULL,
PRIMARY KEY(id)
);
Conection.php:
<?php
$servername = 'localhost';
$username = 'root';
$password = '';
$db = 'educate';
//I added @ to delete error message that comming from MySQL
$conn = @new mysqli($servername,$username,$password,$db);
if($conn->connect_error) die('Connection faild');
?>
Form signin.php:
<?php
//Check the cookie
if(!empty($_COOKIE['user'])) { header ('location: plan.php'); }
?>
<?php
//Check the inputs
function test_input($data) {
$data = trim($data);
//return a $data with whitespace stripped from the beginning and end of
$data
$data = stripslashes($data); //emoves backslashes
$data = htmlspecialchars($data);
//converts some predefined characters to HTML entities
return $data;
}
?>
<?php
$username = $password = $password_hash = '';
$usernameErr = $passwordErr = '';
//Connection file
require ('connection.php');
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if(empty($_POST['username'])){
$usernameErr = 'Username cannot be empty';
}else{
$username = test_input($_POST['username']);
}
if(empty($_POST['password'])){
$passwordErr = 'Password cannot be empty';
}else{
$password = test_input($_POST['password']);
$password_hash = md5($password);
}
//Select the data from DB('educate')
$sql = " SELECT username, password FROM users WHERE username='$username'
AND password='$password_hash' ";
$result = $conn->query($sql);
if($result->num_rows === 0) {
$usernameErr = 'Username is error';
$password = 'Password is error';
} elseif($result->num_rows === 1) {
//Set cookie (one hour) and moved to another page
SETCOOKIE('user', $username, time() + (60*60) );
header('location: plan.php');
}
}
?>
<form action="#" method="post">
Username: <input type="text" name="username" placeholder="username">
<?php echo $usernameErr; ?>
<br/><br/>
Password: <input type="password" name="password" placeholder="password">
<?php echo $passwordErr; ?>
<br/><br/>
<input type="submit" value="Login">
</form>
Logout.php:
<?php
setcookie('user',"", time() - (30*30) );
header('location: form signin.php');
?>