I'm trying that validating the text box inside echo in php. I tried some methods but it is not working.
php form code:
echo '<form method="post" action="singlepage.php?id='.$idn.'"';
echo '<label id="blogtextarea2">Comment:</label><textarea rows="10" cols="75" name="comment" id="blogtextarea" ></textarea><br>';
echo '<input type="submit" name="post" id="blogsubmit" value="post">';
echo '</form>';
and validation code is
if(isset($_POST['post']))
{
if ($_POST['comment'] != "") {
$_POST['comment'] = filter_var($_POST['comment'], FILTER_SANITIZE_STRING);
if ($_POST['comment'] == "") {
$errors .= 'Please enter a valid name.<br/><br/>';
}
} else {
$errors= 'Please enter your name.<br/>';
}
}
I'm not exactly sure what you meant by "not working", but I have cleaned up your code and changed the check for an empty POST comment data using the empty() function instead.
There was also a redundant check within your first check for an empty comment which I've removed:
$errors = '';
if(isset($_POST['post'])) {
if(!empty($_POST['comment'])) {
$_POST['comment'] = filter_var($_POST['comment'], FILTER_SANITIZE_STRING);
} else {
$errors = 'Please enter your name.<br/>';
}
}
echo $errors;
Ok found it why it is not working
if(isset($_POST['post']))
{
if (!empty($_POST['comment'])) {
$_POST['comment'] = filter_var($_POST['comment'], FILTER_SANITIZE_STRING);
} else {
$errors = 'Please enter your name.';
}
}
echo $errors;
You have to check defined conditions on singlepage.php
Related
I have issue with fat-free contact form.
My contact form does nothing. Like no success or any kind of error data.
My contact form POST and GET route:
$f3->route('GET #contact: /contact', 'Rimtay\Client->GET_Contact');
$f3->route('POST #contact: /send', 'Rimtay\Client->contactPost');
My contact form POST function:
function contactPost(){
function validateInput($data) {
$bad = array("content-type","bcc:","to:","cc:","href");
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
foreach ($bad as $badString) {
if (preg_match('/('.$badString.')/i',$data)) {
// If it looks like someone is trying to hack
// into the site via the contact page, then just stop.
exit;
}
}
return $data;
}
// define variables and set to empty values
$contactNameError = $contactEmailError = $contactMessageError = "";
$name = $email = $message = $success = "";
if ($f3->exists('POST.name',$name)) {
if ($name !== '') {
$name = validateInput($name);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$contactNameError = "Wrong name";
} else { // valid name
$f3->set('contactName',$name);
}
} else {
$contactNameError = "name empty";
}
} else {
$contactNameError = "name error";
}
if ($f3->exists('POST.email',$email)) {
if ($email !== '') {
$email = validateInput($email);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$contactEmailError = "wrong email";
} else { // valid email
$f3->set('contactEmail',$email);
}
} else {
$contactEmailError = "email empty";
}
} else {
$contactEmailError = "error email";
}
if ($f3->exists('POST.subject',$message)) {
if ($message !== '') {
$f3->set('contactMessage',$message);
} else {
$contactMessageError = "message tühi";
}
} else {
$contactMessageError = "lambi message";
}
if (($contactNameError === '') && ($contactEmailError === '') && ($contactMessageError === '')) {
// send the message
$messageBody = "";
unset($_POST['submit']);
$messageBody = "Name: ".$name."\n";
$messageBody .= "email: ".$email."\n";
$messageBody .= "Subject: Construction - Message from " . $name."\n";
$messageBody .= $message."\n";
$messageBody = wordwrap($messageBody,70);
$to = $f3->get('contactAddresses');
$subject = 'Contact Submitted';
if (mail($to, $subject, $messageBody)){
$f3->set('contactSuccess',true);
} else {
// error sending the email to myself
}
} else {
$f3->set('contactSuccess',false);
}
// Set the content source
$this->f3->set('pageContent','contact.html');
}
my form looks like this:
<form class="form" action="{{ #schemeHost.#PATH }}" method="post">
<textarea class="textarea" name="message" placeholder="Message*">{{ #contactMessage }}</textarea>
<div>
<input type="text" placeholder="Name *" name="name" value="{{ #contactName }}" class="input">
<input type="email" placeholder="Email *" name="email" value="{{ #contactEmail }}" class="input">
</div>
<button class="submit" type="submit" name="submit">Send</button>
</form>
My System isnt giving any success or error messages.
And not sending out contact form messages to email.
I dont see what I'm doing wrong there.
Your code is very prone to errors. For example, the $f3 variable is not defined anywhere in your code.
How does your code handle the errors? It might be that you see no errors because there is no error reporting setup by you and the server is silently not showing the errors. I suggest you to check the error log.
I also suggest to use a form validation library like CakePHP validation library. You will need to learn how to use it, but it will save you big time in the end and your code will be cleaner.
I'm working on an e-commerce website project, and I'm trying to validate customer's information using PHP. And I'm here trying to check if the customer put his/her phone number, and to check if the phone number is in the correct form. So first, I check the POST array if it's empty or not, if it is empty, I show an error message "Phone number must be entered". And if there is a phone number, I check the REGEX and if it does not match, I show an error message "Phone number is invalid". And everything is correct, just proceeds. But somehow, below my code, does not check REGEX. If it is empty, it shows an error message for the empty field, but not REGEX. Why is this so?
if (!empty($_POST)) {
$error = false;
if (empty($_POST["phone"])) {
echo "<p class='errorMessage'> Phone must be entered. </p>";
$error = true;
}
if (!empty($_POST["phone"])) {
if (!preg_match("/^[2-9]\d{2}-\d{3}-\d{4}$/", $_POST['phone'])) {
echo "<p class='errMessage'>Phone number is invalid</p>";
}
}
if (!$error) {
header("Location: confirmation.php");
exit;
}
}
And here is the HTML part:
<tr>
<th><label for="phone">Phone Number</label></th>
<td><input class="inputField" type="text" id="phone" name="phone"
<?php
if (isset($_POST["phone"])) echo "value='" . $_POST["phone"] . "'";
?>></td>
</tr>
This is because you don't declare error if the regex is invalid, so the code proceeds :
if (!empty($_POST)) {
$error = false;
if (empty($_POST["phone"])) {
echo "<p class='errorMessage'> Phone must be entered. </p>";
$error = true;
}
if (!empty($_POST["phone"])) {
if (!preg_match("/^[2-9]\d{2}-\d{3}-\d{4}$/", $_POST['phone'])) {
$error = true;
echo "<p class='errMessage'>Phone number is invalid</p>";
}
}
if (!$error) {
header("Location: confirmation.php");
exit;
}
}
Try the following code:
if (strlen($_POST["phone"]) >0) {
if (!preg_match("/^[2-9]\d{2}-\d{3}-\d{4}$/", $_POST['phone'])) {
$error = true;
echo "<p class='errMessage'>Phone number is invalid</p>";
}
else {
echo "<p class='errorMessage'> Phone must be entered. </p>";
$error = true;
}
I have the following code :
if(isset($_POST['submit'])){
if (! isset($_POST['firstname'])) {
$error[] = "Please fill out all fields";
}
if (! isset($_POST['surname'])) {
$error[] = "Please fill out all fields";
}
........
with validation:
if (strlen($_POST['firstname']) < 2){
$error[] = 'First name cannot be empty';
}
if (strlen($_POST['surname']) < 2){
$error[] = 'Please provide your surname';
}
......
More checks are made with the database....
This checks for errors and displays them in one go:
if(isset($error)){
foreach($error as $error){
echo '<p class="error-login">'.$error.'</p>';
}
}
While this is working fine, I would like errors to be shown under each input box where there is an error happening.
I don't want to change the entire code, just want to make the necessary changes to this one, which I am incapable of doing myself.
Is putting them in array the only approach here or is there a simpler way ?
Thanks.
The approach is - add errors to $error under a certain key, I presume - name of the input field:
if(isset($_POST['submit'])){
// I use key `all` for errors that don't belong to any field
if (! isset($_POST['firstname'])) {
$error['all'] = "Please fill out all fields";
}
if (! isset($_POST['surname'])) {
$error['all'] = "Please fill out all fields";
}
if (strlen($_POST['surname']) < 2){
$error['surname'] = 'Please provide your surname';
}
In your html markup:
// general errors, not related to inputs
if(isset($error['all'])){
foreach($error['all'] as $err){
echo '<p class="error-login">'.$err.'</p>';
}
}
<input type="text" name="surname" />
<?php
if(isset($error['surname'])){
foreach($error['surname'] as $err){
echo '<p class="error-login">'.$err.'</p>';
}
}
I am validating a form data using this script below.
When i submit the form if there is any errors the error message is displaying properly but if no errors and validation succeed i try to echo out the variables to test the script but the script is only displaying this : []
Please examine the code and help me solve this.
<?php
//included files
include("./includes/connect.php");
include("./includes/functions.php");
$errors = array();
//checking if user have submitted the form
if(isset($_POST['submitted'])) {
//validating and cleaning submitted form data ...
if (isset($_POST['name']) && !empty($_POST['name'])) {
if(preg_match("/^[a-zA-Z ]{2,20}$/", strip_trim($_POST['name']))) {
$cln_name = clean_data($_POST['name']);
} else {
$_POST['name'] = FALSE;
$errors[] = "The name you entered is not valid";
}
} else {
$errors[] = "You have not enter your name!";
}
if(isset($_POST['email']) && !empty($_POST['email'])) {
$cln_email = filter_var($_POST['email'] , FILTER_SANITIZE_EMAIL);
if(filter_var($cln_email, FILTER_VALIDATE_EMAIL)) {
$cln_email = clean_data($cln_email);
} else {
$_POST['email'] = FALSE;
$errors[] = "The email you entered is not valid";
}
} else {
$errors[] = "You have not provide you email!";
}
if(isset($_POST['plate_num']) && !empty($_POST['plate_num'])) {
if(ctype_alnum($_POST['plate_num']) && strlen($_POST['plate_num']) >= 5) {
$cln_plate_num = clean_data($_POST['plate_num']);
} else {
$_POST['plate_num'] = FALSE;
$errors[] = "The plate number you provided is not a valid plate number";
}
} else {
$errors[]= "You have not provide a plate number";
}
//checking for errors and printing errors..
if (count($errors > 0)) {
$errors_to_json = json_encode($errors);
echo $errors_to_json;
//foreach ($errors as $error) {
//echo $error . "<br />";
//}
} else {
echo $cln_name . "<br />";
echo $cln_email . "<br />";
echo $cln_plate_num;
}
} else {
echo "You did not submit the form!";
}
?>
This script is returning only this :
[]
Any idea please ??
functions.php :
<?php
function clean_data($data) {
if(function_exists('mysql_real_escape_string')) {
global $dbc;
$data = mysql_real_escape_string(trim($data), $dbc);
$data = strip_tags($data);
} else {
$data = mysql_escape_string(trim($data));
$data = strip_tags($data);
}
return $data;
}
function strip_trim($data) {
$data = stripslashes(trim($data));
return $data;
}
?>
you have problem in your if condition:
//checking for errors and printing errors..
if (count($errors > 0)) {
...
this will always return to TRUE because $error = [] and count([] > 0) results to TRUE
that's why you always end up in:
$errors_to_json = json_encode($errors);
echo $errors_to_json;
// Will indeed display '[]' because json_encode([]) is '[]'
i believe what you mean here is:
if (count($errors) > 0) {
...
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();
}
?>