i am validating three types of input(string,email,url):
string-validating:
if ($_POST['string'] != "") {
$string = filter_var($_POST['string'], FILTER_SANITIZE_STRING);
if ($string != "") {
// valid
} else {
// not valid
}
} else {
// empty
}
email-validating:
if ($_POST['email'] != "") {
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
// valid
} else {
// not valid
} else {
// empty
}
url-validating:
if ($_POST['url'] != "") {
$url = filter_var($_POST['url'], FILTER_SANITIZE_URL);
if (filter_var($url, FILTER_VALIDATE_URL)) {
// valid
} else {
// not valid
}
} else {
// empty
}
After doing this checks i use PDO - Prepared statements to inserate in database.
You think this is secure enough or did i missed some points?
Hope for your answers, thanks and greetings!
Related
When doing php validation should I First do the filter sanitizing/validating or is it okay to do it as part of an if statement see the examples below
First Example
$vvalidation = 0;
if (isset($_POST['db9_name']) && $_POST['db9_name'] != ''){
$name = $_POST['db9_name'];
if (filter_var($name, FILTER_SANITIZE_STRING === null)){
$vvalidation++;
}
} else{
$vvalidation++;
}
Second Example
$vvalidation = 0;
if (isset($_POST['db9_name']) && $_POST['db9_name'] != ''){
$name = $_POST['db9_name'];
$vname = filter_var($name, FILTER_SANITIZE_STRING);
if ($vname === null)){
$vvalidation++;
}
} else{
$vvalidation++;
}
and for email ?
example 1
if (isset($_POST['txtemail']) && $_POST['txtemail'] !== '') {
$vEmail = strtolower(strip_tags(trim($_POST['txtemail'])));
$vEmail = str_replace(' ', '', $vEmail);
if (filter_var($vEmail, FILTER_SANITIZE_EMAIL) === null) {
$vValidation++;
} elseif (filter_var($vEmail, FILTER_VALIDATE_EMAIL) === null) {
$vValidation++;
}
} else {
$vValidation++;
}
example 2
if (isset($_POST['txtemail']) && $_POST['txtemail'] !== '') {
$vEmail = strtolower(strip_tags(trim($_POST['txtemail'])));
$vEmail = str_replace(' ', '', $vEmail);
$email = (filter_var($vEmail, FILTER_SANITIZE_EMAIL);
$email .= (filter_var($vEmail, FILTER_VALIDATE_EMAIL);
if (email === null){
$vValidation++;
} else {
$vValidation++;
}
or does it not really matter?
I am trying to check on validate. in PrestaShop i do it this way:
if (empty($email)) {
$this->errors[] = Tools::displayError('Email is empty.');
$this->doLog('ERROR: Email/username is empty');
} elseif (!Validate::isEmail($email)) {
$this->errors[] = Tools::displayError('Invalid email address.');
$this->doLog('ERROR: Invalid Email address');
}
Does anyone have any idea how to do this in OpenCart?
Thanks
open this file for example:
catalog/controller/information/contact.php
you will see validate function:
protected function validate() {
if ((utf8_strlen($this->request->post['name']) < 3) || (utf8_strlen($this->request->post['name']) > 32)) {
$this->error['name'] = $this->language->get('error_name');
}
if (!filter_var($this->request->post['email'], FILTER_VALIDATE_EMAIL)) {
$this->error['email'] = $this->language->get('error_email');
}
if ((utf8_strlen($this->request->post['enquiry']) < 10) || (utf8_strlen($this->request->post['enquiry']) > 3000)) {
$this->error['enquiry'] = $this->language->get('error_enquiry');
}
// Captcha
if ($this->config->get($this->config->get('config_captcha') . '_status') && in_array('contact', (array)$this->config->get('config_captcha_page'))) {
$captcha = $this->load->controller('extension/captcha/' . $this->config->get('config_captcha') . '/validate');
if ($captcha) {
$this->error['captcha'] = $captcha;
}
}
return !$this->error;
}
In that file, you can also see how this function is used:
if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
I have a post form on front end where users can post (post_type = product) from the form. As a part of it I have tried implementing few server side validations as in below code. The issue is that the validations are all working fine but the data is getting saved on form submission even when the validation fails.
Ideally the form submission should fail when there is a field validation failure.
I am not sure if $hasError = true is working or not, there might be a very simple logic I am missing which I am not getting. Any help regarding this?
Thanks in advance.
$postTitleError = '';
if (isset($_POST['submitted']) && isset($_POST['post_nonce_field']) && wp_verify_nonce($_POST['post_nonce_field'], 'post_nonce')) {
if (trim($_POST['postTitle']) === '') {
$postTitleError = 'msg 1';
$hasError = true;
}
if (trim($_POST['postCat1']) === '') {
$postTitleError = 'msg2';
$hasError = true;
}
if (trim($_POST['postPrice']) === '') {
$postTitleError = 'msg3';
$hasError = true;
}
if (trim($_POST['postTime']) === '') {
$postTitleError = 'msg4';
$hasError = true;
}
if (trim($_POST['postTimeMin']) === '') {
$postTitleError = 'msg5';
$hasError = true;
}
if (trim($_POST['postContent']) === '') {
$postTitleError = 'msg6';
$hasError = true;
}
<?php
//$postTitleError = '';
$resultArr = array();
$error_msg = false;
if (isset($_POST['submitted']) && isset($_POST['post_nonce_field']) && wp_verify_nonce($_POST['post_nonce_field'], 'post_nonce')) {
if (isset($_POST['postTitle']) && !empty($_POST["postTitle"])) {
//$postTitleError = 'msg 1';
//$hasError = true;
$postTitle=$_POST['postTitle'];
}
else
{
$resultArr['status'] = 'failure';
$resultArr['error_msg_postTitle']= "msg 1";
$error_msg = true;
}
if (isset($_POST['postCat1']) && !empty($_POST["postCat1"]) ) {
// $postTitleError = 'msg2';
// $hasError = true;
$postCat1=$_POST['postCat1'];
}
else
{
$resultArr['status'] = 'failure';
$resultArr['error_msg_postCat1']= "msg2";
$error_msg = true;
}
if (isset($_POST['postPrice']) && !empty($_POST["postPrice"]) ) {
// $postTitleError = 'msg3';
//$hasError = true;
$postPrice=$_POST['postPrice'];
}
else
{
$resultArr['status'] = 'failure';
$resultArr['error_msg_postPrice']= "msg3";
$error_msg = true;
}
if (isset($_POST['postTime']) && !empty($_POST["postTime"]) ) {
//$postTitleError = 'msg4';
//$hasError = true;
$postTime=$_POST['postTime'];
}
else
{
$resultArr['status'] = 'failure';
$resultArr['error_msg_postTime']= "msg4";
$error_msg = true;
}
if (isset($_POST['postTimeMin']) && !empty($_POST["postTimeMin"]) ) {
// $postTitleError = 'msg5';
// $hasError = true;
$postTimeMin=$_POST['postTimeMin'];
}
else
{
$resultArr['status'] = 'failure';
$resultArr['error_msg_postTimeMin']= "msg5";
$error_msg = true;
}
if (isset($_POST['postContent']) && !empty($_POST["postContent"]) ) {
//$postTitleError = 'msg6';
// $hasError = true;
$postContent=$_POST['postContent'];
}
else
{
$resultArr['status'] = 'failure';
$resultArr['error_msg_postContent']= "msg6";
$error_msg = true;
}
if($error_msg == false)
{
//here publish post code
}
else
{
//here Error message prine
}
?>
This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 8 years ago.
Header location not working on live server but works on localhost.
This code worked until last week, but it does not work anymore.
So, I have started testing on localhost. It is working as before.
I tried to add "ob_start()" on the top of the code; not working.
Please review this code and comment.
<?php session_start();
$fnameErr ="";
$lnameErr ="";
$emailErr ="";
$phoneErr = "";
$dateErr = "";
$timeErr = "";
$errMsg = "";
$area = "";
$local3 = "";
$local4 = "";
$cust_info = "";
$charOnly = "/^[a-z]+[a-z]$/i";
$reg_email = "/^[^0-9~!##$%^&*()_+=?.,][a-z0-9_]+([.][a-z0-9_]+)*[#][a-z0-9_]+([.][a-z0-9_]+)*[.][a-z]{2,3}$/i";
$reg_phone = "/^(\d{3}+\d{3}+\d{4}|\d{3}\d{3}+[\s]{1}+\d{4}|\d{3}+[\s]{1}+\d{3}+[\s]{1}+\d{4}||\d{3}+[-]{1}+\d{3}+[-]{1}+\d{4}|\d{3}+[\s]{1}+\d{7}|\(\d{3}\)\s{1}\d{3}[\s-]{1}\d{4})$/";/*"/^(\d{3}|[(]\d{3}[)]|\d{3}[)])[ -]*\d{3}[ -]*\d{4}$/";*/
$dataValid = true;
$phone = $area .''. $local3 .''. $local4;
$phoneValid = true;
// If submit with POST
if ($_POST) {
$errMsg = "Debugging";
$area = $_POST['c_area'];
$local3 = $_POST['c_local3'];
$local4 = $_POST['c_local4'];
$cust_info = array( "first" => $_POST['c_fname'],
"last" => $_POST['c_lname'],
"email" => $_POST['c_email'],
"phone" => array("area"=> $area,
"mid" => $local3,
"last" => $local4),
"date" => $_POST['c_date'],
"time" => $_POST['c_time']);
// Test for nothing entered in field
if ($_POST['c_fname'] == "") {
$fnameErr = "Please enter your first name.";
$dataValid = false;
}
else {
if ( preg_match($charOnly, $_POST['c_fname']) )
{
$fnameErr = "";
} else {
$fnameErr = "This is an invalid name.";
$dataValid = false;
}
}
if ($_POST['c_lname'] == "") {
$lnameErr = "Please enter your last name.";
$dataValid = false;
}
else {
if ( preg_match($charOnly, $_POST['c_lname']) )
{
$lnameErr = "";
} else {
$lnameErr = "This is an invalid name.";
$dataValid = false;
}
}
if ($_POST['c_email'] == "") {
$emailErr = "Please enter E-mail address.";
$dataValid = false;
}
else {
if ( preg_match($reg_email, $_POST['c_email']) )
{
$emailMsg = "";
} else {
$emailMsg = "E-mail is not Valid.";
$dataValid = false;
}
}
if ($_POST['c_area'] == "") {
$phoneErr = "Please enter phone number.";
$dataValid = false;
$phoneValid = false;
}
if ($_POST['c_local3'] == "") {
$phoneErr = "Please enter phone number.";
$dataValid = false;
$phoneValid = false;
}
if ($_POST['c_local4'] == "") {
$phoneErr = "Please enter phone number.";
$dataValid = false;
$phoneValid = false;
}
if( $phoneValid ) {
$phone = $area . "" . $local3 . "" .$local4;
if ( preg_match($reg_phone, $phone) ) {
$phoneErr = "";
} else {
$phoneErr = "Phone number is not Valid.";
$dataValid = false;
}
} else {
$area = "";
$local3 = "";
$local4 = "";
$phone = "";
}
if ($_POST['c_date'] == "") {
$dateErr = "Please choose a date.";
$dataValid = false;
}
if ($_POST['c_time'] == "" || $_POST['c_time'] == "Morning" || $_POST['c_time'] == "Afternoon") {
$timeErr = "Please choose a time.";
$dataValid = false;
} else {
if ("07:00" == $_POST['c_time']){
$Checked0700 = 'selected';
}
else if ("07:30" == $_POST['c_time']){
$Checked0730 = 'selected';
}
else if ("08:00" == $_POST['c_time']){
$Checked0800 = 'selected';
}
else if ("08:30" == $_POST['c_time']){
$Checked0830 = 'selected';
}
else if ("09:00" == $_POST['c_time']){
$Checked0900 = 'selected';
}
else if ("09:30" == $_POST['c_time']){
$Checked0930 = 'selected';
}
else if ("10:00" == $_POST['c_time']){
$Checked1000 = 'selected';
}
else if ("10:30" == $_POST['c_time']){
$Checked1030 = 'selected';
}
else if ("11:00" == $_POST['c_time']){
$Checked1100 = 'selected';
}
else if ("11:30" == $_POST['c_time']){
$Checked1130 = 'selected';
}
else if ("12:00" == $_POST['c_time']){
$Checked1200 = 'selected';
}
else if ("12:30" == $_POST['c_time']){
$Checked1230 = 'selected';
}
else if ("13:00" == $_POST['c_time']){
$Checked1300 = 'selected';
}
else if ("13:30" == $_POST['c_time']){
$Checked1330 = 'selected';
}
else if ("14:00" == $_POST['c_time']){
$Checked1400 = 'selected';
}
else if ("14:30" == $_POST['c_time']){
$Checked1430 = 'selected';
}
else if ("15:00" == $_POST['c_time']){
$Checked1530 = 'selected';
}
else if ("15:30" == $_POST['c_time']){
$Checked1530 = 'selected';
}
else if ("16:00" == $_POST['c_time']){
$Checked1600 = 'selected';
}
else if ("16:30" == $_POST['c_time']){
$Checked1630 = 'selected';
}
else if ("17:00" == $_POST['c_time']){
$Checked1700 = 'selected';
}
else if ("after" == $_POST['c_time']){
$Checkedafter = 'selected';
}
}
}
if ($_POST && $dataValid) {
$_SESSION['token1'] = "ok";
$_SESSION['cust'] = $cust_info;
header('Location:innout-booking-step2.php');
exit();
?>
I also faced such problem so I tried following steps to resolve it.
1. Remove or comment spaces, echos, print_r, error reporting before calling header location.
2. Remove spaces after php end tag (after ?> )
3. Modify header location syntax for this what I generally do is open w3schools copy header location syntax and paste it. In your case you should try to change your header code as
header('Location: innout-booking-step2.php'); (space after : )
i have a simple contact form that i have included a honeypot input field.
i would like the form to redirect to a webpage if the field is filled out.
i tried the below code, but it is giving me an error:
the AJAX request failed!
so i know i have done something wrong. i'm sure it is simple.
thanks
the php code:
if(!empty($_POST["e-mail"])) header('Location: blankman.html');exit;
the form input:
<input type="text" name="e-mail" id="e-mail"/>
here is the full php code:
<?php
if(!empty($_POST["e-mail"])) header('Location: blankman.html');exit;
// Clean up the input values
foreach($_POST as $key => $value) {
if(ini_get('magic_quotes_gpc'))
$_POST[$key] = stripslashes($_POST[$key]);
$_POST[$key] = htmlspecialchars(strip_tags($_POST[$key]));
}
// Assign the input values to variables for easy reference
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
// Test input values for errors
$errors = array();
if(strlen($name) < 2) {
if(!$name) {
$errors[] = "missing your name";
} else {
$errors[] = "your name must be 2 characters";
}
}
if(!$email) {
$errors[] = "missing your email";
} else if(!validEmail($email)) {
$errors[] = "you must enter a valid email";
}
if(strlen($message) < 3) {
if(!$message) {
$errors[] = "missing your message";
} else {
$errors[] = "oops! your message is not long enough";
}
}
if($errors) {
// Output errors and die with a failure message
$errortext = "";
foreach($errors as $error) {
$errortext .= "<li>".$error."</li>";
}
$response = array(
"success" => false,
"content" => "<span class='failure'><ul>". $errortext ."</ul></span>"
);
die(json_encode($response));
}
// Send the email *********** enter your email address and message info ***
$to = "myemail#myemail.com";
$subject = "Website message from: $name";
$message = "From:\n$name\n\nEmail:\n$email\n\nMessage:\n$message";
$headers = "From: $email";
mail($to, $subject, $message, $headers);
// Die with a success message
$response = array(
"success" => true,
"content" => "<span class='success'><li>Thank you! Your message has been sent :).</li></span>"
);
die(json_encode($response));
// A function that checks to see if
// an email is valid
function validEmail($email)
{
$isValid = true;
$atIndex = strrpos($email, "#");
if (is_bool($atIndex) && !$atIndex)
{
$isValid = false;
}
else
{
$domain = substr($email, $atIndex+1);
$local = substr($email, 0, $atIndex);
$localLen = strlen($local);
$domainLen = strlen($domain);
if ($localLen < 1 || $localLen > 64)
{
// local part length exceeded
$isValid = false;
}
else if ($domainLen < 1 || $domainLen > 255)
{
// domain part length exceeded
$isValid = false;
}
else if ($local[0] == '.' || $local[$localLen-1] == '.')
{
// local part starts or ends with '.'
$isValid = false;
}
else if (preg_match('/\\.\\./', $local))
{
// local part has two consecutive dots
$isValid = false;
}
else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
{
// character not valid in domain part
$isValid = false;
}
else if (preg_match('/\\.\\./', $domain))
{
// domain part has two consecutive dots
$isValid = false;
}
else if(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
str_replace("\\\\","",$local)))
{
// character not valid in local part unless
// local part is quoted
if (!preg_match('/^"(\\\\"|[^"])+"$/',
str_replace("\\\\","",$local)))
{
$isValid = false;
}
}
if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")))
{
// domain not found in DNS
$isValid = false;
}
}
return $isValid;
}
?>
here is the javascript:
<script>
$(document).ready(function () {
$("#contactform").submit(function (e) {
e.preventDefault();
var t = $(this).attr("action");
var n = $(this).serialize();
$.post(t, n, null, "json").done(function (e) {
if (e.success) {
$("#success").html(e.content);
$("#contactform,#error").hide()
} else {
$("#error").html(e.content)
}
}).fail(function () {
alert("The AJAX request failed!")
})
})
})
</script>
Do not show whatever different behavior if honeypot is filled. This way you are screaming to a spamer with BIG RED LETTERS: "Here is a honeypot! Investigate and write a workaround!"
Always respond to a spam request EXACTLY the same way as to a regular one:
if(!empty($_POST["e-mail"])) {
$response = array(
"success" => true,
"content" => "<span class='success'><li>Thank you! Your message has been sent :).</li></span>"
);
die(json_encode($response));
}