Jump to content

Simple registration form


RaggedClinic13

Recommended Posts

I made a registration/login form a while ago, you can have it if you want. It's nothing fancy, doesn't have password reset, but it is pretty simple. Keep the directory structure and this is also mobile friendly.

SQL: (run this first)

CREATE TABLE userdata (
  uid int(11) NOT NULL AUTO_INCREMENT,
  firstname varchar(255) NOT NULL,
  lastname varchar(255) NOT NULL,
  username varchar(20) NOT NULL,
  useremail varchar(255) NOT NULL,
  userpassword varchar(255) NOT NULL,
  regdate timestamp  NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (uid)
);

Put the following in an "includes" folder:

db.php: (obviously update the variables)

<?php
$type     = 'mysql';                 // Type of database
$server   = 'localhost';             // Server the database is on
$db       = 'db_name';             // Name of the database
$port     = '3306';                      // Port is usually 8889 in MAMP and 3306 in XAMPP
$charset  = 'utf8mb4';               // UTF-8 encoding using 4 bytes of data per character

$username = 'your_user_name';         // Enter YOUR username here
$password = 'xxxxxx';         // Enter YOUR password here

$options  = [                        // Options for how PDO works
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];                                                                  // Set PDO options

// DO NOT CHANGE ANYTHING BENEATH THIS LINE
$dsn = "$type:host=$server;dbname=$db;port=$port;charset=$charset"; // Create DSN
try {                                                               // Try following code
    $pdo = new PDO($dsn, $username, $password, $options);           // Create PDO object
} catch (PDOException $e) {                                         // If exception thrown
    throw new PDOException($e->getMessage(), $e->getCode());        // Re-throw exception
}

header-member.php: (includes)

<!DOCTYPE html>
<html>
  <head>
    <title>Members area</title>
  </head>
  <body>
    <div class="page">
      <header>
        <a href="index.php"></a>
      </header>
      <nav>
        <a href="home.php">Home</a>
        <a href="products.php">Products</a>
        <a href="account.php">My Account</a>
        <?= $logged_in ? '<a href="logout.php">Log Out</a>' : '<a href="login.php">Log In</a>'; ?>
      </nav>
      <section>

sessions.php: (includes)

<?php
session_start();                                         // Start/renew session
$logged_in = $_SESSION['logged_in'] ?? false;            // Is user logged in?


function login()                                         // Remember user passed login
{
    session_regenerate_id(true);                         // Update session id
    $_SESSION['logged_in'] = true;                       // Set logged_in key to true
}

function logout()                                        // Terminate the session
{
    $_SESSION = [];                                      // Clear contents of array

    $params = session_get_cookie_params();               // Get session cookie parameters
    setcookie('PHPSESSID', '', time() - 3600, $params['path'], $params['domain'],
        $params['secure'], $params['httponly']);         // Delete session cookie

    session_destroy();                                   // Delete session file
}

function require_login($logged_in)                       // Check if user logged in
{
    if ($logged_in == false) {                           // If not logged in
        header('Location: login.php');                   // Send to login page
        exit;                                            // Stop rest of page running
    }
}

style.css: (put this in a folder called "css")

* {
    box-sizing: border-box;
}




#registration{
	text-align: center;
	border: 2px solid blue;
  border-radius: 12px;
      overflow: hidden;

   width: 280px;
  height: 580px;
  margin: auto;
  padding-top: 20px;
  background-color: #DCDCDC;


}



#login {
  text-align: center;
  border: 2px solid blue;
  border-radius: 12px;
      overflow: hidden;

     width: 220px;
  height: 400px;
  margin: auto;
  padding-top: 20px;
  background-color: #DCDCDC;

}
input {
  height: 6%;
  border-radius: 4px;
  -webkit-transition: 0.5s;
}

input:focus {
  border: 3px solid #5d96f0;
}

input[type=submit] {
    background-color: blue;
  border: none;
  color: white;
  padding: 9px;
  text-decoration: none;
  margin: 4px 2px;
  cursor: pointer;
  width: 65%;
}

.member {
  text-align: center;
  margin-top: 10px;
    font-family: Arial, Helvetica, sans-serif;


}

.error{
  color: red;
   font-family: Arial, Helvetica, sans-serif;
   font-size: 16px;

}

