How do you know which variable matters and which is null?

I need to check the input that I will need in order to later check the database for its presence in the table. The input number must be a mobile number (all digits, 10 max len) or an email address. This is below what I did

<?php

$credential = '9999999999';

if (ctype_digit($credential)) {
        $mobile_number = $credential;
        echo 'Mobile: '. $mobile_number;
    } elseif (filter_var($credential, FILTER_VALIDATE_EMAIL)) {
        $email = $credential;
        echo 'Email: '.$email;
    }

conclusion when $credential = '9999999999';

Mobile: 9999999999

conclusion when $credential = 'abc@gmail.com';

Email: abc@gmail.com

Two questions,

  • Is there a better way to do this? For example, using preg_match.

  • , . , $credential = $_POST['credential'];, . , ? , , , - null.

+4
3

filter_var($credential, FILTER_VALIDATE_EMAIL) , , .

, . , , .., . , . SO . . ? ? , , .

:

if (ctype_digit($credential) && strlen($credential)==10) {
    $mobile_number = $credential;
    echo 'Mobile: '. $mobile_number;
} elseif (filter_var($credential, FILTER_VALIDATE_EMAIL)) {
    $email = $credential;
    echo 'Email: '.$email;
}

:

if (preg_match('/^\d{10}$/',$credential)) {
    $mobile_number = $credential;
    echo 'Mobile: '. $mobile_number;
} elseif (filter_var($credential, FILTER_VALIDATE_EMAIL)) {
    $email = $credential;
    echo 'Email: '.$email;
}

. , .

+3
+2

PHP

if (preg_match('/^\d{10}$/', $string) || filter_var($string, FILTER_VALIDATE_EMAIL)) {
    //valid
} else {
    //invalid
}

however, you should also check this on the client side to make sure the request is not even sent to the server if the value is invalid.

EDIT:

if (preg_match('/^\d{10}$/', $string)) {
    //valid mobile
} else if (filter_var($string, FILTER_VALIDATE_EMAIL)) {
    //valid email
} else {
    //invalid
}
+1
source

Source: https://habr.com/ru/post/1690925/


All Articles