Can't insert my records into database? - php

This is my register form,after i add validation and my record can't insert into database.But my validation are working.If i exchange the code of validation and mysql,all can insert into database even if got error in my validation.
<?php
$fnameErr=$lnameErr=$passErr=$repassErr=$icErr=$emailErr=$add1Err=$add2Err=$postErr=$mobileErr="";
$fname=$lname=$pass=$repass=$ic=$email=$add1=$add2=$postcode=$mobile="";
if (isset($_POST['submitbtn']))
{
$fname = $_POST['bname'];
$lname = $_POST['lname'];
$pass = $_POST['bpass'];
$repass = $_POST['bconpass'];
$ic = $_POST['bic'];
$email = $_POST['bemail'];
$add1 = $_POST['badd1'];
$add2 = $_POST['badd2'];
$postcode = $_POST['bpostcode'];
$mobile = $_POST['bmobile'];
$country = $_POST['bcountry'];
$state = $_POST['bstate'];
$city = $_POST['bcity'];
$gen = $_POST['bgender'];
if($fname==""||$lname==""||$pass==""||$repass==""||$ic==""||$email==""||$add1==""||$add2==""||$country==""||$state==""||$postcode==""||$mobile==""||$city==""||$gen=="")
{
?>
<script type="text/javascript">
alert("Please fill in all the required informations.");
</script>
<?php
}
if (empty($errors) === true)
{
//bemail
if (filter_var($_POST['bemail'], FILTER_VALIDATE_EMAIL) === false)
{
$emailErr = 'A valid email address is required';
}
else if (email_exists($_POST['bemail']) === true)
{
$emailErr= 'Sorry, the email \'' . $_POST['bemail'] . '\' is already in use';
}
//fname xx
if (!preg_match("/^[A-Z][a-zA-Z -]+$/i",$_POST['bname']))
{
$fnameErr= 'Your first name cannot contain with any symbol and number';
}
//lname xx
if (!preg_match("/^[A-Z][a-zA-Z -]+$/i",$_POST['lname']) )
{
$lnameErr= 'Your last name cannot contain with any symbol and number';
}
//ic xx
if(!preg_match("/^\d{6}-\d{2}-\d{4}$/i", $_POST['bic']))
{
$icErr= 'Your ic cannot contain any character / must insert "-"';
}
//mobile xx
if (!preg_match("/^\d{3}-\d{7}$/i", $_POST['bmobile']))
{
$mobileErr= 'Phone must comply with this mask: 010-1111111 or 0111-1111111';
}
//password
if (strlen($pass) < 6)
{
$passErr = 'Your password must be at least 6 characters';
}
//re-password
if ($_POST['bpass'] !== $_POST['bconpass'])
{
$repassErr= 'Your password do not match';
}
//add1 xx
if (!preg_match("/^[a-zA-Z0-9 _.,:\"\']+$/i", $_POST['badd1']))
{
$add1Err = 'Address 1 must be only letters, numbers or one of the following';
}
//add2 xx
if (!preg_match("/^[a-zA-Z0-9 _.,:\"\']+$/i",$_POST['badd2']))
{
$add2Err= 'Address 2 must be only letters, numbers or one of the following';
}
//postcode xx
if (!preg_match("/^\d{5}$/i", $_POST['bpostcode']))
{
$postErr = 'Postcode must be 5 digits';
}
?>
<script type="text/javascript">
alert("Register have some error,please complete your informations.");
</script>
<?php
}
else
{
$result = mysql_query("select * from member where Member_Email='$email'");
if (mysql_num_rows($result)==0)
{
mysql_query("insert into member(Member_Name,Member_Lname,Member_Pass,Member_IC,Member_Email,Member_Street1,Member_Street2,Member_Country,Member_State,Member_Postcode,Member_HP,Member_City,Member_Gen) VALUES ('$fname','$lname','$pass','$ic','$email','$add1','$add2','$country','$state','$postcode','$mobile','$city','$gen')");
header("Location:all_login.php");
?>
<script type="text/javascript">
alert('Registered successfully!');
</script>
<?php
}
else
{
?>
<script type="text/javascript">
alert("email address already exists!");
</script>
<?php
}
}
}
?>
I'm so sorry with my poor english.

if (empty($errors) === true)
At no point before this in the code you posted do you define $errors. As per the PHP doc on that function, if the variable doesn't exist then empty() will return true. So unless you've left something out, your code will always enter the first part of the if statement and not the second.
I suspect that you want to change that line to if (empty($errors) === false) so that you only enter that part of your code if there is an error.

You should be really carefull for usage of variable like $test should be '.$test.' if string. Also you should use mysqli

Related

trying to compare two email fields - page blanks out

Right now, posting a snippet of what I wrote:
if (isset($_POST["email1"] != $_POST["email2"])) {
$email2Err = "please enter the same email address";
}
Every single time when I try to post the snippet above or a variation of it, it literally blanks out my page.
Question is, is the code I wrote above a good way to compare two email addresses via text fields?
And why does it blank out my entire page every time?
Here's a bit of further context if that's more helpful (let me know you want the entire page):
<?php
session_start(); //allows use of session variables
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["nights"])) {
$nightsErr = "# of nights are required";
} else {
$nights = test_input($_POST["nights"]);
}
if (empty($_POST["arrivals"])) {
$arrivalsErr = "Time of arrival is required";
} else {
$arrivals = test_input($_POST["arrivals"]);
}
if (empty($_POST["male"])) {
$maleErr = "# of people (gender female) required";
} else {
$male = test_input($_POST["male"]);
}
if (empty($_POST["female"])) {
$femaleErr = "# of people (gender female) required";
} else {
$female = test_input($_POST["female"]);
}
if (empty($_POST["rooms"])) {
$roomsErr = "# of rooms required";
} else {
$rooms = test_input($_POST["rooms"]);
}
if (empty($_POST["type"])) {
$typeErr = "type of rooms required";
} else {
$type = test_input($_POST["type"]);
}
if (empty($_POST["name"])) {
$nameErr = "name required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["address"])) {
$addressErr = "address required";
} else {
$address = test_input($_POST["address"]);
}
if (empty($_POST["zip"])) {
$zipErr = "zip required";
} else {
$zip = test_input($_POST["zip"]);
}
if (empty($_POST["telephone"])) {
$telephoneErr = "telephone required";
} else {
$telephone = test_input($_POST["telephone"]);
}
if (empty($_POST["email1"])) {
$email1Err = "email required";
} else {
$email1 = test_input($_POST["email1"]);
}
if (empty($_POST["email2"])) {
$email2Err = "email2 required";
} else {
$email2 = test_input($_POST["email2"]);
}
if (isset($_POST["email1"] != $_POST["email2"])) {
$email2Err = "please enter the same email address";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
This is failing you and isn't the right syntax for what you want to achieve:
if (isset($_POST["email1"] != $_POST["email2"]))
What you need to do is to first check if it is set then check if both are (not) equal to, but it's best to use !empty(), then check if it is not equal to:
if (!empty($_POST["email1"]) && !empty($_POST["email2"])) {
if ($_POST["email1"] != $_POST["email2"]) {
$email2Err = "Emails don't match. Please enter the same email address.";
}
}
Plus, make sure your form elements both have the right name attributes.
Also, a blank page can mean syntax errors.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
What you are doing is assigning by using a single equals to sign rather make it a double equals to sign, I mean ==
Try:
if (isset($_POST["email1"]) && isset($_POST["email2"])) {
if ($_POST["email1"] != $_POST["email2"]) {
$email2Err = "please enter the same email address";
}
}

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.

Can't figure out how to format this logic statement in PHP

I have some PHP I'm using to validate a form, and once the validation is complete the data from the form is sent into a database. My problem isn't actually a code problem, it's just I can't figure out how to write the if-else statement blocks.
Basically I have all these if statements that check if one of the form fields is empty or doesn't meed the criteria, and then a corresponding else statement which simply holds the data they've entered, so when the form reloads they don't have to enter it in again. At the moment I have an else statement at the end which posts all the data into my database when all the fields are validated - the problem is that I have one too many else statements and it gives me errors for this.
So I figure I have to wrap the whole block of code in one if-else statement, that would basically say if there are no errrors, do the else which sends the data to the database.
Basically I have the else done, I just need help to think of what condition to put for the if
Here's my code
//Define the database connection
$conn = mysqli_connect("danu.nuigalway.ie","myb1608re","fa3xul", "mydb1608") or die (mysql_error());
## Initialise varialbes to null ##
$nameError ="";
$emailError ="";
$categoryError ="";
$messageError ="";
$validName ="";
$validEmail ="";
$validMessage ="";
## On submitting form below function will execute ##
if(isset($_POST['submit']))
{
//assign details to be posted to variables
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$category = $_POST['category'];
//if name is less than 10 characters
if (empty($_POST["name"]) || strlen($name)<10)
{
$nameError ="* Name is too short";
}
else
{
$validName = $_POST["name"];
}
//if email is too short or is not the right format
if (empty($_POST["email"]) || !preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email) || strlen($email)<10 )
{
$emailError = "* You did not enter a valid email";
$validEmail = $_POST["email"];
}
else
{
$validEmail = $_POST["email"];
}
//if a category is not chosen
if (empty($_POST["category"])) {
$categoryError = "* Please select a category";
}
//if the message is left blank
if (empty($_POST["message"]) || strlen($message)<25 ) {
$messageError = "* Your message is too short";
}
else {
$validMessage = $_POST["message"];
}
//If there are no errors, email details to admin
else {
// variables to send email
$to = "e.reilly4#nuigalway.ie";
$subject = "Contact Form";
$body = "\r\n
Category: $_POST[category] \r\n
Message: $_POST[message] \r\n
Name: $_POST[name] \r\n
Email: $_POST[email]";
// Email Function
mail($to,$subject,$body);
//Insert the data into the database
$conn->query("INSERT INTO Assignment(Name, Email, Category, Message)VALUES('$name', '$email', '$category', '$message')", MYSQLI_STORE_RESULT);
$conn->close();
echo "sent to database";
}
}
?> <!-- End of PHP -->
Essentially I need to figure out another if statement to put just after the first one, but for the life of me I can't think of a condition to have. I thought what if I made a boolean that was false, and once all the data is correct it is put to true, but I can't figure out how to implement it. Just looking for any ideas on how to go about it
When I do validation, I personally try to come up with a function that will validate each value similarly. There are a few checks you should be doing as you go. Here is a restructure of what you have with some notations:
<?php
//Define the database connection
$conn = mysqli_connect("danu.nuigalway.ie","myb1608re","fa3xul", "mydb1608") or die (mysql_error());
// I usually build a simple validate function
// This is just an example, you can edit based on your needs
function validate_var($value = false,$type = 'str')
{
// Validate the different options
if(!empty($value) && $value != false) {
switch ($type) {
case ('str'):
return (is_string($value))? true:false;
case ('num') :
return (is_numeric($value))? true:false;
case ('email'):
return (filter_var($value,FILTER_VALIDATE_EMAIL))? true:false;
}
// This will just check not empty and string length if numeric
if((is_numeric($type) && !empty($value)) && (strlen($value) >= $type))
return true;
}
// Return false if all else fails
return false;
}
// On post, proceed
if(isset($_POST['submit'])) {
//assign details to be posted to variables
$name = $_POST['name'];
$email = $_POST['email'];
// Strip the message of html as a precaution
// Since you are not binding in your sql lower down, you should probably use
// htmlspecialchars($_POST['message'],ENT_QUOTES))
// or use the binding from the mysqli_ library to escape the input
$message = htmlspecialchars(strip_tags($_POST['message']),ENT_QUOTES));
// Do a "just-incase" filter (based on what this is supposed to be)
$category = preg_replace('/[^a-zA-Z0-9]/',"",$_POST['category']);
// Validate string length of 10
if(!validate_var($name,10))
$error['name'] = true;
// Validate email
if(!validate_var($email,'email'))
$error['email'] = true;
// Validate message length
if(!validate_var($message,25))
$error['message'] = true;
// Validate your category
if(!validate_var($category))
$error['category'] = true;
// Check if there are errors set
if(!isset($error)) {
// Use the filtered variables,
// not the raw $_POST variables
$to = "e.reilly4#nuigalway.ie";
$subject = "Contact Form";
$body = "\r\n
Category: $category \r\n
Message: $message \r\n
Name: $name \r\n
Email: $email";
// Don't just send and insert, make sure you insert into your databases
// on successful send
if(mail($to,$subject,$body)) {
//Insert the data into the database
$conn->query("INSERT INTO Assignment(Name, Email, Category, Message)VALUES('$name', '$email', '$category', '$message')", MYSQLI_STORE_RESULT);
$conn->close();
echo "sent to database";
}
else
echo 'An error occurred.';
}
else {
// Loop through errors cast
foreach($error as $kind => $true) {
switch ($kind) {
case ('name') :
echo "* Name is too short";
break;
case ('email') :
echo "* You did not enter a valid email";
break;
case ('category') :
echo "* Please select a category";
break;
case ('message') :
echo "* Your message is too short";
break;
}
}
}
}
?>

Validate Dynamically Form Data

I have a form field in my site that I need to know if the email that the user want to use isn't already used by other user.
I am using JavaScript and PHP for that but can make it work.
function validateEmail(){
//testing regular expression
var a = $("#email").val();
var filter = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,6}$/;
//if it's valid email
if(filter.test(a)){
if($("#email").val() != ""){
$.getScript("http://localhost/sisdelivery/validaEmail.php?&email="+$("#email").val(), function(){
if(resultadoEmail["email"] != ""){
email.addClass("error");
emailInfo.text("Email ja cadastrado!");
emailInfo.addClass("error");
return false;
}
else{
email.removeClass("error");
emailInfo.text("Email OK");
emailInfo.removeClass("error");
return true;
}
}
}
}
//if it's NOT valid
else{
var valEmail = $("#email").val();
if(valEmail == ""){
email.addClass("error");
emailInfo.text("Favor digitar um email!");
emailInfo.addClass("error");
return false;
}
else{
email.addClass("error");
emailInfo.text("O email digitado e invalido");
emailInfo.addClass("error");
return false;
}
}
}
The PHP code that looks on the database for the data:
<?php
include "conecta.php";
$email = $_GET['email'];
$consulta = "SELECT * FROM usuarios WHERE email = '$email';";
$result = mysql_query($consulta);
$num = mysql_num_rows($result);
if($num == 0)
echo "var resultadoEmail = { 'email' : '' }";
else{
while($row = mysql_fetch_object($result)){
$email = $row -> email;
}
echo "var resultadoEmail = { 'email' : '$email' }";
}
?>
I'm getting the error Uncaught SyntaxError: Unexpected token } but can't find where is the problem.
First of all, I just want to tell you that you have a security risk in your code. This line :
$email = $_GET['email'];
$consulta = "SELECT * FROM usuarios WHERE email = '$email';";
allow a person to run sql against your database and retrieve data. This is know as sql injection. You should validate your email before doing your query at minimum.
use this
return true;
}
});
^^^ // you forgot this

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