Email validation, Am I doing the right thing? - php

I am writing some PHP code where I end it with a email validation checking. Can someone review it and confirm if it's a good solution?
<?php
function isTrue($var) {
return (isset($var)) ? TRUE : FALSE;
}
function len($str) {
$i;
for($i=0; isTrue($str[$i]); $i++) {
/* count me */
}
return $i;
}
function parsMe($str) {
$at; $dot; $isvalid=0; $isnotvalid=0;
for ( $at=0; isTrue($str[$at]); $at++) {
if ( $str[$at] == "#" ) {
for ( $dot=$at+1; isTrue($str[$dot]); $dot++ ) {
if ( $str[$dot] == "." ) $isvalid += 1;
if ( $str[$dot] =="#" || $str[len($str)-1] == "#" || $str[len($str)-1] == "." ) {
die("Error email entered");
}
}
}
if ( $str[$at] != "#" ) {
$isnotvalid+=1;
}
}
/* exit cond */
if ( $isnotvalid == len($str) ) die("Error mail usage");
else if ( $isvalid == 0 ) die("Error mail");
else echo "Mail is OK ";
}
$eml = "dotdot#com.";
parsMe($eml);
?>
parsMe() should produce error.

There are built in functions for checking validity of emails:
<?php
$email ='dotdot#com';
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
echo "E-mail is not valid";
}else{
echo "E-mail is valid";
}
?>

Related

Multiple if(strlen) with different value?

So I am trying to have two if(strlen) but the top one is the only one that displays even if it's the call sign error? Updated to have the full list of code.
final public function register()
{
global $core, $template, $_CONFIG;
if(isset($_POST['register']))
{
unset($template->form->error);
$template->form->setData();
$name = $template->form->reg_name;
if($this->validName($name))
{
if(!$this->nameTaken($name))
{
if(!$this->emailTaken($template->form->reg_email))
{
if(strlen($template->form->reg_password) >= 8)
{
if(strlen($template->form->reg_callsign) > 2)
{
if(!$this->callTaken($template->form->reg_callsign))
{
if($this->isBanned($_SEVER['REMOTE_ADDR']) == false)
{
if($template->form->reg_email == $template->form->reg_rep_email)
{
if($this->validEmail($template->form->reg_email))
{
$this->addUser($name, $core->hashed($template->form->reg_password), $template->form->reg_email, $template->form->reg_callsign, 1, $core->hashed);
$this->turnOn($name);
header('Location: ' . $_CONFIG['game']['url'] . '/application');
exit;
}
else
{
$template->form->error = 'Oops, email seems to be invalid.';
return;
}
}
else
{
$template->form->error = 'Email & repeated email doesn\'t match.';
return;
}
}
else
{
$template->form->error = 'Sorry, it appears you are banned.<br />';
$template->form->error .= 'Reason: ' . $this->getReason($_SERVER['REMOTE_ADDR']);
return;
}
}
else
{
$template->form->error = 'That call sign is already taken!';
return;
}
}
else
{
$template->form->error = 'Your call sign must be 3 digits.';
return;
}
}
else
{
$template->form->error = 'Make sure your password has 8 characters or more.';
return;
}
}
else
{
$template->form->error = 'Oops, this email is already registered.';
return;
}
}
else
{
$template->form->error = 'Oops, this name:<b>' . $name . '</b> is taken.';
return;
}
}
else
{
$template->form->error = 'Oops, this name is invalid.';
return;
}
}
}
What I would like to happen is where if(strlen($template->form->reg_password) >= 8) (error message) would only show up if the password is shorter than 8 and the if(strlen($template->form->reg_callsign) > 2) (error message) to show up if they are only putting 1-2 numbers and not 3

server side data validation with nesting

