Search code examples
phpregexvalidationexplodestrpos

checking whether domain of the email compatible with the company name


I'm trying to implement a code to validate company email. When a user enters company and work email they both should be compatible with each other. As an instance, if a user who's working at QUT registers with the system when he/she enters the company as QUT, then the email domain must be @qut.edu.au. The code below shows the method I've implemented. But for some reason, there is a logical error in the code which gives "You must enter a valid email".(Supposed to be triggered when company name is not included in domain).But it pops up every time it runs. Any help would be highly appreciated. Thank you!

    <?php
require_once $_SERVER['DOCUMENT_ROOT'].'/abp/core/init.php';
include 'includes/head.php';
include 'includes/navigation.php';
$email = ((isset($_POST['email']))?sanitize($_POST['email']):'');
$email = trim($email);
$password = ((isset($_POST['password']))?sanitize($_POST['password']):'');
$password = trim($password);
$company_name = ((isset($_POST['company_name']))?sanitize($_POST['company_name']):'');
$company_name = trim($company_name);
$errors = array();
**$domain = array_pop(explode('@', $email));**


if($_POST){
        // form validation
        if(empty($_POST['email']) || empty($_POST['password'])){
          $errors[] = 'You must provide email and password.';
        }else {
          //validlate email

          **if (strpos( $domain, $company_name) !== true) {**
            $errors[] = 'You must enter a valid email.';


          }else{
            // check if email exist in the databse
            $query = "SELECT * FROM users WHERE email=?";
            $stmt = $db->prepare($query);
            $stmt->bind_param("s", $email);
            $stmt->execute();
            $stmt->store_result();

Solution

  • your code reads

    if(strpos(something, something) !== true) {
        error message
    }
    

    strpos can never ever return true only an int or FALSE, hence you always get an error message. it's in the docs too.

    the correct version would be:

    if(strpos($haystack, $needle) === false) {
         //errormessage
    }
    

    (additionally the concept of matching an email address to a company name is not a good idea as mentioned abundantly in the comments)