Looking for someone to help me with some basic PHP & MySQL

Ruan @ Webluno

Webluno Representative
Company Rep
Joined
Jun 28, 2020
Messages
85
Hi there,

I'm by no means a professional PHP developer but I was hoping that some of you could help me out, I'm willing to pay if required, hope someone can help out a friend for free :). Right now I have the following code: https://pastebin.com/LraQzy6g

Problem 1: The form <input> field is empty but every time you open or refresh the page it submits empty information.

Problem 2: My code is vulnerable to injections.

What I want to add:

1. Check if user already exists and redirect them to a URL
2. Check if user is banned (Banned = True) and redirect them to a URL
3. If the user is new, redirect them to a URL and store their data in the database.
 

Thor

Honorary Master
Joined
Jun 5, 2014
Messages
43,368
In a meeting, will check after this for you.

In the meantime, this might make the penny drop|


Ignore this part, its not really the right way, but conceptionally you should get the idea.

<code>
function clean_input($user_input) {
$user_input = trim($user_input);
$user_input = stripslashes($user_input);
$user_input = htmlspecialchars($user_input);
return $user_input;
}
</code>
 

Johnatan56

Honorary Master
Joined
Aug 23, 2013
Messages
30,309
Hi there,

I'm by no means a professional PHP developer but I was hoping that some of you could help me out, I'm willing to pay if required, hope someone can help out a friend for free :). Right now I have the following code: https://pastebin.com/LraQzy6g

Problem 1: The form <input> field is empty but every time you open or refresh the page it submits empty information.

Problem 2: My code is vulnerable to injections.

What I want to add:

1. Check if user already exists and redirect them to a URL
2. Check if user is banned (Banned = True) and redirect them to a URL
3. If the user is new, redirect them to a URL and store their data in the database.
Problem 2: use prepared statements https://www.php.net/manual/en/pdo.prepared-statements.php
Problem 1: Sticky form: https://tutorials.supunkavinda.blog/php/forms-sticky
 

Ruan @ Webluno

Webluno Representative
Company Rep
Joined
Jun 28, 2020
Messages
85
@Thor & @Johnatan56

Thanks for your replies, really appreciate it.

Even though I understand the examples you've sent me I still have no clue on how to implement it the way I need it to work.
 

Johnatan56

Honorary Master
Joined
Aug 23, 2013
Messages
30,309
@Thor & @Johnatan56

Thanks for your replies, really appreciate it.

Even though I understand the examples you've sent me I still have no clue on how to implement it the way I need it to work.
In regards to PDO: https://phpdelusions.net/pdo

In regards to form, you need to learn how to use same page forms (sticky form).
You need to submit the form somewhere, if you send it to your page, you need to check that the variable are set, if it is set, validate the form, if not, show the form.
I suggest you start with $GET and $POST: https://www.tutorialspoint.com/php/php_get_post.htm
 

Thor

Honorary Master
Joined
Jun 5, 2014
Messages
43,368
This is dirty, cause I don't want to spend toooo much free time, but you should get the idea here, obviously, you would collect more than just the RSA ID, to tie it to a person, etc.


Code:
<?php

