How to verify any email with php - php

I am working with a form. Where user enters their email, I can validate the email through regex. But what I need is like this. After searching, I found a solution here. The as it checks the MX record of the email. But still it does not work for me fine, because when I gave a rough email like : ahhhhhhhhhhhhhhhhh#yahoo.com my form accepted it, and when I gave the same email on the other website, it rejected the email. It might be the problem with my logic I don't know, below is my code where I am verifying the email.
if(isset($_GET["saveData"])){
$_appid = $_GET["appid"];
$_name = $_GET["name"];
$_email = $_GET["email"];
$_pass = $_GET["pass"];
$_applink = $_GET["applink"];
function domain_exists($email, $record = 'MX'){
list($user, $domain) = explode('#', $email);
return checkdnsrr($domain, $record);
}
if(!empty($_appid) && !empty($_name) && !empty($_email) && !empty($_pass) && !empty($_applink)){
if(!domain_exists($_email) OR !filter_var($_email, FILTER_VALIDATE_EMAIL)) {
echo "email_prb";
} else{
$sl = "SELECT * FROM fb_data WHERE useremail = '$_email' OR fbappid = '$_appid' ";
$count = $con->query($sl);
if(mysqli_num_rows($count)>0){
echo "exists";
}else{
$in = "INSERT INTO fb_data VALUES(NULL,'$_name','$_email','$_pass','$_applink','$_appid',1,0)";
if ($con->query($in)) {
echo "Inserted";
}
}
}
} else{
echo "empty";
}
}

Kindly Use mysqli or Pdo.. your code is vulnerable to sql injection, try to add mysql escape. but i have rewritten your PHP below without changing query.
Filter validate email will check for the correct email format, so you dont need checking for #. but if you filter the #example.com you need a custom filter for that.
<?php
if(isset($_GET["saveData"])){
$_appid = $_GET["appid"];
$_name = $_GET["name"];
$_email = $_GET["email"];
$_pass = $_GET["pass"];
$_applink = $_GET["applink"];
function domain_exists($email, $record = 'MX'){
list($user, $domain) = explode('#', $email);
return checkdnsrr($domain, $record);
}
if(!empty($_appid) && !empty($_name) && !empty($_email) && !empty($_pass) && !empty($_applink)){
if((!domain_exists($_email)) && (!filter_var($_email, FILTER_VALIDATE_EMAIL))) {
echo "email_prb";
} else{
$sl = "SELECT * FROM `fb_data` WHERE `useremail` = '$_email' OR `fbappid` = '$_appid' ";
$count = $con->query($sl);
if(mysqli_num_rows($count)>0){
echo "exists";
}else{
$in = "INSERT INTO `fb_data` VALUES(NULL,'$_name','$_email','$_pass','$_applink','$_appid',1,0)";
if ($con->query($in)) {
echo "Inserted";
}
}
}
} else{
echo "empty";
}
}
?>

on this part of your code
if(!domain_exists($_email) OR !filter_var($_email, FILTER_VALIDATE_EMAIL))
change the "OR" to ||. Like this
if(!domain_exists($_email) || !filter_var($_email, FILTER_VALIDATE_EMAIL))

Related

depending on condition show error message in php

