login with cpf or email in php

0

I'm having a problem when making a login system that the user must be able to authenticate through their e-mail or cpf.

I am doing the comparison with the value of the login field received, if it is number I do search with cpf and if not I do with email. See below:

 if (is_numeric($_POST['email_cpf'])) {
     //pesquisa com cpf
 }else{
     //pesquisa com e-mail
 }

This works, the problem is that when the user enters the cpf login field in the format with 000.000.000-00 separators, this is given as a string and therefore searches the email.

I made a function to remove the tabs, but this is bad because if the email for example has traces or dots, they will also be removed

How do I resolve this?

    
asked by anonymous 23.09.2017 / 15:07

2 answers

1

Before you verify that the user typed only numbers, remove the periods and dashes using the str_replace as follows:

$login = $_POST['email_cpf'];
$login = str_replace('.', '', $login);
$login = str_replace('-', '', $login);

At this point you will already have what the user typed without points or dashes in the $login variable. If the variable contains only numbers you check by the CPF, otherwise, you get what the user initially typed and checks the email:

if (is_numeric($login)) {
    //pesquisa com cpf
}else{
    $login = $_POST['email_cpf'];
    //pesquisa com e-mail
}

You can also do this in a simpler way:

if (is_numeric(str_replace(array('.', '-'), $_POST['email_cpf']))) {
    //pesquisa com cpf
}else{
    //pesquisa com e-mail
}
    
23.09.2017 / 15:16
1

With regular expression, you can do something like:

if (preg_match("/^\d{3}\.?\d{3}\.?\d{3}-?\d{2}$/", $valor)) {
    // É CPF
} else {
    // É e-mail
}

So, the separator characters will be optional, you can either enter the CPF with only numbers or with the tabs, as long as it has the 11 digits.

With the characters ^ and $ , the beginning and end of the expression are defined, ensuring that there is nothing more than the CPF in value. \d{x} creates groups of x digits.

  

See working at Ideone .

    
23.09.2017 / 15:35