how to get value from text file in php - php

I have script that make comparison between value from page php and data store in txt file, and then it will do some special code.
Content of txt file (account.txt)
F: user pass { expire=date; afexpire=date; email=email#gmail.com; Country=Germani; visit_from=none; ip=none; hosted=none }
F: mike fghg58g { expire=2016-05-24; afexpire=2015-5-24 17; email=mike#gmail.com; Country=uk; visit_from=none; ip=none; hosted=none }
F: adresson f5849dh9d { expire=2016-11-01; afexpire=2015-11-01 17; email=mike#gmail.com; Country=Germani; visit_from=none; ip=none; hosted=none }
my script
<?php
$user = "Mike"; // user that is inserted in page form
$email = "mike#gmail.com"; // email that is inserted in page form
$userFile = "Mike"; // user in txt file
$emailFile = "mike#gmail.com"; // email in txt file
if( $user == $userFile && $email == $emailFile ) {
echo "The user and email is used";
} elseif( $user == $userFile && $email != $emailFile ) {
echo "The user is used";
} else{
// do special code
}
I don't know how to read file txt from path and change user and email in file to value to make comprison
$userFile = "Mike"; // user in txt file (account.txt)
$emailFile = "mike#gmail.com"; // email in txt file (account.txt)
This is my spcial script that make output in (account.txt)
<?php
if (isset($_POST["g-recaptcha-response"])) {
$name = $_POST['name'];
$user = $_POST['user'];
$pass = $_POST['pass'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$country = $_POST['country'];
$plan = $_POST['plan'];
$quantity = $_POST['quantity'];
$payment = $_POST['payment'];
$reciever = $_POST['reciever'];
$captcha = $_POST['g-recaptcha-response'];
$message_user = $_POST['message'];
$serverip = $_POST['REMOTE_ADDR'];
$to = 'sup.alphas#gmail.com';
$parts = explode("#", $email);
$sufemail = $parts[0];
// $sufemail = substr(strstr($email, '#'), 1); for domain//
$subject_form = 'Request new account by '.$sufemail.'';
// Check if name has been entered
if (!$_POST['name']) {
$errName = 'Please enter your name';
}
// Check if name has been entered
if (!$_POST['user']) {
$errUser = 'Please enter your username';
}
// Check if name has been entered
if (!$_POST['pass']) {
$errPass = 'Please enter your password';
}
// Check if email has been entered and is valid
if (!$_POST['email']) {
$errEmail = 'Please enter a valid email address';
}
if (!$_POST['country']) {
$errCountry = 'Please enter your country';
}
if (!$_POST['plan']) {
$errPlan = 'Please enter your plan';
}
if (!$_POST['quantity']) {
$errQuantity = 'Please enter your quantity';
}
if (!$_POST['payment']) {
$errPayment = 'Please enter your method of payment';
}
if (!$_POST['g-recaptcha-response']) {
$errCaptcha = 'Please enter captcha';
}
// If there are no errors, send the email
if (!$errName && !$errUser && !$errPass && !$errEmail && !$errCountry && !$errPlan && !$errQuantity && !$errPayment && !$errCaptcha) {
// Start Create new account //
$dateadd = date('Y-m-d', strtotime("$plan"));
$datetry = date('Y-m-d H', strtotime("+1 day"));
$handle = fopen('/usr/www/users/alphacz/alpha/phpm/account.cfg', 'a');
fwrite($handle, 'F: ' . $_POST["user"] . ' ' . $_POST["pass"] . ' { expire=' . $datetry . '; afexpire=' . $dateadd . '; email=' . $email . '; Country=' . $country . '; visit_from=none; ip=none; hosted=' . $_POST['REMOTE_ADDR'] . " }\r\n");
fclose($handle);
Help me, please
Thank you

You can check a needle in a haystack which is your account file here.
username pattern is "F: {user} pass {..."
email pattern is "; email={email}; Country="
Note: You must also think that this excample check keywords incasesensitive, so
when searching and inserting, you should convert keywords to lowercase
$user_used = userExists('Mike');
$email_used = emailExists('mike#gmail.com');
if ($user_used && $email_used)
{
echo 'The user and email is used';
}
elseif ($user_used) {
echo 'The user is used';
}
else
{
//do special code
}
function userExists($user)
{
return (exec('grep ' . escapeshellarg('F: ' . $user . ' ') . ' {file-path}'));
}
function emailExists($email)
{
return (exec('grep ' . escapeshellarg('; email=' . $email . ';') . ' {file-path}'));
}

We could fix your current code to read from the file, but instead we first rewrite your code which writes to the file, so it will be way easier to read from the file afterwards.
(Since you only show part of the script which writes to the file I can only rewrite that part.)
Changes
JSON format for the file
Instead of writing your data into the file in a custom format we will save the data in JSON format. You can easily work with JSON in PHP since it has built-in functions to work with it.
$_POST ↔ $_SERVER ?
At some point you use $_POST['REMOTE_ADDR'], but I assume that you wanted to use $_SERVER["REMOTE_ADDR"]. See: http://php.net/manual/en/reserved.variables.server.php.
!$XY
While using !$XY as condition may work sometimes it isn't very practical. Since it simply negates the value and then checks if it is a truthy or falsey value and should enter the if statement or not. So I would recommend you to use !empty() to check if your input is set and is not empty.
Code
<?php
if (isset($_POST["g-recaptcha-response"])){
$checkPostIndices = ["name", "user", "pass", "email", "phone", "country", "plan", "quantity", "payment", "reciever", "g-recaptcha-response", "message"];
$data = [];
$errors = [];
$errorMessages = [
"name" => "Please enter your name",
"user" => "Please enter your username",
"pass" => "Please enter your password",
"email" => "Please enter a valid email address",
"phone" => "Please enter your phone number",
"country" => "Please enter your country",
"plan" => "Please enter your plan",
"quantity" => "Please enter your quantity",
"payment" => "Please enter your method of payment",
"reciever" => "Please eneter a reciever",
"g-recaptcha-response" => "Please enter captcha",
"message" => "Please enter a message",
];
foreach($checkPostIndices as $index){
if(!empty($_POST[$index])){
$data[$index] = $_POST[$index];
} else {
$errors[] = $errorMessages[$index];
}
}
$data["serverip"] = $_SERVER["REMOTE_ADDR"];
$to = "sup.alphas#gmail.com";
$sufemail = explode("#", $data["email"])[0];
$subject_form = "Request new account by " . $sufemail;
if(!empty($errors)){
$fileData = array_intersect_key($data, ["user", "pass", "email", "country", "serverip"]);
$fileData["dateadd"] = date("Y-m-d", strtotime($data["plan"]));
$fileData["datetry"] = date("Y-m-d H", strtotime("+1 day"));
$file = file_get_contents("/usr/www/users/alphacz/alpha/phpm/account.cfg");
$file = empty($file) ? [] : json_decode($file, TRUE);
$file[] = $fileData;
file_put_contents("/usr/www/users/alphacz/alpha/phpm/account.cfg", json_encode($file));
}
}
?>
So now after that your data should be stored in JSON like this:
[
{"key":"data"}
//...
]
And then you can easily use json_decode() to decode your file into an array, loop through the array and check if the email and user are already used.
Code
<?php
$user = "Mike";
$email = "mike#gmail.com";
$file = file_get_contents("/usr/www/users/alphacz/alpha/phpm/account.cfg");
$data = json_decode($file, TRUE);
foreach($data as $v){
if($v["user"] == $user && $v["email"] == $email){
echo "Email and user already used";
}
}
?>

Related

Validation for registration page in PHP

I have a registration page and I want to validate it. I have this code:
$msg = "";
$msg_3 = "";
if(isset($_POST['submit'])) {
$First_Name = ((isset($_POST['First_Name']))?sanitize($_POST['First_Name']):'');
$Last_Name = ((isset($_POST['Last_Name']))?sanitize($_POST['Last_Name']):'');
$email = ((isset($_POST['email']))?sanitize($_POST['email']):'');
$confirm_email = ((isset($_POST['confirm_email']))?sanitize($_POST['confirm_email']):'');
$mobile_number = ((isset($_POST['mobile_number']))?sanitize($_POST['mobile_number']):'');
$password = ((isset($_POST['password']))?sanitize($_POST['password']):'');
$confirm_password = ((isset($_POST['confirm_password']))?sanitize($_POST['confirm_password']):'');
$gender = ((isset($_POST['gender']))?sanitize($_POST['gender']):'');
$day = ((isset($_POST['day']))?sanitize($_POST['day']):'');
$month = ((isset($_POST['month']))?sanitize($_POST['month']):'');
$year = ((isset($_POST['year']))?sanitize($_POST['year']):'');
$insurance = ((isset($_POST['insurance']))?sanitize($_POST['insurance']):'');
$agree = ((isset($_POST['agree']))?sanitize($_POST['agree']):'');
$sql = "SELECT email, mobile_number FROM customers WHERE email ='$email' OR mobile_number ='$mobile_number'";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
if ($email == $row['email']) {
$msg = "<span class='text-danger'>The email address you've entered is already associated with another account.
<br>Please sign in or enter a different email address. Please try again.</span>";
} if ($mobile_number == $row['mobile_number']) {
$msg_3 = "<span class='text-danger'>The mobile phone number you've entered is already associated with another account.
<br>Please sign in or enter a different number. Please try <br>again.</span>";
}
}
} else {
// Insert into database and send email
}
Now how could I validate each field if it is empty and print different messages under each field in this nested if and while. I'm getting confused.
If you will use same names in db as in form you could use something like this:
$keys = ['gender', 'email', 'mobile_number']; //etc
$errors = [];
while ($row = $result->fetch_assoc()) {
array_walk($keys, function ($key) {
if (empty($row[$key])) {
$errors[] = "$key is required"
}
if (isset($_POST[$key]) && $_POST[$key] == $row[$key]) {
$errors[] = "please enter $key"
}
})
}
if you need to have more customized messages you might map keys to error text like:
$keys = ['gender' => ['equal' => 'your error message', 'empty' => 'empty msg'], 'email' => ['equal' => 'email validation error', 'empty' => 'error msg 2']]; //etc
$errors = [];
while ($row = $result->fetch_assoc()) {
array_walk($keys, function ($errorMsg, $key) {
if (isset($_POST[$key]) && $_POST[$key] == $row[$key]) {
$errors[$key] = $errorMsg['equal'];
}
if (empty($row[$key])) {
$errors[$key] = $errorMsq['empty'];
}
})
}
Do not repeat
Prevent SQL Injection
You can do something like this.
<?php
if(isset($_POST['submit'])) {
$errors = [];
function getPost($postIndex, $errorMessage = '') {
global $errors;
if (!empty( $_POST[$postIndex] )) {
$value = $_POST[$postIndex];
return $value;;
} else {
$errors[$postIndex] = $errorMessage;
return null;
}
}
function validateString($s) {
return htmlspecialchars(trim($s));
}
getPost('First_Name', 'Firstname Cannot Be Empty');
getPost('Last_Name', 'Lastname cannot be empty');
$email = getPost('email', 'Your Error Message');
getPost('confirm_email', 'Your Error Message');
$mobile_number = getPost('mobile_number', 'Your Error Message');
getPost('password', 'Your Error Message');
getPost('confirm_password', 'Your Error Message');
getPost('gender', 'Your Error Message');
getPost('day', 'Your Error Message');
getPost('month', 'Your Error Message');
getPost('year', 'Your Error Message');
getPost('insurance', 'Your Error Message');
getPost('agree', 'Your Error Message');
$stmt = $mysqli -> prepare('SELECT email, mobile_number FROM customers WHERE email =? OR mobile_number =?');
if (
$stmt &&
$stmt -> bind_param('ss', $email, $mobile_number) &&
$stmt -> execute() &&
$stmt -> store_result() &&
$stmt -> bind_result($dbEmail, $dbMobileNumber) &&
$stmt -> fetch()
) {
if ($email == $dbEmail) {
// email equal error message
} if ($mobile_number == $row['mobile_number']) {
// mobile number equal error message
}
}
if (count($errors)) {
echo "You have an error";
}
// or get the post index in your HTML form and show the error message there
// <?php isset($errors['firstName']) ? echo $errors['firstname'] : null;
}

How to write the test case in PHP and push into multidimensional array

Here i am having three field like name,email,mobile. here what i am doing means i writing the test case for those fields in PHP,lets take name field condition like
empty condition
name should not be number
name minimum 3 charector
suppose above conditions failed means i have to push to Failed Condition array, i tried i am not getting my expected results,kindly any one update my code
My code
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
if(!empty($name) && !empty($email) && !empty($phone)){
// Scenario = 1
if(!preg_match("/^[a-zA-Z'-]+$/", $name)){
$namevalidation['status'] = "Fail" ;
$namevalidation['Failed Condition'][]['name'][]['Name should not be a number'] = "Condition Failed" ;
}
// Scenario = 2
$namelength = strlen($name);
if($namelength > 2){
}else{
$namevalidation['Failed Condition'][]['name'][]['Minimum Charector'] = "Condition Failed" ;
}
if(!empty($namevalidation)){
echo json_encode($namevalidation);
}
}else{
$mandatory['status'] = "Fail" ;
$mandatory['Error Message'] = "Mandatory fields mismatch";
if(empty($name)){
$mandatory['Required Fields'][] = "Name is mandatory";
}
if(empty($email)){
$mandatory['Required Fields'][] = "Email is mandatory";
}
if(empty($phone)){
$mandatory['Required Fields'][] = "Phone is mandatory";
}
if(!empty($mandatory)){
echo json_encode($mandatory);
}
}
?>
Expected Output
{
"status": "Fail",
"Failed Condition": [
{
"name": [
{
"Name should not be a number": "Condition Failed"
},
{
"Minimum Charector": "Condition Failed"
}
]
}
]
}
But i am getting out put like this
{
"status": "Fail",
"Failed Condition": [
{
"name": [
{
"Name should not be a number": "Condition Failed"
}
]
},
{
"name": [
{
"Minimum Charector": "Condition Failed"
}
]
}
]
}
You used [] in your code that creates new arrays instead of appending the previously created array.
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
if(!empty($name) && !empty($email) && !empty($phone)){
// Scenario = 1
if(!preg_match("/^[a-zA-Z'-]+$/", $name)){
$namevalidation['status'] = "Fail" ;
$namevalidation['Failed Condition'][0]['name'][]['Name should not be a number'] = "Condition Failed" ;
}
// Scenario = 2
$namelength = strlen($name);
if($namelength > 2){
}else{
$namevalidation['Failed Condition'][0]['name'][]['Minimum Charector'] = "Condition Failed" ;
}
if(!empty($namevalidation)){
echo json_encode($namevalidation);
}
}else{
$mandatory['status'] = "Fail" ;
$mandatory['Error Message'] = "Mandatory fields mismatch";
if(empty($name)){
$mandatory['Required Fields'][] = "Name is mandatory";
}
if(empty($email)){
$mandatory['Required Fields'][] = "Email is mandatory";
}
if(empty($phone)){
$mandatory['Required Fields'][] = "Phone is mandatory";
}
if(!empty($mandatory)){
echo json_encode($mandatory);
}
}
However your current code creates different main structure of the Json if a different input is made.
Say the name is 'ab' then your code does not add the $namevalidation['status'] = "Fail" ;.
My suggestion is that you in "scenario 2" do a isset() check and if it's not set then you set it.
if($namelength > 2){
}else{
$namevalidation['Failed Condition'][0]['name'][]['Minimum Charector'] = "Condition Failed" ;
if(!isset($namevalidation['status'])) $namevalidation['status'] = "Fail" ;
}

faulty error output in my registration form

I am trying to make a registration form and doing some checks before running SQL queries, but as i test and try to generate multiple errors, i am getting only the error that comes first, or sometimes no error at all. I am unable to locate where i have made error.
The following is the code in PHP.
//function to filter only phone numbers
function get_phone($number) {
return preg_replace('#[^0-9]#', '', $number);
}
//function to take only alphabets.
function get_alpha($alphabets){
return preg_replace('#[^a-z]#', '', $alphabets);
}
//function to check email.
function isValidEmail($email){
if (strlen ($email) > 50){
$errors[] = 'email address too long, please use a shorter email address..!';
} else {
return (filter_var($email, FILTER_VALIDATE_EMAIL));
}
}
function output_errors($errors){
$output = array();
foreach($errors as $error) {
$output[] = '<li>' . $error . '</li>';
}
return '<ul>' . implode('', $output) . '</ul>';
}
if (empty($_POST) === false) {
//store the text box field names of the form to local variables.
$cust_name = $_POST['name1'];
$cust_email = $_POST['email'];
$cust_phone = $_POST['phone'];
$cust_addr1 = $_POST['addr1'];
$cust_addr2 = $_POST['addr2'];
$cust_city = $_POST['city'];
$cust_state = $_POST['state'];
$cust_country = $_POST['country'];
$username = $_POST['uname'];
$password = $_POST['passwd'];
$cnf_passwd = $_POST['cnf_passwd'];
$sec_que = $_POST['sec_que'];
$sec_ans = $_POST['sec_ans'];
//sanitize the inputs from the users end.
$cust_name = sanitize($username);
$cust_phone = get_phone($cust_phone);
$cust_addr1 = sanitize($cust_addr1);
$cust_addr2 = sanitize($cust_addr2);
$cust_city = get_alpha($cust_city);
$cust_state = get_alpha($cust_state);
$cust_country = get_alpha($cust_country);
$username = sanitize($username);
$password = md5($password);
$cnf_passwd = md5($cnf_passwd);
$sec_que = sanitize($sec_que); //put up dropdown menu
$sec_ans = sanitize($sec_ans);
$cust_email = isValidEmail($cust_email);
//check for error handling in form data
//1. check for empty fields,
if ($cust_name == "" || $cust_phone == "" ||
$cust_addr1 == "" || $username == "" ||
$password == "" || $cnf_passwd == "" ||
$sec_que == "" || $sec_ans == ""
) {
$errors[] = 'No blank fields allowed, please fill out all the required fields..!';
//2.check for field lengths
} else if (strlen($cust_name) < 3 || strlen($cust_name > 20)) {
$errors[] = 'The name length should be between 3 to 20, please check & correct..!';
//3. check for phone number length
} else if (strlen($cust_phone) < 10 || strlen($cust_phone) > 11) {
$errors[] = 'The phone number must be 10 or 11 digits..!';
//4. check for address input lengths.
} else if (strlen($cust_addr1) < 5 || strlen($cust_addr1) > 50) {
$errors[] = 'Please provide a valid address..to serve you better..!';
//5. check if the password fields content match.
//length is not checked because the entered values will be converted to MD5 hash
// of 32 characters.
} else if ($password != $cnf_passwd) {
$errors[] = 'The passwords do not match. Please enter your passwords again..!';
// 6. check for length of the security answers.
} else if (strlen($sec_ans) < 5 || strlen($sec_ans) > 50) {
$errors[] = 'Please enter a proper security answer..!';
} //7. check for valid email address
else if($cust_email == false){
$errors[] = 'The email address you entered is not valid, please check and correct..!';
} else {
execute the SQL queries and enter the values in the database.
echo 'GOOD...TILL NOW..!!!';
}
} else {
$errors [] = 'No data received, Please try again..!!';
}
if(empty($errors) === false) {
?>
<h2>The Following errors were encountered:</h2>
<?php
echo output_errors($errors); //output the errors in an ordered way.
}
?>
When you use this structure:
if () {
} else if () {
} else if () {
}
// etc.
then only one condition can be satisfied. As soon as one of those if conditions is true, the rest of the else if blocks and the final else block are ignored.
If your conditions aren't mutually exclusive, put them in their own separate blocks:
if () {
}
if () {
}
if () {
}
// etc.

Select case with array

How can I write a select case with an array to check form validation?
this is my code:
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
$array = array($name,$email,$message);
switch($array[]) {
case empty($array[0]):
error = "name";
break;
case empty($array[1]):
error = "email";
break;
case empty($array[2]):
error = "message";
}
Then, I would like to write code to have this result:
if name is empty:
"Please fill in your name"
if email is empty:
"Please fill in your email"
if name and email is empty:
"Please fill your name and email"
if name and email and message is empty:
"Please fill in your name, email and message"
You want to concat your messages, so better use if statements:
$error = "Please fill in: ";
if (empty($array[0]))
$error .= "name ";
if (empty($array[1]))
$error .= "email ";
if (empty($array[2]))
$error .= "message ";
The .= will concat the string to the existing one.
Try this for a grammatically correct solution:
$empty = array();
$fields = array('name', 'email', 'message');
foreach ($fields as $key => $value){
if(empty($_POST[$value])) $empty[] = $value;
}
$error_msg = '';
$count = count($empty);
$cnct = ', ';
if ($count > 0){
$error_msg = 'Please fill in your ';
}
foreach ($empty as $key => $value){
if ($key == $count - 2){
$cnct = ' and ';
}elseif($key == $count - 1){
$cnct = '.';
}
$error_msg .= $value.$cnct;
}
You can simply try:
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
$error="Please fill in your ";
$array = array('name'=>$name,'email'=>$email,'message'=>$message);
foreach($array as $key=>$value){
if(empty($value)){
$error.=','.$key;
}
}
You can't use a variable expression in case statement of switch block.
A switch case must have a constant expression in many languages including php. So, something like a variable or function call doesn't work.
You better use conditionals for this.
Your code is also missing $ symbol for variable error.
Do this instead:
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
$array = array($name,$email,$message);
$error="Please fill in your ";
if(empty($array[0])){
$error.= "\nname";
}
if(empty($array[1])){
$error.="\nemail";
};
if(empty($array[2])){
$error.= "\nmessage";
}
echo $error;
You should simply write:
$error = "Please fill in: ";
if (empty($array[0]))
$error.= "name ";
if (empty($array[1]))
$error.= "email ";
if (empty($array[2]))
$error.= "message";
A switch isn't made for what you want to do.

Validate Mobile number in php form

I want to validate mobile number of 10 digits and also add a prefix of 0 when I enter into the database.
<?php
include ('database_connection.php');
$citystate = $_POST['citystate'];
$serviceprovider = $_POST['serviceprovider'];
$accept = $_POST['accept'];
if (isset($_POST['formsubmitted'])) {
$error = array(); //Declare An Array to store any error message
if (isset($_POST['checkbox'])) {
$mumbai = (in_array("mumbai", $_POST['checkbox']) ? 1 : 0);
$pune = (in_array("pune", $_POST['checkbox']) ? 1 : 0);
$banglore = (in_array("banglore", $_POST['checkbox']) ? 1 : 0);
$mysore = (in_array("mysore", $_POST['checkbox']) ? 1 : 0);
}
if ($mumbai + $pune + $banglore + $mysore == 0) {
$error[] = 'Please check atleast one SMS center';
}
if ($accept != 1) {
$error[] = 'Please check terms ';
}
if (empty($_POST['mobileno'])) {//if no name has been supplied
$error[] = 'Please Enter a Mobile Number '; //add to array "error"
}
if (empty($_POST['mobileno'])) {//if no name has been supplied
$error[] = 'Please Enter a Mobile Number '; //add to array "error"
} else {
$mobile = $_POST['mobileno']; //else assign it a variable
/* if( preg_match("^[0-9]{10}", $mobile) ){
}
else {
$error[] = 'Your Mobile No is invalid ';
} */
}
if (empty($_POST['fname'])) {//if no name has been supplied
$error[] = 'Please Enter a First name '; //add to array "error"
} else {
$fname = $_POST['fname']; //else assign it a variable
}
if (empty($_POST['lname'])) {//if no name has been supplied
$error[] = 'Please Enter a Last name '; //add to array "error"
} else {
$lname = $_POST['lname']; //else assign it a variable
}
if (empty($_POST['email'])) {
$error[] = 'Please Enter your Email ';
} else {
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['email'])) {
//regular expression for email validation
$email = $_POST['email'];
} else {
$error[] = 'Your EMail Address is invalid ';
}
}
if (empty($_POST['passwd1'])) {
$error[] = 'Please Enter Your Password ';
} else {
$password = $_POST['passwd1'];
}
if (empty($_POST['passwd2'])) {
$error[] = 'Please Verify Your Password ';
} else {
$password = $_POST['passwd2'];
}
if ($_POST["passwd1"] != $_POST["passwd2"]) {
$error[] = 'Password does not match';
}
if (empty($error)) { //send to Database if there's no error ' //If everything's OK...
// Make sure the mobile no is available:
$query_verify_mobileno = "SELECT * FROM userdtls WHERE mobileno = '$mobile'";
$result_verify_mobileno = mysqli_query($dbc, $query_verify_mobileno);
if (!$result_verify_mobileno) {//if the Query Failed ,similar to if($result_verify_mobileno==false)
echo ' Database Error Occured ';
}
if (mysqli_num_rows($result_verify_mobileno) == 0) { // IF no previous user is using this number .
// Create a unique activation code:
//$activation = md5(uniqid(rand(), true));
$query_insert_user = "INSERT INTO userdtls ( mobileno, serviceprovider, pass, fname, lname, email, citystate, MUM, PUN, BNG, MYS ) VALUES ( '" . $mobile . "', '" . $serviceprovider . "', '" . $password . "', '" . $fname . "', '" . $lname . "', '" . $email . "', '" . $citystate . "','" . $mumbai . "', '" . $pune . "', '" . $banglore . "', '" . $mysore . "' )";
}
}
}
Now I get stuck in mobile number validation. I tried using regular expressions.
What I want to do is add a 10 digit phone number and make sure it is only digits or else give error and while entering the number to database I want to add a prefix to the mobile number of 0 so it should be like 0and10digitnumber
Try something like this :
$phoneNumber = $_POST['mobileno'];
if(!empty($phoneNumber)) // phone number is not empty
{
if(preg_match('/^\d{10}$/',$phoneNumber)) // phone number is valid
{
$phoneNumber = '0' . $phoneNumber;
// your other code here
}
else // phone number is not valid
{
echo 'Phone number invalid !';
}
}
else // phone number is empty
{
echo 'You must provid a phone number !';
}
Probably the most efficient and well-readable form would be to use the libphonenumber library from Google. PHP fork is available on GitHub. It can help you not only to validate number itself, but you can check country code with it or even know if some number is valid for specific country (this lib knows which number prefixes are valid for many countries). For example: 07700 900064 is valid GB number, but 09700 900064 is not, even if they have same length.
Here's how I would validate mobile phone number in your app:
$phoneNumber = $_POST['mobileno'];
$countryCode="GB";
if (!empty($phoneNumber)) { // phone number is not empty
$phoneUtil = \libphonenumber\PhoneNumberUtil::getInstance();
$mobileNumberProto = $phoneUtil->parse($phoneNumber, $countryCode);
if ($phoneUtil->isValidNumber($mobileNumberProto)) { // phone number is valid
//here you know that number is valid, let's try to format it without country code but with 0 at the beginning (national number format)
$phoneNumber = $mobileNumberProto->format($mobileNumberProto, PhoneNumberFormat::NATIONAL);
} else {
$error[] = 'Phone number not valid!';
}
} else {
$error[] = 'You must provide a phone number!';
}
$countryCode is two chars ISO 3166-1 code. You can check it for your country on Wikipedia.
For Indian Mobile Numbers it will be easiest
if(is_numeric($num)){
if($num>=1000000000 && $num<=9999999999){
$num="0".$num;
}
else{
echo "Invalid Mobile Number";
}
}
else{
echo "Hey Buddy mobile numbers are always in digits";
}
This idea struck me because of the willingness of finding easy and some short of mind because the number(1000000000 ) is the lowest numerical value(10 digits) and the number (9999999999) is a highest numerical value that can be used as a mobile number in India.
And one more thing code will run faster than other solutions.
Have you tried a regular expression like:
if( !preg_match("/^([0-1]-)?[0-9]{3}-[0-9]{3}-[0-9]{4}$/i", $phone) ) {
echo 'Please enter a valid phone number';
}
if(!ereg("^[7-9]{1}[0-9]{9}$", $mob)) { return false; }
Improving pravin tripathi's answer:
if(!ereg("^[7-9]{1}[0-9]{9}$", $mob)) { return false; }
since ereg() is deprecated, you could use
preg_match("/^[7-9]{1}[0-9]{9}$/i", $mobile_no)
This will help you validate a mobile number from India, since they are 10 digits and start with 7, 8 or 9 as of today. You could always change the pattern if new digits get introduced.

Categories