I am trying to display error messages to user if they entered a wrong uk phone number format or not a number, but the error messages not working.
HTML
<input type="text" name="phone" class="form-control" value="<?php echo $phone;?>" placeholder="Mobile Number ">
<span class="error"><?php echo $phoneErr;?></span>
PHP
$phoneErr = "";
$phone = "";
if (empty($_POST["phone"])) {
$phone = "";
} else if(!preg_match( $phone, '/^(?:\(\+?44\)\s?|\+?44 ?)?(?:0|\(0\))?\s?(?:(?:1\d{3}|7[1-9]\d{2}|20\s?[78])\s?\d\s?\d{2}[ -]?\d{3}|2\d{2}\s?\d{3}[ -]?\d{4}) $/'))
{
$phoneErr = "Invalid phone number";
}else {
$phone = test_input($_POST["phone"]);
}
test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
If it's not a number nothing will be inserted to the database, but if I typed a number 9223372036854775807 will be inserted, this value is not the one I entered. I have done some researches, I think this value means invalid string.
Other parts of my form are working fine only the phone number not working well, I am not sure why.
First of all: your regular expression (even purged by final space) doesn't match 9223372036854775807.
You don't show how you insert values in database, but if above code is for checking the phone number, it's a mystery how any phone number can be inserted, unless you insert $_POST['phone']. But why you insert $_POST['phone'] if you before try to convert it in $phone?
I say “try”, because in fact the line $phone = test_input($_POST["phone"]) never happens.
If $_POST['phone'] is empty, you set $phone to empty string (this in unnecessary: $phone is already an empty string, but this is not a problem), otherwise you test your regular expression, but you test it on $phone (an empty string), not on $_POST['phone']; in addition, you invert preg_match arguments, so in fact you test if an empty pattern matches string /^(?:\(\+?44\)\s?|\ ....
You have to rewrite your check routine in something like this:
$phoneErr = False;
$phone = "";
if( ! empty( $_POST["phone"] ) )
{
$pattern = '/^(?:\(\+?44\)\s?|\+?44 ?)?(?:0|\(0\))?\s?(?:(?:1\d{3}|7[1-9]\d{2}|20\s?[78])\s?\d\s?\d{2}[ -]?\d{3}|2\d{2}\s?\d{3}[ -]?\d{4})$/';
if( !preg_match( $pattern, $phone ) )
{
$phoneErr = "Invalid phone number";
}
else
{
$phone = test_input($_POST["phone"]);
}
}
(...)
if( $phoneErr )
{
// Your error routine here
}
elseif( $phone )
{
// Insert $phone (not $_POST['phone']) to database
}
Regarding your regular expression, check it with more than one UK valid numbers on regex101.com before using it. As alternative, you can try the regular expressions suggested in question cited in comments.
Solved
<?php
require_once('connect.php');
if(isset($_POST['submit']))
{
$name= strip_tags($_POST['name']);
$phone = strip_tags($_POST['phone']);
if($name=="") {
$error[] = "Please enter name.";
}
else if(!preg_match('/^[a-zA-Z ]*$/', $name))
{
// check if name only contains letters and whitespace
$error[] = "Only letters and white space allowed for name";
}
else
{
if( !empty($phone) )
{
$pattern = '/^(?:\(\+?44\)\s?|\+?44 ?)?(?:0|\(0\))?\s?(?:(?:1\d{3}|7[1-9]\d{2}|20\s?[78])\s?\d\s?\d{2}[ -]?\d{3}|2\d{2}\s?\d{3}[ -]?\d{4})$/';
if(!preg_match($pattern, $phone)){
$error[] = 'Please enter a valid phone number!';
}else{
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt =$conn->prepare( "INSERT INTO contact (name,phone)
VALUES( :name, :phone)");
$stmt->bindparam(':name', $name);
$stmt->bindparam(':phone', $phone);
$stmt->execute();
}catch(PDOException $e) {
echo "Error: " . $e->getMessage();
die();
}
}
}
}
}
?>
Related
i have an a project im using php and flutter for that
when i want to add a data to database i want to validate user inputs in php
im using a postman to test it i want to all inputs correct that add on database can some one help me?
when i request a post add and user want to add data to database i want all inputs correct as i defined on below if one inputs not correct i want to tell that filed incorrect and do not add a data utill all inputs correct
if ($_SERVER["REQUEST_METHOD"] === 'POST') {
$pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^";
if (empty($_POST['First_Name'])) {
echo 'Error! You didnt Enter the First Name. <br />';
} else {
$first_name = $_POST['First_Name'];
if (!preg_match("/^[a-zA-z]*$/", $first_name)) {
echo 'Only alphabets and whitespace are allowed For First Name. <br />';
}
}
if (empty($_POST['Last_Name'])) {
echo 'Error! You didnt Enter the Last Name. <br />';
} else {
$last_name = $_POST['Last_Name'];
if (!preg_match("/^[a-zA-z]*$/", $last_name)) {
echo 'Only alphabets and whitespace are allowed For Last Name. <br />';
}
}
if (empty($_POST['Email'])) {
echo 'Email Address Is Required <br />';
} else {
$email = $_POST['Email'];
if (!preg_match($pattern, $email)) {
echo 'Email is not valid! <br />';
}
}
if (empty($_POST['Phone'])) {
echo 'Phone Number is Required! <br />';
} else {
$phone = $_POST['Phone'];
if (!preg_match('/^[0-9]*$/', $phone)) {
echo 'Only Numeric Value Is Allowed. <br />';
} elseif (!preg_match('/^0\d{10}$/', $phone)) {
echo 'Invalid Phone Number!';
} elseif (preg_match('/^0\d{10}$/', $phone)) {
$re = "SELECT * FROM user WHERE Phone=$phone ";
$reresult = mysqli_query($conn, $re);
if (mysqli_num_rows($reresult) > 0) {
echo "user has already registered! <br />";
}
}
}
$first_name = mysqli_real_escape_string($conn, $_POST['First_Name']);
$last_name = mysqli_real_escape_string($conn, $_POST['Last_Name']);
$email = mysqli_real_escape_string($conn, $_POST['Email']);
$phone = mysqli_real_escape_string($conn, $_POST['Phone']);
$dob = mysqli_real_escape_string($conn, $_POST['DOB']);
$sql = "INSERT INTO `user` (`First_Name`,`Last_Name`,`Email`,`Phone`,`DOB` )
VALUES('$first_name','$last_name','$email','$phone','$dob')";
$query = mysqli_query($conn, $sql);
//$check=mysqli_fetch_array($query);
if ($query) {
echo ' user successfully added!';
} else {
echo 'failure';
}
//phone else
}
im asking to solve my problem
When I click the submit button without filling the form, a new entry appears on database with the ID but the form keep validating and showing the user, this field is required but why the form is still submitting to the database?
Here is my code, kindly help, I am new in PHP and very tired of solving such problem.
<?php
include 'dbc.php';
// define variables and set to empty values
$name_error = $email_error = $phone_error = $url_error = $message_error = "";
$name = $email = $phone = $message = $url = $success = "";
//form is submitted with POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST["name"])) {
$name_error = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$name_error = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$email_error = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if (empty($_POST["phone"])) {
$phone_error = "Phone is required";
} else {
$phone = test_input($_POST["phone"]);
// check if e-mail address is well-formed
}
if (empty($_POST["url"])) {
$url_error = "Website url is required";
} else {
$url = test_input($_POST["url"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$url)) {
$url_error = "Invalid URL";
}
}
if (empty($_POST["message"])) {
$message_error = "Message field is required";
} else {
$message = test_input($_POST["message"]);
}
if ($name_error == '' and $email_error == '' and $phone_error == '' and $url_error == '' and $message_error == ''){
$message = 'Hello Ladies';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message .= "$key: $value\n";
}
$to = 'sample#email.com';
$subject = 'Contact Form Submit';
if (mail($to, $subject, $message)){
$success = "Message sent, thank you for contacting us!";
}
}
$query = "INSERT INTO clients(name,email,phone,url,message) ";
$query .= "VALUES('$name', '$email', '$phone', '$url', '$message') ";
$create_user = mysqli_query($mysqli, $query);
if (!$create_user) {
die("QUERY FAILED. " . mysqli_error($mysqli));
}
}
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
I hope I don't get downvote.
The only check actually being made before the query is run, is
if ($_SERVER["REQUEST_METHOD"] == "POST") {
which means that the only requirement for inserting values, is that the form is sent over POST, nothing else. This can be checked with a proper editor and seeing what brackets are wrapped around your query. You do some checks earlier in the code to validate and check the input, but this doesn't tell if the query should be run or not.
If you move the closing-bracket } of the following if-block
if ($name_error == '' and $email_error == '' and $phone_error == '' and $url_error == '' and $message_error == ''){
until after the query is performed, the query will only run if it passed all your checks. (place it after the following snippet)
if (!$create_user) {
die("QUERY FAILED. " . mysqli_error($mysqli));
}
In other remarks, your test_input() is rubbish (really) and you shouldn't use it. Parameterize your queries instead and filter the input with proper functions. There are validation filters and sanitation filters already implemented in PHP, you should use them if you need to.
You should prepare and bind the values of your queries using mysqli::prepare(), this will handle any issues dealing with quotes and protect your database against SQL injection.
References
mysqli::prepare()
How can I prevent SQL injection in PHP?
i'm worried about the security of my form. The idea is to make a form to participate in a contest in facebok. Basically just firstname, lastname, email. I've been searching through topics and there is a lot of info about security but i can't figure out what is enough security?
I know that there will always be a risk that someone finds a way to abuse the security, but i'd like to find a solution, which blocks the most of them. Also if there are obvious mistakes, please let me know.
Here is my code and all help and guidance is appreciated.
<?php
$dsn = 'mysql:dbname=dbname;host=localhost';
$user = '';
$password = '';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$firstErr = $lastErr = $emailErr = "";
$first = $last = $email = "";
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["first"])) {
$firstErr = "Name is required";
echo "<p>Firstname: $firstErr</p>";
} else {
$first = test_input($_POST["first"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$first)) {
$firstErr = "Only letters and white space allowed";
echo "<p>Firstname: $firstErr</p>";
}
}
if (empty($_POST["last"])) {
$lastErr = "Name is required";
echo "<p>Lastname: $lastErr</p>";
} else {
$last = test_input($_POST["last"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$last)) {
$lastErr = "Only letters and white space allowed";
echo "<p>Lastname: $lastErr</p>";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
echo "<p>Email: $emailErr</p>";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
echo "<p>Email: $emailErr</p>";
}
}
if ($firstErr == false && $lastErr == false && $emailErr == false) {
$query = "INSERT INTO contactstable (first,last,email) VALUES(:first,:last,:email)";
$statement = $dbh->prepare($query);
$statement->execute(array(
':first'=> $first,
':last'=> $last,
':email'=> $email
));
echo "<p>Thank you for participating!</p>";
}
else {
echo "Fix the missing or incorrect lines.";
}
}
?>
You are using PDO, it already implements the security measures for 1st order injection and when the queries are parametrized the 2nd order also prevented(2nd order injection means data has been cycled through the database once before being included in a query).
But there is no harm if you implements validations for the inputs.
I have a form, php validation, and send to email. My php validation works fine. My send to email works fine. When I use them both together, they work fine until I add header('Location: http://google.com'); exit(); I am using google.com for because I havent made my confirmation page yet. When I add this line to the php, that's when it goes straight to google.com when I go to my website. Can someone please help? I have been trying to figure out all of this validation and form to email for 2 straight days now, and I cannot figure it out. I know nothing about php. My code is below.
My php:
<?php
// define variables and set to empty values
$nameErr = $emailErr = $email2Err = $commentsErr = "";
$name = $email = $email2 = $comments = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if ( ! preg_match("/^[a-zA-Z ]*$/", $name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if ( ! preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["email2"])) {
$email2Err = "It is required to re-enter your email.";
} else {
$email2 = test_input($_POST["email2"]);
// check if e-mail address syntax is valid
if ( ! preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email2)) {
$email2Err = "Invalid email format";
}
}
if (empty($_POST["comments"])) {
$commentsErr = "A comment is required.";
} else {
$comments = test_input($_POST["comments"]);
if (preg_match("#^[a-zA-Z0-9 \.,\?_/'!£\$%&*()+=\r\n-]+$#", $comments)) {
// Everything ok. Do nothing and continue
} else {
$commentsErr = "Message is not in correct format.<br>You can use a-z A-Z 0-9 . , ? _ / ' ! £ $ % * () + = - Only";
}
}
if (isset($_POST['service'])) {
foreach ($_POST['service'] as $selectedService)
$selected[$selectedService] = "checked";
}
}
if (empty($errors)) {
$from = "From: Our Site!";
$to = "jasonriseden#yahoo.com";
$subject = "Mr Green Website | Comment from " . $name . "";
$message = "Message from " . $name . "
Email: " . $email . "
Comments: " . $comments . "";
mail($to, $subject, $message, $from);
header('Location: http://google.com');
exit();
}
?>
Please someone help me. I have no idea what is wrong.
Ok. I did what you told me Barmar. Not sure if I did it right or not. It solved one problem, but another was created.
I started over with the code that validates and sends the form data to my email. Now I just want to add header('Location: http://google.com '); exit(); ....and it work. Can you tell me what to do? I have no idea what php, so the more specific that you can be, the better.
Here is the php:
<?php
// define variables and set to empty values
$nameErr = $emailErr = $email2Err = $commentsErr = "";
$name = $email = $email2 = $comments = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["name"]))
{$nameErr = "Name is required";}
else
{$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else
{$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
}
}
if (empty($_POST["email2"]))
{$email2Err = "It is required to re-enter your email.";}
else
{$email2 = test_input($_POST["email2"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email2))
{
$email2Err = "Invalid email format";
}
}
if (empty($_POST["comments"]))
{$commentsErr = "A comment is required.";}
else
{$comments = test_input($_POST["comments"]);
if (preg_match("#^[a-zA-Z0-9 \.,\?_/'!£\$%&*()+=\r\n-]+$#", $comments)) {
// Everything ok. Do nothing and continue
} else {
$commentsErr = "Message is not in correct format.<br>You can use a-z A-Z 0-9 . , ? _ / ' ! £ $ % * () + = - Only";
}
}
if (isset($_POST['service']))
{
foreach ($_POST['service'] as $selectedService)
$selected[$selectedService] = "checked";
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (empty($errors)) {
$from = "From: Our Site!"; //Site name
// Change this to your email address you want to form sent to
$to = "jasonriseden#yahoo.com";
$subject = "Mr Green Website | Comment from " . $name . "";
$message = "Message from " . $name . "
Email: " . $email . "
Comments: " . $comments . "";
mail($to,$subject,$message,$from);
}
?>
The problem is that there's no variable $errors. So if(empty($errors)) is always true, so it goes into the block that sends email and redirects. This happens even if the user hasn't submitted the form yet -- I'm assuming this code is part of the same script that displays the registration form after the code you posted.
You need to make two changes:
The code that sends the email and redirects should be moved inside the first if block, after all the validation checks.
Instead of if(empty($error)), it should check if($nameErr && $emailErr && $email2Err && $commentsErr). Or you should change the validation code to set $error whenever it's setting one of these other error message variables.
I know this isn't a direct answer to your question, but have a look into Exceptions. By having seperate functions for each validation and have them throw an exception when something is wrong, your code will be much cleaner and bugs will have much less room to pop up. Bonus points if you put all the validation functions in a class.
Example: (I renamed test_input() to sanitize_input(), because that's what it does)
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
try
{
$name = getValidatedName();
$email = getValidatedEmail();
// send email with $name and $email
}
catch (Exception $e)
{
echo '<div class="error">' . $e->getMessage() . '</div>';
}
}
function getValidatedName()
{
if (empty($_POST["name"]))
throw new Exception("Name is required");
$name = sanitize_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/", $name))
throw new Exception("Only letters and white space allowed");
return $name;
}
function getValidatedEmail()
{
if (empty($_POST["email"]))
throw new Exception("Email is required");
$email = sanitize_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) // you don't have to reinvent the wheel ;)
throw new Exception("Invalid email format");
return $email;
}
im trying to create a form that validates the input fields then sends the data into a mysql database. i can get either the input validation to work, or the data inserted into the database, but not both.. heres my code:
<?php require_once('../php/pdo_connect.php');
// define variables and set to empty values
$first_name_err = $last_name_err = $cell_err = $email_err = FALSE;
$first_name = $last_name = $cell = $email = FALSE;
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["first_name"]))
{$first_name_err = "First name is required";}
else
{
$first_name = test_input($_POST["first_name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$first_name))
{
$first_name_err = "Please don't use hypens or other special characters";
}
}
if (empty($_POST["last_name"]))
{$last_name_err = "Last name is required";}
else
{
$last_name = test_input($_POST["last_name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$last_name))
{
$last_name_err = "Please don't use hypens or other special characters";
}
}
if (empty($_POST["cell"]))
{$cell_err = "Phone number is required";}
else
{
$cell = test_input($_POST["cell"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[\+0-9\-\(\)\s]*$/",$cell))
{
$cell_err = "Invalid cell phone number";
}
}
if (empty($_POST["email"]))
{$email_err = "Email address is required";}
else
{
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$email_err = "Invalid email format";
}
}
if ($first_name_err = false){
//insert info into db
$query = $pdo->prepare("INSERT INTO `guestlist_page_requests` (first_name, last_name, cell, email) VALUES (?, ?, ? ,?)");
$query->bindValue(1, $first_name);
$query->bindValue(2, $last_name);
$query->bindValue(3, $cell);
$query->bindValue(4, $email);
$query->execute();
header('Location: ../index.php');
}else{
//not enough data to submit to db
}
}
i tried a few differant variations of this line:
if ($first_name_err = false){
but im not really sure what i should be putting here?
this line almost makes it work:
if (!empty($_POST['first_name']) && !empty($_POST['last_name']) && !empty($_POST['cell']) && !empty($_POST['email'])){
but then it submits the data with the errors unless one of the fields is empty.
this also doesnt seem to work right:
if ($first_name_err = false){