label {
  font-family: Arial, Helvetica, sans-serif;
   font-size: 14px;
    color: blue;
    position: relative;
    bottom: 10px;

}


#login > input[type=submit]:nth-child(7) {
  padding: 4px;
  width: 82%;
}

.success {
    color: blue;
   font-family: Arial, Helvetica, sans-serif;
   font-size: 16px;
    text-align: center;
  margin-top: 20px;
}

.errorsignup, .errorlogin {
    color: red;
   font-family: Arial, Helvetica, sans-serif;
   font-size: 16px;
    text-align: center;
  margin-top: 20px;
}

@media screen and (max-width: 520px) {


  #registration {
      height: 590px;
      width: 350px;
 


}

#login {
  height: 500px;
      width: 350px;
}
input {
  width: 300px;
}


input[type=submit] {
width: 300px;
}


#login > input[type=submit]:nth-child(7) {
  padding: 6px;
}

}

Put the following in the root directory:

account.php:

<?php
include 'includes/sessions.php';
require_login($logged_in);                  // Redirect user if not logged in
?>
<?php include 'includes/header-member.php'; // Include new header file ?>

  <h1>Account</h1>
  A user account page goes here.

home.php:

<?php 
include 'includes/sessions.php';
include 'includes/header-member.php'; 
?>

<h1>Home</h1>
<p><b>Not logged in:</b> navigation bar shows a link to log in.</p>
<p><b>Logged in:</b> navigation bar shows a link to log out.</p>

index.php: 

<!DOCTYPE html>
<html>
<head>
        <link rel="stylesheet" href="css/style.css">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">


<meta charset="UTF-8">
<title>Sign up form</title>
</head>
<body>
 <?php


 include 'includes/db.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {


$UserError = '';

$FirstName = $_POST['fname'];
$LastName = $_POST['lname'];
$UserName = $_POST['uname'];
$Email = $_POST['email'];
$confirmEmail = $_POST['confirmemail'];
$PassWord = $_POST['password'];
$ConfirmPassWord = $_POST['confirmpassword'];

$sql = "SELECT username FROM userdata
WHERE username = :username;";

$statement = $pdo->prepare($sql);
$statement->execute(['username' => $UserName]);
$UserExists  = $statement->fetch();


$count = $statement->rowCount();

if ($count !== 0){
  
  $UserError = "<p class='error'>This Username is taken</p>";
  
} 


$sqlemail = "SELECT useremail FROM userdata
WHERE useremail = :useremail;";

$statement1 = $pdo->prepare($sqlemail);
$statement1->execute(['useremail' => $Email]);
$EmailExists  = $statement1->fetch();

$CountEmail = $statement1->rowCount();


if ($CountEmail !== 0){
  
  $EmailError = "<p class='error'>This email is already registered</p>";
  
} 

if ($PassWord !== $ConfirmPassWord){
  $PassError = "<p class='error'>The passwords do not match</p>";
}

if ($Email !== $confirmEmail){
  $emailmatcherror = "<p class='error'>The emails do not match</p>";
}



$hashPass = password_hash($PassWord, PASSWORD_DEFAULT);

$sqlvalidate = "SELECT username, useremail FROM userdata
WHERE useremail = :useremail OR username = :username;";

$statement2 = $pdo->prepare($sqlvalidate);
//$statement2->execute(['useremail' => $Email]);



$statement2->execute(array('useremail' => $Email, 'username' => $UserName));


$validateReg  = $statement2->fetch();


$countValidate = $statement2->rowCount();

$sqlinsert = "INSERT INTO userdata (firstname, lastname, username, useremail, userpassword)
VALUES (:firstname, :lastname, :username, :useremail, :userpassword);";

if ($countValidate == 0 && $PassWord == $ConfirmPassWord && $Email == $confirmEmail) {
  $statement3 = $pdo->prepare($sqlinsert);
  $statement3->execute(array('firstname' => $FirstName, 'lastname' => $LastName, 'username' => $UserName, 'useremail' => $Email, 'userpassword' => $hashPass));
  //$registerUser  = $statement3->fetch();
  $last_id = $pdo->lastInsertId();

  
} if (isset($last_id)) {
  $msg = "<p class='success'>You have signed up sucessfully</p>";

} else {
  $msg = "<p class='errorsignup'>Something went wrong!</p>";

} 







}




 ?>