$error_message = $success_message = '';

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

  A South African ID number is a 13-digit number which is defined by the following format: YYMMDDSSSSCAZ.

  The first 6 digits (YYMMDD) are based on your date of birth. 20 February 1992 is displayed as 920220.
  The next 4 digits (SSSS) are used to define your gender.  Females are assigned numbers in the range 0000-4999 and males from 5000-9999.
  The next digit (C) shows if you're an SA citizen status with 0 denoting that you were born a SA citizen and 1 denoting that you're a permanent resident.
  The last digit (Z) is a checksum digit – used to check that the number sequence is accurate using a set formula called the Luhn algorithm.

  */

  // validate the ID
  if(!verify_id_number($_POST['rsa_id'])) {
    $error_message = "Not a valid RSA ID Number";
  }

  if(!$error_message) {
    // connect database
    $db_servername = "localhost";
    $db_username = "xxx";
    $db_password = "xxx";

    try {
      $pdo = new PDO("mysql:host=$db_servername;dbname=myDB", $db_username, $db_password);
      // set the PDO error mode to exception
      $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch(PDOException $e) {
      echo "Connection failed: " . $e->getMessage();
    }  
   
    // check if the user exist & is not banned
    $stmt = $pdo->prepare('SELECT id FROM table WHERE rsa_id = :rsa_id');
    $stmt->bindParam(':rsa_id', $_POST['rsa_id']);
    $stmt->execute()
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if($user) {
      if($user['banned']) {
        redirect('some-banned-url-notice.html');
      }
      
      redirect('some-url-for-existing-users.html')
    }
    
    // insert into database
    $stmt = $pdo->prepare('INSERT INTO table (rsa_id) VALUES (:rsa_id)');
    $stmt->bindParam(':rsa_id', $_POST['rsa_id']);
    if($stmt->execute()) {
      $success_message = "Thank You";
    }
   
    // send alert to owner
  }

  // function - ID validator
  function verify_id_number($id_number, $gender = '', $foreigner = 0) {

     $validated = false;

     if (is_numeric($id_number) && strlen($id_number) === 13) {

        $errors = false;
        $num_array = str_split($id_number);

        // Validate the day and month
        $id_month = $num_array[2] . $num_array[3];
        $id_day = $num_array[4] . $num_array[5];

        if ( $id_month < 1 || $id_month > 12) {
           $errors = true;
        }

        if ( $id_day < 1 || $id_day > 31) {
           $errors = true;
        }

        // Validate gender
        $id_gender = $num_array[6] >= 5 ? 'male' : 'female';

        if ($gender && strtolower($gender) !== $id_gender) {
           $errors = true;
        }

        // Validate citizenship

        // citizenship as per id number
        $id_foreigner = $num_array[10];

        // citizenship as per submission
        if ( ( $foreigner || $id_foreigner ) && (int)$foreigner !== (int)$id_foreigner ) {
           $errors = true;
        }

        // Declare the arrays
        $even_digits = array();
        $odd_digits = array();

        // Loop through modified $num_array, storing the keys and their values in the above arrays
        foreach ( $num_array as $index => $digit) {

            if ($index === 0 || $index % 2 === 0) {
                $odd_digits[] = $digit;
            }

            else {
                $even_digits[] = $digit;
            }

        }

        // use array pop to remove the last digit from $odd_digits and store it in $check_digit
        $check_digit = array_pop($odd_digits);

        //All digits in odd positions (excluding the check digit) must be added together.
        $added_odds = array_sum($odd_digits);

        //All digits in even positions must be concatenated to form a 6 digit number.
        $concatenated_evens = implode('', $even_digits);

        //This 6 digit number must then be multiplied by 2.
        $evensx2 = $concatenated_evens * 2;

        // Add all the numbers produced from the even numbers x 2
        $added_evens = array_sum( str_split($evensx2) );

        $sum = $added_odds + $added_evens;

        // get the last digit of the $sum
        $last_digit = substr($sum, -1);

        /* 10 - $last_digit
         * $verify_check_digit = 10 - (int)$last_digit; (Will break if $last_digit = 0)
         * verify check digit is the resulting remainder of
         *  10 minus the last digit divided by 10
         */
         $verify_check_digit = (10 – (int)$last_digit) % 10;

        // test expected last digit against the last digit in $id_number submitted
        if ((int)$verify_check_digit !== (int)$check_digit) {
           $errors = true;
        }

        // if errors haven't been set to true by any one of the checks, we can change verified to true;
        if (!$errors) {
           $validated = true;
        }

     }

     return $validated;
  }
}

?>

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Example ID Form</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.3/css/bulma.min.css">
  </head>
  <body>
  <section class="section">
    <div class="container">
      <h1 class="title">Example Form</h1>
      <?php echo $error_message ?? $success_message ?? '' ?>
      <form action="" method="post">
        <div class="field">
          <label class="label">RSA ID Number</label>
          <div class="control">
            <input class="input" type="text" maxlength="13" minlength="13" name="rsa_id" placeholder="Enter your 13 Digit RSA ID Number">
          </div>
        </div>
      </form>
    </div>
  </section>
  </body>
</html>
 
Last edited:

Ruan @ Webluno

Webluno Representative
Company Rep
Joined
Jun 28, 2020
Messages
85
@Thor Thank you for the code, I've tried to private message you for some paid time :) but it seems your dm's are closed.
 

Thor

Honorary Master
Joined
Jun 5, 2014
Messages
43,368
Added the other part for question 1 to 3

PHP:
    // check if the user exist & is not banned
    $stmt = $pdo->prepare('SELECT id FROM table WHERE rsa_id = :rsa_id');
    $stmt->bindParam(':rsa_id', $_POST['rsa_id']);
    $stmt->execute()
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
   
    if($user) {
      if($user['banned']) {
        redirect('some-banned-url-notice.html');
      }
     
      redirect('some-url-for-existing-users.html')
    }

   // redirect function - exits
function redirect($url) {
    header("location: " . $url);
    exit();
}
 

GreGorGy

BULLSFAN
Joined
Jan 18, 2005
Messages
15,287
$stmt = $pdo->prepare('SELECT id FROM table WHERE rsa_id = :rsa_id'); $stmt->bindParam(':rsa_id', $_POST['rsa_id']); $stmt->execute() $user = $stmt->fetch(PDO::FETCH_ASSOC); if($user) { if($user['banned'])


Your SELECT is for id, not banned - this will fail.
 
Top