Browsing articles from "November, 2022"

Part 6: Create your own Registration System using PHP and MySql

Nov 28, 2022   //   by h05t5cr1pt3r   //   Blog  //  No Comments

6. Implementing Account Activation

The account activation system will send an email to the user with the activation link when the user has registered.

The first thing we need to do is to go into phpMyAdmin and select our database, in our case this would be phplogin, you can either add the column activation_code to the accounts table or execute the SQL statement below.

ALTER TABLE accounts ADD activation_code varchar(50) DEFAULT ''

Now we need to edit our register.php file, search for this line of code:

if ($stmt = $con->prepare('INSERT INTO accounts (username, password, email) VALUES (?, ?, ?)')) {

Replace with:

if ($stmt = $con->prepare('INSERT INTO accounts (username, password, email, activation_code) VALUES (?, ?, ?, ?)')) {

Search for:

$stmt->bind_param('sss', $_POST['username'], $password, $_POST['email']);

Replace with:

$uniqid = uniqid();
$stmt->bind_param('ssss', $_POST['username'], $password, $_POST['email'], $uniqid);

The $uniqud variable will generate a unique ID that we’ll use for our activation code, this will be sent to the user’s email address.

Search for:

echo 'You have successfully registered, you can now login!';

Replace with:

$from    = 'noreply@yourdomain.com';
$subject = 'Account Activation Required';
$headers = 'From: ' . $from . "\r\n" . 'Reply-To: ' . $from . "\r\n" . 'X-Mailer: PHP/' . phpversion() . "\r\n" . 'MIME-Version: 1.0' . "\r\n" . 'Content-Type: text/html; charset=UTF-8' . "\r\n";
// Update the activation variable below
$activate_link = 'http://yourdomain.com/phplogin/activate.php?email=' . $_POST['email'] . '&code=' . $uniqid;
$message = '<p>Please click the following link to activate your account: <a href="' . $activate_link . '">' . $activate_link . '</a></p>';
mail($_POST['email'], $subject, $message, $headers);
echo 'Please check your email to activate your account!';

Upon account registration, the user will need to activate their account using the activation link that is sent to their email address. You need to update both the $from and $activate_link variables.

Now we can proceed to create the activation file. The activation file will process the GET parameters and verify the email and code. The user’s account will be activated if the code is valid.

Edit/create the activate.php file and add the following code:

<?php
// Change this to your connection info.
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'root';
$DATABASE_PASS = '';
$DATABASE_NAME = 'phplogin';
// Try and connect using the info above.
$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);
if (mysqli_connect_errno()) {
	// If there is an error with the connection, stop the script and display the error.
	exit('Failed to connect to MySQL: ' . mysqli_connect_error());
}
// First we check if the email and code exists...
if (isset($_GET['email'], $_GET['code'])) {
	if ($stmt = $con->prepare('SELECT * FROM accounts WHERE email = ? AND activation_code = ?')) {
		$stmt->bind_param('ss', $_GET['email'], $_GET['code']);
		$stmt->execute();
		// Store the result so we can check if the account exists in the database.
		$stmt->store_result();
		if ($stmt->num_rows > 0) {
			// Account exists with the requested email and code.
			if ($stmt = $con->prepare('UPDATE accounts SET activation_code = ? WHERE email = ? AND activation_code = ?')) {
				// Set the new activation code to 'activated', this is how we can check if the user has activated their account.
				$newcode = 'activated';
				$stmt->bind_param('sss', $newcode, $_GET['email'], $_GET['code']);
				$stmt->execute();
				echo 'Your account is now activated! You can now <a href="index.html">login</a>!';
			}
		} else {
			echo 'The account is already activated or doesn\'t exist!';
		}
	}
}
?>

If the code reflects the one in the database that is associated with the user’s account then the value of the activation_code column will be updated to activated.

If we want to check if the user has activated their account, we can add the following code to the pages we want to restrict non-activated users:

if ($account['activation_code'] == 'activated') {
	// account is activated
	// Display home page etc
} else {
	// account is not activated
	// redirect user or display an error
}

For the above code to work, you will need to connect to your MySQL database and select the user’s account.

Also, take note PHP mail function will only work if your computer or server supports it. If it doesn’t send an email, check your configuration or install a mail server such as Postfix.

Conclusion

Congratulations! You’ve successfully created a Login System (if you followed the previous tutorial) and registration system with PHP and MySQL. You’re free to use the code in this tutorial and adapt it for your own projects.

Remember that this is just a secure base that you should work from. Consider changing or implementing your own validation, and implement your own features.

If you would like more of this tutorial series, feel free to drop a comment and suggest to us what we could create next.

Enjoy coding!

Part 5: Create your own Registration System using PHP and MySql

Nov 28, 2022   //   by h05t5cr1pt3r   //   Blog  //  No Comments

5. Validating Form Data

We already have basic validation in our PHP script but what if we want to check if the email is actually an email or if the username and password should be a certain amount of characters long, you can do that with the codes below, add them in the register.php file before the following line:

if ($stmt = $con->prepare('SELECT id, password FROM accounts WHERE username = ?')) {

 

Email Validation

if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
	exit('Email is not valid!');
}

 

Invalid Characters Validation

if (preg_match('/^[a-zA-Z0-9]+$/', $_POST['username']) == 0) {
    exit('Username is not valid!');
}

 

Character Length Check

if (strlen($_POST['password']) > 20 || strlen($_POST['password']) < 5) {
	exit('Password must be between 5 and 20 characters long!');
}

You should always implement your own validation, these are just basic examples.

Part 4: Create your own Registration System using PHP and MySql

Nov 28, 2022   //   by h05t5cr1pt3r   //   Blog  //  No Comments

4. Registering Users with PHP & MySQL

Now we need to create the registration file that will process the form fields, check for basic validation, and insert the new account into our database.

The registration page will require a connection to our database and therefore we must include the necessary variables and MySQL functions. Edit the register.php file and add the following code:

<?php
// Change this to your connection info.
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'root';
$DATABASE_PASS = '';
$DATABASE_NAME = 'phplogin';
// Try and connect using the info above.
$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);
if (mysqli_connect_errno()) {
	// If there is an error with the connection, stop the script and display the error.
	exit('Failed to connect to MySQL: ' . mysqli_connect_error());
}