I cannot figure out why my nesting here is not working. Whenever I run this it goes straight to 'Incorrect password' (with all the fields blank) even though the condition about string length that proceeds it, is false. A reading of 'Email and password are required' is what I want to happen first. THEN if the email doesn't contain an # sign, the # notification, THEN the password notification. But it keeps jumping over my previous if statements. I know the nesting must be wrong, and I've re-arranged it many times. The only way it works is to remove the # verification line completely, but I need to have it.
if ( isset($_POST['who']) && isset($_POST['pass']) ) {
if ( strlen($_POST['who']) < 1 || strlen($_POST['pass']) < 1 ) {
$failure = "E-mail and password are required";
}
if(stripos($_POST['who'],'#') === false && strlen($_POST['who'] > 1)) {
$failure = "E-mail must have an at-sign (#)";
}
else {
$check = hash('md5', $salt.$_POST['pass']);
if ( $check == $stored_hash ) {
// Redirect the browser to auto.php
header("Location: auto.php?name=".urlencode($_POST['who']));
return;
} else {
$failure = "Incorrect password";
}
}
}
you need to put 2nd if condition in else block. think about when password was blank but email was entered. it will bypass 2nd if block and go to else use like blow code
if ( isset($_POST['who']) && isset($_POST['pass']) ) {
if ( strlen($_POST['who']) <= 1 || strlen($_POST['pass']) < 1 ) {
$failure = "E-mail and password are required";
}
else {
if(stripos($_POST['who'],'#') === false && strlen($_POST['who'] > 1)) {
$failure = "E-mail must have an at-sign (#)";
}
else {
$check = hash('md5', $salt.$_POST['pass']);
if ( $check == $stored_hash ) {
// Redirect the browser to auto.php
header("Location: auto.php?name=".urlencode($_POST['who']));
return;
} else {
$failure = "Incorrect password";
}
}
}
}

complete form validation in php

I have this php code associated with a database and I need here to make a complete email and name validation
based on this code how can I do that because my code has some issues here
1)name key doesn't have (//) or any symbols to be a correct name
2)email key is valid email because what we did here just make ensure that there is # symbol and if I type the email hhhh#hhh.com or even without( .com ) it will be valid also ?!!
if(array_key_exists("submit",$_POST)){
$link = mysqli_connect("localhost","root","123456789","users");
if(mysqli_connect_error()){
die("There is a problem in connecting to database");
}
if(!$_POST['name']){
$error .="<p>Your Full name is required</p><br>";
}
if(!$_POST['email']){
$error .="<p>Your email address is required</p><br>";
}
if(!$_POST['password']){
$error .="<p>Your password is required</p><br>";
}
if($error !=""){
$error = "<p>There were errors in your form</p><br>".$error;
}
}
You can use this function for the validation:
function filtervariable($string,$type,$method) {
//function for sanitizing variables using PHPs built-in filter methods
$validEmail = false;
if ($method == 'sanitize') {
$filtermethod = 'FILTER_SANITIZE_';
} elseif ($method == 'validate') {
$filtermethod = 'FILTER_VALIDATE_';
} else {
return;
}
switch ($type) {
case 'email':
case 'string':
case 'number_int':
case 'int':
case 'special_chars':
case 'url':
$filtertype = $filtermethod.strtoupper($type);
break;
}
if ($filtertype == 'FILTER_VALIDATE_EMAIL' && !empty($string)) {
list($local,$domain) = explode('#',$string);
$localLength = strlen($local);
$domainLength = strlen($domain);
$checkLocal = explode('.',$domain);
if (($localLength > 0 && $localLength < 65) && ($domainLength > 3 && $domainLength < 256) && (checkdnsrr($domain,'MX') || checkdnsrr($domain,'A') || ($checkLocal[1] == 'loc' || $checkLocal[1] == 'dev' || $checkLocal[1] == 'srv'))) { // check for "loc, dev, srv" added to cater for specific problems with local setups
$validEmail = true;
} else {
$validEmail = false;
}
}
if (($filtertype == 'FILTER_VALIDATE_EMAIL' && $validEmail) || $filtertype != 'FILTER_VALIDATE_EMAIL') {
return filter_var($string, constant($filtertype));
} else {
return false;
}
}
And use it like this:
$email = filtervariable($registeremail,'email','validate');
It will return "true" on success and "false" on failure.

PHP - how i count numerical character and string character to check username length value?