i have code like this
<?php
require('../config.php');
require_once($CFG->dirroot . '/user/editlib.php');
$errorMessage = '';
$successMessage = '';
if(isset($_SESSION['successMessage']))
{
$successMessage = $_SESSION['successMessage'];
unset($_SESSION['successMessage']);
}
if (isset($_POST['register'])) {
if(!preg_match("/^(?=.*[0-9])(?=.*[a-z])(\S+)$/i", $_POST['password']))
{
$errorMessage="don't allow spaces";
}
$errors = array();
$data = array();
$chk_sql = "SELECT * FROM {user} u where username = ?";
if (!empty($chk_sql) ) {
$errorMessage='Username already taken';
}
if(!$chk_username = $DB->get_record_sql($chk_sql, array($_POST['username'])) )
{
$secret = $_POST['secret'];
$access_code_sql = "SELECT * FROM {accesscode} WHERE random_no= ? and status=1";
if($chk_secret = $DB->get_record_sql($access_code_sql, array($secret)) )
{
if ( $chk_secret->used >= $chk_secret->number ) {
$errorMessage = "your access code limit completed..";
}
else
{
$cadminid = $chk_secret->cadmin_id;
$clientid = $chk_secret->clientid;
$DB->execute("UPDATE {accesscode} SET used = used+1 WHERE random_no = '$secret'");
$insert_record = new stdClass();
$insert_record->firstname = $_POST['firstname'];
$insert_record->lastname = $_POST['lastname'];
$insert_record->username = $_POST['username'];
$insert_record->secret = $secret;
$insert_record->password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$insert_record->timecreated = time();
$insert_record->maildigest = $cadminid;
$insert_record->maildisplay = $clientid;
$insert_record->idnumber = 1;
$insert_record->mnethostid = 1;
$insert_record->confirmed = 1;
$insert_record->email = $_POST['email'];
if($result = $DB->insert_record('user', $insert_record))
{
$_SESSION['successMessage'] = "record created successfully";
header('Location: register.php');
}
else
$errorMessage = "error! can you please try again";
}
}
else
$errorMessage = "your access code is wrong..";
}
}
?>
so i want to write condition like another if condition
if ( $chk_secret->status='0' ) {
$errorMessage = "your access code deactivated..";
}
if not they can register
i tried..but i didn't get idea where i have to add that if..
before i have condition like if number>used it will show some error message like your accesscode limit completed
can anyone help me..
thanks in advance..
= is for value assignment
== is compare two operands
so you need to change
if ( $chk_secret->status='0' ) {
to
if ( $chk_secret->status=='0' ) {
UPDATE:
your query SELECT * FROM {accesscode} WHERE random_no= ? and status=1
which means it going to return only status == 1
you can check with number of rows returned is ZERO then through status zero error message.
Or else
Get rows only based on random_no exists and then check status key

While submitting a form I check if there the e-mail isnt already in the sql database but it doesnt work

I'm using a fetchAll and a for loop to do the trick. In the if statement with $validate as result I tried numbers, boolean and now strings to get the result. Nothing worked so far. Here is my code:
$groep_naam = $_POST['groep'];
$naam = $_POST['naam'];
$adres = $_POST['adres'];
$mail2 = $_POST['mail2'];
$pass1 = md5($_POST['pass1']);
$pass2 = md5($_POST['pass2']);
$select = $db->prepare("SELECT * FROM deelnemers");
$select->execute();
$result = $select->fetchAll();
$len = count($result);
for ($x=0;$x<$len;$x++) {
$mail1 = $_POST['mail1'];
$db_mail = $result[$x][mail];
if ($db_mail != $mail1) {
$validate = "true";
}
if ($db_mail == $mail1) {
$validate = "false";
}
}
if (isset($_POST['submit'])) {
if ($mail1 == $mail2 && $pass1 == $pass2) {
if ($validate == "true") {
$add = $db->prepare("INSERT INTO deelnemers (groep_naam, naam, adres, mail, pass, rechten) VALUES ('$groep_naam', '$naam', '$adres', '$mail1', '$pass1', 'user')");
$add->execute();
} if ($validate == "false") {
echo '
<script>
$("#duplicateEntry").modal("show");
</script>
';
}
You are doing it wrong. Instead of fetching all emails, you should do a query to check if that particular email exists in db.
Pseudocode:
$select = $db->prepare("SELECT 1 FROM deelnemers WHERE mail = :email");
$select->bindValue(':email', $_POST['mail1']);
$select->execute();
$validate = $select->rowCount() > 0; //rowCount/rowExists/whatever to check if the query returned anything
Looking at your current code, probable mistake is on line
$db_mail = $result[$x][mail];
It probably should've been
$db_mail = $result[$x]['mail'];
Another thing, you loop through all emails comparing them with the one from request, so even if you find the one email matching it, later in another loop you rewrite your $validate value.

Login works on local server not on live server

My login of admin panel and member panel both works fine on local server, But on Live server member panel doesn't work. As admin and member panel both use same connection file so it means connection file works fine. More over when we fill wrong user or password it says
Invalid User or Password
But when we login with correct user or password it returns back with no indication of error.
My login file upper php part is:
<?php
include_once("../init.php");
$msg='';
?>
<?php
if(isset($_POST['click']))
{
$user = trim($_POST['user']);
$pass = trim($_POST['pass']);
if(($user =='' )|| ($pass=='')){
$msg ='Please enter username & password';
}else{
$npass = ($pass);
$qry = mysql_query("select * from user where user ='$user'");
if(mysql_num_rows($qry)==0) {
$msg ='Invalid UserName';
} else {
$res = mysql_fetch_array($qry);
if($res['pass']==$npass) {
$_SESSION['USE_USER'] = $res['user'];
$_SESSION['SID'] = $res['id'];
$_SESSION['USE_NAME'] = $res['fname'];
$_SESSION['USE_SPONSOR'] = $res['sponsor'];
$_SESSION['PACKAGE_AMT'] = $res['package_amt'];
$_SESSION['ADDRESS'] = $res['address'];
$_SESSION['PHONE'] = $res['phone'];
$_SESSION['JOIN_DATE'] = $res['join_date'];
header('location: main.php');
} else {
$msg ='Invalid Password';
}
}
}
}
?>
My header file main.php is
<?php
include_once("../init.php");
validation_check($_SESSION['SID'],MEM_HOME_ADMIN);
$msg='';
$dir ='../'.USER_PIC;
$sId = $_SESSION['SID'];
?>
Session is started from another file called function.php
<?php
function logout($destinationPath)
{
if(count($_SESSION))
{
foreach($_SESSION AS $key=>$value)
{
session_unset($_SESSION[$key]);
}
session_destroy();
}
echo "<script language='javaScript' type='text/javascript'>
window.location.href='".$destinationPath."';
</script>";
}
function validation_check($checkingVariable, $destinationPath)
{
if($checkingVariable == '')
{
echo "<script language='javaScript' type='text/javascript'>
window.location.href='".$destinationPath."';
</script>";
}
}
function realStrip($input)
{
return mysql_real_escape_string(stripslashes(trim($input)));
}
function no_of_record($table, $cond)
{
$sql = "SELECT COUNT(*) AS CNT FROM ".$table." WHERE ".$cond;
$qry = mysql_query($sql);
$rec = mysql_fetch_assoc($qry);
$count = $rec['CNT'];
return $count;
}
//drop down
function drop_down($required=null, $text_field, $table_name, $id, $name, $cond, $selected_id=null)
{
$qry = mysql_query("SELECT $id, $name FROM $table_name WHERE $cond ORDER BY $name ASC");
$var = '';
if(mysql_num_rows($qry)>0)
{
$var = '<select id="'.$text_field.'" name="'.$text_field.'" '.$required.'>';
$var .='<option value="">--Choose--</option>';
while($r = mysql_fetch_assoc($qry))
{
$selected = '';
if($selected_id==$r[$id]){
$selected = 'selected="selected"';
}
$var .='<option value="'.$r[$id].'" '.$selected.'>'.$r[$name].'</option>';
}
$var .='</select>';
}
echo $var;
}
function uploadResume($title,$uploaddoc,$txtpropimg)
{
$upload= $uploaddoc;
$filename=$_FILES[$txtpropimg]['name'];
$fileextension=strchr($filename,".");
$photoid=rand();
$newfilename=$title.$photoid.$fileextension;
move_uploaded_file($_FILES[$txtpropimg]['tmp_name'],$upload.$newfilename);
return $newfilename;
}
function fRecord($field, $table, $cond)
{
$fr = mysql_fetch_assoc(mysql_query("SELECT $field FROM $table WHERE $cond"));
return $fr[$field];
}
function get_values_for_keys($mapping, $keys) {
$output_arr = '';
$karr = explode(',',$keys);
foreach($karr as $key) {
$output_arr .= $mapping[$key].', ';
}
$output_arr = rtrim($output_arr, ', ');
return $output_arr;
}
function getBaseURL() {
$isHttps = ((array_key_exists('HTTPS', $_SERVER)
&& $_SERVER['HTTPS']) ||
(array_key_exists('HTTP_X_FORWARDED_PROTO', $_SERVER)
&& $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')
);
return 'http' . ($isHttps ? 's' : '') .'://' . $_SERVER['SERVER_NAME'];
}
function request_uri()
{
if ($_SERVER['REQUEST_URI'])
return $_SERVER['REQUEST_URI'];
// IIS with ISAPI_REWRITE
if ($_SERVER['HTTP_X_REWRITE_URL'])
return $_SERVER['HTTP_X_REWRITE_URL'];
$p = $_SERVER['SCRIPT_NAME'];
if ($_SERVER['QUERY_STRING'])
$p .= '?'.$_SERVER['QUERY_STRING'];
return $p;
}
preg_match ('`/'.FOLDER_NAME.'(.*)(.*)$`', request_uri(), $matches);
$tableType = (!empty ($matches[1]) ? ($matches[1]) : '');
$url_array=explode('/',$tableType);
?>
Moreover I have created user id by words and time like LH1450429882 and column is verture type. I think this has no effect on login.
I think main errors come from function.php Sorry for a long code, but I tried to cover all parts of coding.
I am struggling with this code from a week. Thanks in advance for help.
This is probably a bug that error_reporting will show off. Always use it in development mode, to catch some carelessness errors and ensure the code's clarity.
ini_set('display_errors',1);
error_reporting(E_ERROR | E_WARNING | E_PARSE);
By implementing code ini_set('display_errors',1); error_reporting(E_ERROR | E_WARNING | E_PARSE); I got the error of header ploblem on line 6 in login php I have removed ?> and
Now my working code in login.php is
<?php
include_once("../init.php");
$msg='';
if(isset($_POST['click']))
{
$user = trim($_POST['user']);
$pass = trim($_POST['pass']);
if(($user =='' )|| ($pass=='')){
$msg ='Please enter username & password';
}else{
$npass = ($pass);
$qry = mysql_query("select * from user where user ='$user'");
if(mysql_num_rows($qry)==0) {
$msg ='Invalid UserName';
} else {
$res = mysql_fetch_array($qry);
if($res['pass']==$npass) {
$_SESSION['USE_USER'] = $res['user'];
$_SESSION['SID'] = $res['id'];
$_SESSION['USE_NAME'] = $res['fname'];
$_SESSION['USE_SPONSOR'] = $res['sponsor'];
$_SESSION['PACKAGE_AMT'] = $res['package_amt'];
$_SESSION['ADDRESS'] = $res['address'];
$_SESSION['PHONE'] = $res['phone'];
$_SESSION['JOIN_DATE'] = $res['join_date'];
header('location: main.php');
} else {
$msg ='Invalid Password';
}
}
}
}
?>

trying to convert mysql select statement to PDO

I'm trying to convert from an old MySQL library to PDO.
In order to read the data with my old MySQL code I use:
$assoc = mysql_fetch_assoc($exeqr);
With PDO I'm trying to do that with a foreach like I have on my code using PDO, but its not working...
Can you see something wrong here??
My OLD ode using MySQL:
<?php
if(isset($_POST['sendLogin']))
{
$f['email'] = mysql_real_escape_string($_POST['email']);
$f['pass'] = mysql_real_escape_string($_POST['password']);
if(!$f['email'] || !valMail($f['email']))
{
echo 'Email empty or invalid';
}
else if(strlen($f['pass']) <8 || strlen($f['pass'])>12)
{
echo 'pass must have between 8 and 12 chars!';
}
else
{
$autEmail = $f['email'];
$autpass = $f['pass'];
$query = "SELECT * FROM users where email= '$autEmail'";
$exeqr = mysql_query($query) or die(mysql_error());
$assoc = mysql_fetch_assoc($exeqr);
if(mysql_num_rows($exeqr) == 1 )
{
if($autEmail == $assoc['email'] && $autpass == $assoc['pass'])
{
$_SESSION['assoc'] = $assoc;
header('Location:'.$_SERVER['PHP_SELF']);
}
else
{
echo ' wrong password';
}
}
else
{
echo 'email does no exist';
}
}
}
And the new code I am trying to convert using PDO:
<?php
if(isset($_POST['sendLogin']))
{
$f['email'] = mysql_real_escape_string($_POST['email']);
$f['pass'] = mysql_real_escape_string($_POST['password']);
if(!$f['email'] || !valMail($f['email']))
{
echo 'Email empty or invalid';
}
else if(strlen($f['pass']) <8 || strlen($f['pass'])>12)
{
echo 'pass must have between 8 and 12 chars!';
}
else
{
$autEmail = $f['email'];
$autpass = $f['pass'];
$searchEmail = $pdo->prepare("SELECT * FROM users where email=:email");
$searchEmail->bindValue(":email,$autEmail");
$searchEmail->execute;
$num_rows = $searchEmail->fetchColumn();
$result = $searchEmail->fetch(PDO::FETCH_OBJ);
if($num_rows == 1)
{
if($autEmail == $result['email'] && $autpass == $result['pass'])
{
$_SESSION['result'] = $result;
header('Location:'.$_SERVER['PHP_SELF']);
}
else
{
echo ' wrong password';
}
}
else
{
echo 'email does no exist';
}
}
}
Warning: PDOStatement::bindValue() expects at least 2 parameters, 1 given in $searchEmail->bindValue(":email,$autEmail");
You need to move your ", currently it's including the variable as well as the parameter name resulting in you not passing in the variable to bind to said parameter (which is why you are getting the error telling you you haven't passed in enough arguments).
$searchEmail = $pdo->prepare("SELECT * FROM users where email = :email");
$searchEmail->bindValue(":email", $autEmail);
Notice: Undefined property: PDOStatement::$execute in $searchEmail->execute;
You've forgotten the () brackets from execute(), so PHP is looking for the property of the PDO class called execute instead of the function call.
$searchEmail->execute();
(thanks Prix)
Edit
Your question is now about how to replace this:
$assoc = mysql_fetch_assoc($exeqr);
... with a PDO equivalent. In the manual, there is an example:
$assoc = $searchEmail->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP);
Note: fetchAll() is for fetching multiple results. If you're expecting only one result (which you might be, but you aren't limiting your query so it's feasible to return multiple results), you should just use fetch():
$assoc = $searchEmail->fetch(PDO::FETCH_ASSOC);

Best way to use this IF statement and && Logical expression

require_once('mysqli_connect.php');
$errors = array();
if(empty($_POST['senFirstName']) && empty($_POST['senLastName'])
&& empty($_POST['recFirstName']) && empty($_POST['recLastName'])
&& empty($_POST['proName']) && empty($_POST['proWeight'])
&& empty($_POST['traNo']) && empty($_POST['shipDate'])
&& empty($_POST['deliDate'])) {
$errors[] = 'Please make sure you type in all the information.';
}
else {
$sfn = mysqli_real_escape_string($dbc, trim($_POST['senFirstName']));
$sln = mysqli_real_escape_string($dbc, trim($_POST['senLastName']));
$rfn = mysqli_real_escape_string($dbc, trim($_POST['recFirstName']));
$rln = mysqli_real_escape_string($dbc, trim($_POST['recLastName']));
$pn = mysqli_real_escape_string($dbc, trim($_POST['proName']));
$pw = mysqli_real_escape_string($dbc, trim($_POST['proWeight']));
$traNo = mysqli_real_escape_string($dbc, trim($_POST['traNo']));
$shipDate = mysqli_real_escape_string($dbc, trim($_POST['shipDate']));
$deliDate = mysqli_real_escape_string($dbc, trim($_POST['deliDate']));
$status = mysqli_real_escape_string($dbc, trim($_POST['status']));
$shiptype = mysqli_real_escape_string($dbc, trim($_POST['shiptype']));
}
if(empty($errors)) { // If everything's OK.
$query = "SELECT traNo, CONCAT(recFirstName, ' ', recLastName) AS recieverName, proName, CONCAT(senFirstName, ' ', senLastName) AS senderName, status, shiptype FROM tracking, rel_tracking_reciever, reciever, product, sender
WHERE traNo='$traNo' AND tracking.traId = rel_tracking_reciever.traId AND reciever.recId = rel_tracking_reciever.recId AND tracking.proId = product.proId AND tracking.senId = sender.senId";
$result = #mysqli_query($dbc, $query);
$num = mysqli_num_rows($result);
if ($num) { // tracking number was found
while ($row = mysqli_fetch_array($result,MYSQL_ASSOC)) {
echo '<div id="error">';
echo "<p>This tracking number <b>{$row['traNo']}</b> has already been assigned to <b>{$row['senderName']}</b></p>\n";
echo '</div>';
}
mysqli_free_result ($result); // Free up the resources.
}
1) I want to validate input box with the multiple IF conditions using && Logical expression but instead, it submits empty forms into the database.
Note: I purposely left out the shipment and status input box because the options cannot be empty by default.
2) Is there a way i can generate the tracking number automatically without typing it manually. I have tried GUID but am not getting it.
Thanks..
You have to set ids that you want to validate - there is no complain.
You can do this with:
$ids = array('senFirstName', 'senLastName', 'recFirstName', 'recLastName' /* ... and more */);
$valid = true;
foreach ( $ids as $id ) {
if ( empty($_POST[$id]) ) {
$valid = false;
}
}
if ( $valid === true ) {
// everything's ok
} else {
$errors[] = 'Please make sure you type in all the information.';
}
You need ||, not && if you want to test, if one is empty.
Otherwise you would proove, if all of them are empty.
(Sorry for bad english)
if(empty($_POST['senFirstName']) || empty($_POST['senLastName']) ...

Categories