Don’t forget to update the MySQL variables if your MySQL credentials do not reflect the declared values.

Next, we can add basic validation to ensure the user has entered their details and check for empty variables.

// Now we check if the data was submitted, isset() function will check if the data exists.
if (!isset($_POST['username'], $_POST['password'], $_POST['email'])) {
	// Could not get the data that should have been sent.
	exit('Please complete the registration form!');
}
// Make sure the submitted registration values are not empty.
if (empty($_POST['username']) || empty($_POST['password']) || empty($_POST['email'])) {
	// One or more values are empty.
	exit('Please complete the registration form');
}

Now we need to check if the account already exists in the database. We can check this by selecting a record from our accounts table with the same username that the user has provided.

Add after:

// We need to check if the account with that username exists.
if ($stmt = $con->prepare('SELECT id, password FROM accounts WHERE username = ?')) {
	// Bind parameters (s = string, i = int, b = blob, etc), hash the password using the PHP password_hash function.
	$stmt->bind_param('s', $_POST['username']);
	$stmt->execute();
	$stmt->store_result();
	// Store the result so we can check if the account exists in the database.
	if ($stmt->num_rows > 0) {
		// Username already exists
		echo 'Username exists, please choose another!';
	} else {
		// Insert new account
	}
	$stmt->close();
} else {
	// Something is wrong with the sql statement, check to make sure accounts table exists with all 3 fields.
	echo 'Could not prepare statement!';
}
$con->close();
?>

Replace:

// Insert new account

With:

// Username doesnt exists, insert new account
if ($stmt = $con->prepare('INSERT INTO accounts (username, password, email) VALUES (?, ?, ?)')) {
	// We do not want to expose passwords in our database, so hash the password and use password_verify when a user logs in.
	$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
	$stmt->bind_param('sss', $_POST['username'], $password, $_POST['email']);
	$stmt->execute();
	echo 'You have successfully registered, you can now login!';
} else {
	// Something is wrong with the sql statement, check to make sure accounts table exists with all 3 fields.
	echo 'Could not prepare statement!';
}

This will insert a new account into our accounts table.

Remember in our Login System we used the password_verify function? As you can see in the code above we use the password_hash function, this will encrypt the user’s password using the one-way algorithm — this will prevent your users passwords from being exposed if for somehow your database becomes vulnerable.

That’s basically all we need to do to register accounts on our website.

Part 3: Create your own Registration System using PHP and MySql

Nov 28, 2022   //   by h05t5cr1pt3r   //   Blog  //  No Comments

3. Creating the Database and setting-up Tables

You can skip this step if you followed the Secure Login System Tutorial.

For this part, you will need to access your MySQL database, either using phpMyAdmin or your preferred MySQL database management application.

If you’re using phpMyAdmin then follow these instructions:

  • Navigate to: http://localhost/phpmyadmin/
  • Click the Databases tab at the top
  • Under Create database, type in phplogin in the text box
  • Select utf8_general_ci as the collation
  • Click Create

You can use your own database name, but for this tutorial, we’ll use phplogin.

What we need now is an accounts table that will store all our accounts (usernames, passwords, emails, etc).

Click the database on the left side panel (phplogin) and execute the following SQL statement:

CREATE TABLE IF NOT EXISTS `accounts` (
	`id` int(11) NOT NULL AUTO_INCREMENT,
  	`username` varchar(50) NOT NULL,
  	`password` varchar(255) NOT NULL,
  	`email` varchar(100) NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

On phpMyAdmin this should look like:

http://localhost/phpmyadmin/

phpMyAdmin Accounts Table

The above SQL statement code will create the accounts table with the columns idusernamepassword, and email.

Pages:1234»