<form id="registration" action="index.php" method="post">
 
  <input type="text" id="fname" name="fname" placeholder="Name" required autofocus pattern="[a-zA-Z\s]+" value="<?php if (isset($FirstName)) { 

        echo "$FirstName"; }
?>"><br><br>
  <input type="text" id="lname" name="lname" placeholder="Last Name" required pattern="[a-zA-Z\s]+" value="<?php if (isset($LastName)) { 

        echo "$LastName"; }
?>"><br><br>
  <input type="text" id="uname" name="uname" placeholder="User Name" required pattern="[A-Za-z0-9_]{1,20}" value="<?php if (isset($UserName)) { 

        echo "$UserName"; }
?>"><br>
    <p><?php if (isset($UserError)) { 

        echo "$UserError"; }
?></p>

    



  <input type="email" id="email" name="email" placeholder="Email" required value="<?php if (isset($Email)) { 

        echo "$Email"; }
?>"><br><br>
  <input type="email" id="confirmemail" name="confirmemail" placeholder="Confirm Email" required value="<?php if (isset($confirmEmail)) { 

        echo "$confirmEmail"; }
?>"><br>

    <p><?php if (isset($EmailError)) { 

        echo "$EmailError"; }
?>
  
  <?php if (isset($emailmatcherror)) { 

        echo "$emailmatcherror"; }
?>
</p>

  <input type="password" id="password" name="password" placeholder="Password" required pattern=".{8,}"><br><br>
  <label for="password" class="passlabel">Password must be at least 8 characters</label><br>
  <input type="password" id="confirmpassword" name="confirmpassword" placeholder="Confirm Password" required pattern=".{8,}"><br><br>

     <p><?php if (isset($PassError)) { 

        echo "$PassError"; }
?></p>
  <input type="submit" value="Sign up">
 
</form>

<div class="member">
<a href="login.php">Already a member? Login</a>
</div>
<?php
if (isset($msg)) { 

        echo "$msg"; }

?>

</body>
</html>

login.php:

<!DOCTYPE html>
<html>
<head>

	  <link rel="stylesheet" href="css/style.css">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta charset="UTF-8">
<title>Login Form</title>
</head>
<body>


	<?php
	include 'includes/sessions.php';
		include 'includes/db.php';


	
		


		if ($logged_in) {                              // If already logged in
    header('Location: account.php');           // Redirect to account page
    exit;                                      // Stop further code running
		}

		

		if ($_SERVER['REQUEST_METHOD'] == 'POST') {

				$UserName = $_POST['uname'];
				$PassWord = $_POST['password'];

				$sqlhash = "SELECT username, userpassword FROM userdata
				WHERE username = :username;";

				$statementHash = $pdo->prepare($sqlhash);
				$statementHash->execute(['username' => $UserName]);
				$passVerify  = $statementHash->fetch();

				$countVerify = $statementHash->rowCount();


				if ($countVerify > 0 && $passVerify['username'] == $UserName && password_verify($PassWord, $passVerify['userpassword'])) {
					 login();                               // Call login function
       				 header('Location: account.php');       // Redirect to account page
        			 exit;

				}	else {
					$errorlogin = "<p class='errorlogin'>Incorrect details</p>";

				}


		
			}

	?>

<form id="login" action="login.php" method="post">

	  <input type="text" id="uname" name="uname" placeholder="User Name" required pattern="[A-Za-z0-9_]{1,20}" value="<?php if (isset($UserName)) { 

        echo "$UserName"; }
?>"><br><br>
	    <input type="password" id="password" name="password" placeholder="Password" required pattern=".{8,}"><br><br>
	     <input type="submit" value="Login">

</form>
<?php
if (isset($errorlogin)) { 

        echo "$errorlogin"; }

?>


</body>
</html>

logout.php:

<?php
include 'includes/sessions.php';
logout();                             // Call logout() to terminate session
header('Location: index.php');         // Redirect to home page

products.php:

<?php
include 'includes/sessions.php';
require_login($logged_in);                  // Redirect user if not logged in
?>
<?php include 'includes/header-member.php'; // Include new header file ?>


<h1>Products</h1>

<p>A list of products would go here.</p>

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.