Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /*Connect to a the database, or it should be in a connect.php file that is included here*/
- $servername = "localhost";
- $username = "root";
- $password = "";
- $dbname = "chris";
- // Create connection
- $mysqli = new mysqli($servername, $username, $password, $dbname);
- /* check connection */
- if (mysqli_connect_errno()) {
- printf("Connect failed: %s\n", mysqli_connect_error());
- exit();
- }
- /*The main register function*/
- function register ($mysqli)
- {
- /*Check if the request is POST method*/
- if($_POST)
- {
- // Required field names
- $required = array('first_name', 'last_name', 'email', 'password', 'password_verify');
- // Loop over field names, make sure each one exists and is not empty
- foreach($required as $field)
- {
- if (empty($_POST[$field]))
- {
- return errorMsg($field." Can't be empty!");
- }
- }
- /*Escape string to avoid sql injection*/
- $first_name = $mysqli->real_escape_string($_POST['first_name']);
- $last_name = $mysqli->real_escape_string($_POST['last_name']);
- $email = $mysqli->real_escape_string($_POST['email']);
- $password = $mysqli->real_escape_string($_POST['password']);
- $password_verify= $mysqli->real_escape_string($_POST['password_verify']);
- /*Check if e-mail address syntax is valid or not*/
- $email = filter_var($email, FILTER_SANITIZE_EMAIL); // Sanitizing email(Remove unexpected symbol like <,>,?,#,!, etc.)
- if (!filter_var($email, FILTER_VALIDATE_EMAIL))
- {
- return errorMsg('Invalid Email!');
- }
- /*validate password is confirmed*/
- if($password != $password_verify)
- {
- return errorMsg('Passwords don\'t match!');
- }
- /*Hash password, never ever try to store passwords as plain text in database*/
- $password = password_hash( $password, PASSWORD_BCRYPT, array('cost' => 11));
- /*Get all records associated with that email*/
- $result = $mysqli->query("SELECT * FROM users WHERE email='$email'");
- $exists = $result->num_rows;
- /*Check if the email is already registered*/
- if($exists!=0)
- {
- return errorMsg('The email is already registered, Please try another one!');
- }
- /*Insert query*/
- $query = $mysqli->query("INSERT INTO users(first_name, last_name, email, password) values ('$first_name', '$last_name', '$email', '$password')");
- /*Success*/
- if($query)
- {
- return successMsg("You have been Successfully Registered");
- }
- else
- {
- /*Failure*/
- errorMsg(mysqli_error($conn));
- }
- }
- }
- /*Function that returns the error message in JSON format*/
- function errorMsg($msg)
- {
- print(json_encode(["status" => "error",'message'=> $msg]));
- }
- /*Function that returns the success message in JSON format*/
- function successMsg($msg)
- {
- print(json_encode(["status" => "success",'message'=> $msg]));
- }
- /*Main register function call*/
- register($mysqli);
- $mysqli->close();
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement