How to set validation on Phone number in PHP - php

This is my code:
I never set validation for phone number field, I try "/^([0-9]{3})-[0-9]{3}-[0-9]{4}$/" this type of code for validation,
I enter text in the phone number field, they accept in backend
what can I do? for set validation for phone number field.
<!DOCTYPE HTML>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$nameErr = $phoneErr = "";
$name = $phone = "";
$error = 0;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = htmlspecialchars($_REQUEST['name']);
$phone = htmlspecialchars($_REQUEST['phone']);
if (empty($name)) {
$nameErr = "* Name is required";
$error = 1;
// echo "Name is empty";
}
if (empty($phone)) {
// echo "phone is empty";
$phoneErr = "* Phone is required";
$error = 1;
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<h1>Login Form</h1>
Name: <input type="text" name="name" onkeydown="return alphaOnly(event);" value="<?php echo $name ?>">
<span class="error"> <?php echo $nameErr?></span>
<br></br>
Phone: <input type="text" name="phone" value="<?php echo $phone ?>">
<span class="error"> <?php echo $phoneErr?></span>
<br><br>
<input type="submit">
<br><br>
</form>
</body>
</html>
I need to validate phone number in PHP, but the example do not work.
How can I set validation for mobile number

Sorry to answer an old post.
However, you can check if the number exists by calling a web service.
In this case, I found numverify.com, allowing to verify if a phone number exists.
After creating a free account (allows you to make 250 requests each month), you can invoke the following basic code in PHP:
// set API Access Key
$access_key = 'YOUR_ACCESS_KEY';
// set phone number
$phone_number = '14158586273';
// Initialize CURL:
$ch = curl_init('http://apilayer.net/api/validate?access_key='.$access_key.'&number='.$phone_number.'');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Store the data:
$json = curl_exec($ch);
curl_close($ch);
// Decode JSON response:
$validationResult = json_decode($json, true);
I have no idea if this is reliable, but it worked with my phone number and even retrieved the company carrier.

According to comments and example phone number that you given, this code will validating number of digits and first two numbers of your country, i just replaced + with 0, for sure they won't enter plus.
$tel = '091-9869123456';
if(preg_match("/^[0-9]{3}-[0-9]{10}$/", $tel)) {
echo "valid";
} else {
echo "invalid";
}
Now for more validating need to check country code:
if(substr($tel, 0, 3) == '091'){
echo "valid";
} else {
echo "invalid, it should start with 091";
}
Or you do this with same preg_match like this:
if(preg_match("/^[091]{3}-[0-9]{10}$/", $tel)) {
echo "valid";
} else {
echo "invalid";
}
Demo

Why do you need to validate phone number using php?
You can do it using JS as shown below.
if (/^\+[-0-9]{6,20}$/.test(phoneNumber) == false) {
alert('Wrong Phone Number format. Only numbers,+ and - are allowed. Format: \<Country Code\>\<Phone number\> Eg: +9199999999, +1-105-893-9334 etc');
return;
}

Related

User registration form error php

Hi am trying to write code that validates in the backend. The code should stop as soon as there is an error. In my case, even if the conditions are satisfied the code stops in the first name validation block itself.
Also I wish to have only backend validation.
Here is the php code clientRegister.php
<?php
require_once("connection.php");
session_start();
// define variables and set to empty values
$clientFirstName = $clientLastName =$clientEmail = $clientPassword =
$clientCPassword = $clientContact = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// First Name Validation
if (empty($_POST["clientFirstName"])) {
die("error: empty field");
} else {
$clientFirstName = test_input($_POST["clientFirstName"]);
// check if name only contains letters and whitespace
if (!preg_match("[a-zA-Z ]",$clientFirstName)) {
die("Error: Only letters and white space allowed");
}
}
// Last Name Validation
if (empty($_POST["clientLastName"])) {
die("error: empty field");
} else {
$clientLastName = test_input($_POST["clientLastName"]);
// check if name only contains letters and whitespace
if (!preg_match("[a-zA-Z ]",$clientLastName)) {
die("Error: Only letters and white space allowed");
}
}
// Email Validation
if (empty($_POST["clientEmail"])) {
die("error: empty field");
} else {
$clientEmail = test_input($_POST["clientEmail"]);
// check if e-mail address is well-formed
if (!filter_var($clientEmail, FILTER_VALIDATE_EMAIL)) {
die("Error: Invalid email format");
}
}
// Password Validation
if (empty($_POST["clientPassword"])) {
die("error: empty field");
}
// Confirm Password Validation
if (empty($_POST["clientCPassword"])) {
die("error: empty field");
}
if ($clientPassword != $clientCPassword) {
die("error: passwords mismatch");
}else{
$hashedClientPassword = password_hash($clientPassword, PASSWORD_DEFAULT);
}
if (empty($_POST["clientContact"])) {
die("error: empty field");
} else {
$clientContact = test_input($_POST["clientContact"]);
// check if number is correct
if (!preg_match("[0-9]",$clientContact)) {
die("error: Only 0-9 allowed");
}
}
$check_email = $conn->query("SELECT clientEmail FROM tbl_clients WHERE
clientEmail='$clientEmail'");
$emailCount=$check_email->num_rows;
if ($emailCount==0) {
$newClient = "INSERT INTO tbl_clients(clientFirstName, clientLastName,
clientEmail, clientPassword, clientContact) VALUES('$clientFirstName','$clientLastName','$clientEmail','$hashedClientPassword','$clientContact')";
if ($newClient === false){
$result = array();
$result[] = array("status" => "Error");
}else{
echo "Your have been signed up - please now Log In";
$result = array();
$result[] = array("First Name" => $clientFirstName, "Last Name" => $clientLastName, "Email" => $clientEmail, "Password" => $hashedClientPassword, "Contact" => $clientContact, "status" => "success");
}
}else {
echo "Already Exists";
$result = array();
$result[] = array("status" => "Error");
}
echo json_encode($result);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<h2>Reg User</h2>
<form method="post" action="clientRegister.php">
<label>
First Name:<input type="text" name="clientFirstName"><br/>
Last Name:<input type="text" name="clientLastName"><br/>
Email:<input type="text" name="clientEmail"><br/>
Password:<input type="password" name="clientPassword"><br/>
Confirm Password:<input type="password" name="clientCPassword"><br/>
Contact:<input type="text" name="clientContact"><br/>
<input type="submit" value="Register" name="submit">
</label>
</form>
</body>
</html>
You have missing pattern delimiters for your preg_match()
Replace your patterns with following sample:
if (!preg_match("[a-zA-Z ]",$clientFirstName)) {
die("Error: Only letters and white space allowed");
}
With:
if (!preg_match("/[a-zA-Z ]/",$clientFirstName)) {
die("Error: Only letters and white space allowed");
}
Also your
($clientPassword != $clientCPassword)
will always return false because you have not assigned new $_POST values to them. And since you have initialized both variables as empty. So (empty != empty) always return false.
So you should compare like this:
($_POST["clientPassword"] != $_POST["clientCPassword"])
Regarding your query, it was not executed
$newClient = "INSERT INTO tbl_clients(clientFirstName, clientLastName, clientEmail, clientPassword, clientContact) VALUES('$clientFirstName','$clientLastName','$clientEmail','$hashedClientPassword','$clientContact')";
Which I think you meant:
$newClient = $conn->query("INSERT INTO tbl_clients(clientFirstName, clientLastName, clientEmail, clientPassword, clientContact) VALUES('$clientFirstName','$clientLastName','$clientEmail','$hashedClientPassword','$clientContact')");
Note: Your queries are vulnerable to sql injection and you should use prepare statement
DEMO:
http://sandbox.onlinephpfunctions.com/code/d435ae025dc9e22b677823ff37712bb712b71e1b
You can test this file:
https://pastebin.com/AgfquEMC

PHP - Validation form

I'm trying to create a simple validation script for a form but cannot get it to work properly. I only get redirected to an error page...
As you can see below only small and capitalized letters are allowed for first- and last name, only email structure for email and only numbers, spaces and (+) for the phone number. If the user input is not allowed the user gets redirected to a simple error page.
$first_name = $last_name = $email = $mobile = $country = "";
if (isset($_SERVER["REQUEST_METHOD"] == "POST")) {
// Only small and capitalized letters allowed
$first_name = test_input($_POST['first_name']);
if(!preg_match("/^[a-zA-Z ]*$/",$first_name)) {
die("Error! Non allowed signs were used in 'first name'");
}
// Only small and capitalized letters allowed
$last_name = test_input($_POST['last_name']);
if(!preg_match("/^[a-zA-Z ]*$/",$last_name)) {
die("Error! Non allowed signs were used in 'last name'");
}
// Only email allowed
$email = test_input($_POST['email']);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
die ("Error! Non allowed signs were used in 'email'");
}
// Only numbers, space and + allowed
$mobile = test_input($_POST['mobile']);
if(!preg_match("/^[0-9 +-]+$/",$mobile)) {
die ("Error! Non allowed signs were used in 'mobile'");
}
// Country input (no validation)
$country = $_POST['country'];
}
// Function test input
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
The HTML is basically this:
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type="text" required="" name="first_name" style="width:100%" />
[And so on...]
</form>
if (isset($_SERVER["REQUEST_METHOD"] == "POST")) {`
is incorrect ~ isset returns a boolean which effectively makes this if(false=='POST') or similar
Try:
if ( $_SERVER["REQUEST_METHOD"] == "POST" ) {

Passing on validated variables to a different page (PHP)

On form index.php I have three input fields (Name, Surname and Date of Birth) which I want to pass along to form myProfile.php, the user cannot continue to the next myProfile.php unless all three fields have been completed.
How can I send the variables to the next page, once it has been determined that all the input fields are valid? Currently I can determine that all the input fields are valid, but I don't know how to pass the variables along to myProfile.php
Variables and Input handling (index.php):
<?php
$nameErr = $surnameErr = $dobErr = "";
$name = $surname = $dob = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["surname"])) {
$surnameErr = "Surname is required";
} else {
$surname = test_input($_POST["surname"]);
}
if (empty($_POST["dob"])) {
$dobErr = "Date of Birth is required";
} else {
$dob = test_input($_POST["dob"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Creating the form (index.php):
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
Surname:
<input type="text" name="surname">
<span class="error">* <?php echo $surnameErr;?></span>
<br><br>
Date of Birth:
<input type="date" name="dob">
<span class="error">*<?php echo $dobErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
My problem is that in order to send my name, surname and date of birth to myProfile.php, I need the form action to be action="myProfile.php", however for the input validation to take place it has to be action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>". How can I allow the input validation to take place, and if all the input is valid, then pass the variables along to myProfile.php in order to use the following code:
myProfile.php:
<?php
$name = $_POST['name'];
$surname = $_POST['surname'];
$dob = $_POST['dob'];
echo "<h2>Your Input:</h2>";
echo "My name is " . $name . " " . $surname . ". I am " . date_diff(date_create($dob), date_create('today'))->y . " years old.";
?>
You should be able to use PHP's session functionality to do this. Sessions are not specific to PHP, but PHP has functions which make it easy to maintain data about a specific visitor. This can be tricky because HTTP is a stateless protocol.
In index.php, after you have made sure that the data is valid you can store it in session by calling session_start and using the superglobal $_SESSION variable:
if ($data_is_valid) // you'll have to figure out yourself whether data is valid or not
{
session_start(); // you must call this before using $_SESSION
$_SESSION["valid_data"] = array(
"name" => $name,
"surname" => $surname,
"dob" => $dob
);
// redirect the user to the other page
header("location: myProfile.php");
// always remember to exit after redirecting or code may continue to execute
exit;
}
Then, in my Profile.php, you can call session_start and check for the valid data
session_start();
if (!array_key_exists("valid_data", $_SESSION)) {
die("No valid data found!"); // you might want to redirect back to the first page or something?
}
$data = $_SESSION["valid_data"];
if (!is_array($data)) {
die("Data found is not an array!");
}
// otherwise, data was found...you can keep going!
// you might get errors here if you didn't set these properly on the the previous page
$name = $data['name'];
$surname = $data['surname'];
$dob = $data['dob'];
echo "<h2>Your Input:</h2>";
echo "My name is " . $name . " " . $surname . ". I am " . date_diff(date_create($dob), date_create('today'))->y . " years old.";

How to save a PHP variable when a page loads twice

A user enters two dates periods on a text-box and a SQL select statement picks mobile numbers from a database entered in between the period. I want to pick and display them on a page. On the same display page, I have a text area where a user can type a message and on submit, it should be sent to these selected numbers and displayed mobile numbers. I am having a challenge on passing the $mobilenumber to the function sendbulk that is to send the message to the mobile numbers displayed by $mobilenumber variable. Everything else is okay apart from passing the $mobilenumber. I think this is because after the page loads to display the contacts selected, on the second load as you submit the $message to bulk function the value of $mobilenumber is already lost. How can I save it.
Check sample code below and please advice. How do I save the $mobilenumber so that by the second load it is still there to be passed to the function sendbulk()? Anyone?
<?php
//Define variable and set to empty values
$message = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$message = test_input($_POST['message']);
echo "$message";
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$time1 = isset($_POST['t1']) ? $_POST['t1'] : 'default something missing';
$time2 = isset($_POST['t2']) ? $_POST['t2'] : 'default something missing';
//connection
$sql = "SELECT DISTINCT msisdn FROM customer WHERE DATE_FORMAT(time_paid, '%Y-%c-%e') BETWEEN ADDDATE('$time1',INTERVAL 0 HOUR) AND ADDDATE('$time2',INTERVAL '23:59' HOUR_MINUTE)";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo " Recipients: "; echo "$result->num_rows <br> <br>";
// output data of each row
while($row = $result->fetch_assoc()) {
$mobilenumber = $row['msisdn'];
echo "Mobile : " . "$mobilenumber" . "<br>";
}
} else {
echo "No Contacts to Display";
}
$conn->close();
sendbulk($mobilenumber,$message);
?>
<center></center> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<textarea name='message' rows="6" cols="60" placeholder="Please Type Your Message Here"></textarea>
<br><br>
<input type="submit" name="submit" value="Send Message">
</form></center>
<?php
function sendbulk($mobilenumber,$message) {
echo "$mobilenumber";
echo "$message";
$serviceArguments = array(
"mobilenumber" => $mobilenumber,
"message" => $message_sent
);
$client = new SoapClient("http://*******");
$result = $client->process($serviceArguments);
return $result;
}
You use sessions.
Here is a sample code:
<?php
session_start();
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
} else {
$_SESSION['count'] += 1;
}
echo $_SESSION['count'];
?>
Keep reloading this file via your web server. You should see the variable incrementing.
As an alternative, you can also use $_COOKIE. The only difference is that $_SESSION is saved on the server side and not accessible on the client. To identify the client it does store a cookie for that session on the client.
$_COOKIE on the other hand is completely stored on the client and passed by the browsers to the server on every request.
Also note a caveat, don't overload your session variables or cookies as it will hit your response times.
Also note that session_start() is required in every PHP file where you want to access the session.

PHP - Form validation functions. How to use functions to write better code?

I'm practicing doing simple form validation and have come unstuck trying to use a function to replace code that I repeat several times throughout the validation script.
I am trying to write a function that saves an error message to an $errors array when validation fails for that form field.
The function I'm using does not return any error messages but does not display the message that is should do when validation fails.
I'm testing it on just one filed, the username field and with just one validation rule, username cannot be blank.
NB/ The form and validation worked when I was not trying to use a function.
Here is what I have, what a I doing wrong? I'm struggling to get to grips with functions :-(
functions.php
<?php
//Function to deal with saving error messages to errors array
// #param - 2 parameters. Name of field that has the error; Error message string
// #return - an error message string
function errorHandler($errField, $errMsg){
$errors[$errField] = $errMsg;
return $errors;
}
index.php
<?php
include_once '_includes/headers.php';
include_once '_includes/functions.php';
?>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
//Initialize variables
$data = array();//Store cleaned valid data for output
$errors = array();//Store error messages
$form_is_submitted = false;
$errors_detected = false;
if(isset($_POST['registerBtn'])){
$form_is_submitted = true;
//VALIDATE FORM
//Validate - Username
if (isset($_POST['username'])) {
$username = trim($_POST['username']);
//Username cannot be blank - validation
if($username !== ''){
$data['username'] = htmlentities($username);
//Get the length of the string
$stringLength = strlen($username);
//Username minimum 5 maximum 15 characters long - validation
if($stringLength < 5 || $stringLength > 15){
$errors_detected = true;
$errors['username'] = ' Invalid length. Must be between 5 - 15 characters!';
}else {
$data['username'] = htmlentities($username);
}
//Username must only be alphanumeric characters - validation
if(!ctype_alnum($username)){
$errors_detected = true;
$errors['username'] = ' Invalid characters. Alphanumeric characters only!';
}else {
$data['username'] = htmlentities($username);
}
}else {
$errors_detected = true;
//Call error message function
if($errors_detected === true){
errorHandler('username', ' Field cannot be blank!');
}
}
}else {
$errors_detected = true;
$errors['username'] = ' Is not set!';
}
//Validate - Email
if(isset($_POST['email'])){
$email = trim($_POST['email']);
//Email cannot be blank - validation
if($email !== ''){
$data['email'] = htmlentities($email);
//Email must be valid format - validation
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errors_detected = true;
$errors['email'] = ' Invalid email format!';
}else {
$data['email'] = htmlentities($email);
}
}else{
$errors_detected = true;
$errors['email'] = ' Email address is required!';
}
}else {
$errors_detected = true;
$errors['email'] = " is not set!";
}
}
//Declare form output variable
$output = '';
//IF VALID SUBMISSION
if($form_is_submitted === true && $errors_detected === false){
$output .= '<h3>Form successfully submitted</h3>';
echo $output;
foreach($data as $keys => $values){
echo "<p>$keys : $values</p>";
}
} else {
//IF INVALID SUBMISSION
if($errors_detected === true){
$output .= '<h2>There are errors on the form</h2>';
echo $output;
foreach($errors as $key => $value){
echo "<p>" . htmlentities($key) . ':' . htmlentities($value) . "</p>";
}
}
//DISPLAY/REDISPLAY FORM
$self = htmlentities($_SERVER['PHP_SELF']);
$output ='
<form action="'. $self .'" method="post">
<fieldset id="registration">
<legend>Register</legend>
<p>Insert your profile information:</p>
<div>
<label for="username">Username</label>
<input id="username" name="username" type=text value="' . (isset($data['username']) ? $data['username'] : '') . '" />
</div>
<div>
<label for="email">Email</label>
<input id="email" name="email" type=email value="' . (isset($data['email']) ? $data['email'] : '') . '" />
</div>
<input type="submit" id="registerBtn" name="registerBtn" value="Register" />
</fieldset>
</form>
';
echo $output;
}
?>
<?php
include_once '_includes/footers.php';
?>
UPDATE:
I have updated my function to use the $errors array in my function. This should now no longer be a scope issue I think. As per Francesco Malatesta below ...
First of all, you should study something about objects, classes, exceptions and more complex stuff for this kind of job. I am assuming you want to learn about functions and do some practice.
You should, first of all, pass the errors array as a parameter.
Like this:
function errorHandler($errorsArray, $errField, $errMsg){
$errorsArray[$errField] = $errMsg;
return $errorsArray;
}
And then, in your index.php file:
errorHandler($errors, 'username', ' Field cannot be blank!');
This should work, because you must use the $errors array in your function. It's a scope-related problem.
However, after this, forget everything (well, not everything) and study OOP and Exceptions :)
Have you heard about Exceptions?
Simple example to use a exception:
<?php
try {
// your if's
if(40 > 30) {
throw new Exception("40 is a bigger");
}
} catch (Exception $error) {
echo 'Your error is: '.$error->getMessage();
}
?>

Categories