how to count numerical character combine with string character in php? if i use strlen, thats only count string. I want limit username input value only 20 character, if i input 20 or more string only, this code work, but if i input (e.g : Admin123Admin123Admin123) thats not work, my validation input fail.
i have a code in yii 2 useraccount controller like this :
// new user
if ( $username != '' && $password != '' && intval($group) > 0 && !$exist)
{
$myFunctions = new userFunctions;
$exist = $myFunctions->isUserNameExist( $username );
$isValid = $myFunctions->isValidPassword( $password );
$checkUsername = strlen($username);
// $temp = str_split($username); // Convert a string to an array by each character
// // if don't want the spaces
// $temp = array_filter($temp); // remove empty values
// $checkUsername = count($temp);
if ( $isValid == 0 && !$exist)
{
$result = $myFunctions->saveNewUser( $username, $password, $group, $expired );
$error = ( $result ) ? 0 : 1;
}
else if( $exist )
{
$error = 3;
}
else $error = 2;
}
}
echo \yii\helpers\Json::encode(['result' => $result, 'error' => $error, 'checkUsername' => $checkUsername ]);
this is my code in view :
function saveNewUsers()
{
$.ajax({
type :'POST',
dataType : 'json',
data : { id: $('#hiUserID').val(), username : $('#txtUsername').val(), password: $('#txtPassword1').val(), group: $('#cbUserGroup').val(), expired: $('#cbExpired').val() },
url : '" . \Yii::$app->getUrlManager()->createAbsoluteUrl('useraccount/saveuser') . "',
success : function(response) {
if ( !response.result ) {
if ( response.error == 2 )
{
$('#errorMessageUser').html(DecodeEntities('{$myLabels[20]}.')).show();
}
else if( response.error == 3 )
{
$('#errorMessageUser').html(DecodeEntities('{$myLabels[56]}.')).show();
}
else if( response.checkUsername > 20)
{
$('#errorMessageUser').html(DecodeEntities('{$myLabels[57]}.')).show();
}
else $('#errorMessageUser').html(DecodeEntities('{$myLabels[22]}.')).show();
}
else {
$('#errorMessageUser').html('').hide();
$('#myUserModal').modal('hide');
$.pjax.reload({container:'#myPjax',timeout:false});
}
}
});
}
so, how to count numerical and string in php? i am really new in php thanks for helping and i hope suggestion from our programmers here. Sorry for my bad English.
i already found the answer, yes thanks for chris 85, strlen is not problem but the problem is in controller, this is i change my code :
if ( $username != '' && $password != '' && intval($group) > 0 && !$exist)
{
$myFunctions = new userFunctions;
$exist = $myFunctions->isUserNameExist( $username );
$isValid = $myFunctions->isValidPassword( $password );
$checkUsername = strlen($username);
// var_dump($checkUsername); die();
if ( $isValid == 0 && !$exist && $checkUsername <= 20)
{
$result = $myFunctions->saveNewUser( $username, $password, $group, $expired );
$error = ( $result ) ? 0 : 1;
}
elseif ($checkUsername > 20 )
{
$error = 99;
}
else if( $exist )
{
$error = 3;
}
else $error = 2;
}
and in the view like this :
function saveNewUsers()
{
$.ajax({
type :'POST',
dataType : 'json',
data : { id: $('#hiUserID').val(), username : $('#txtUsername').val(), password: $('#txtPassword1').val(), group: $('#cbUserGroup').val(), expired: $('#cbExpired').val() },
url : '" . \Yii::$app->getUrlManager()->createAbsoluteUrl('useraccount/saveuser') . "',
success : function(response) {
if ( !response.result ) {
if ( response.error == 2 )
{
$('#errorMessageUser').html(DecodeEntities('{$myLabels[20]}.')).show();
}
else if( response.error == 3 )
{
$('#errorMessageUser').html(DecodeEntities('{$myLabels[56]}.')).show();
}
else if( response.error == 99)
{
$('#errorMessageUser').html(DecodeEntities('{$myLabels[57]}.')).show();
}
else $('#errorMessageUser').html(DecodeEntities('{$myLabels[22]}.')).show();
}
else {
$('#errorMessageUser').html('').hide();
$('#myUserModal').modal('hide');
$.pjax.reload({container:'#myPjax',timeout:false});
}
}
});
}
thanks for helping, finally i get the answer.

PHP weird comparison

I've got two inputs in registration form, one with login, one with password. After calling AJAX I'm trying to validate those data and I'm using function below:
function test_input($data) {
if( $data == $_POST["login"] && $data == "" ){
$GLOBALS["message"] .= "<p>Empty login.</p>";
return;
}
elseif( $data == $_POST["pwd"] && $data == "" ){
$GLOBALS["message"] .= "<p>Empty password.</p>";
return;
}
echo 'Good job.';
}
When I click submit button without writing anything I've got answer:
Empty login
Empty login
When I write something in one of them or both of them validation's ok. Why?
Edit - Missing code:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$login = test_input($_POST["login"]);
$pwd = test_input($_POST["pwd"]);
if($message!= ""){
echo $message;
}
else{
echo 'OK';
}
}
Perhaps refactor it something like:
function test_input($data, $field) {
if( $field == "login" && $data == "" ){
return "<p>Empty login.</p>";
}
elseif( $field == "pwd" && $data == "" ){
return "<p>Empty password.</p>";
}
echo 'Good job.';
}
and
$message = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$message .= test_input($_POST["login"], "login");
$message .= test_input($_POST["pwd"], "pwd");
if($message!= ""){
echo $message;
}
else{
echo 'OK';
}
}

Categories