PHP Form Validation white space issue - php

I am trying to validate a form. I have my code as follows:
if(isset($_POST['data'])) {
$id = $this->input->post('id');
$action = $this->input->post('action');
$table = $this->input->post('table');
$data = $this->input->post('data');
$out = array();
$out['id'] = $id;
$out['error'] = '';
$out['fieldErrors'] = '';
$out['data'] = array();
$out['row'] = $data;
if($action=="create" && $data['display_name'] === '') {
if (empty($data['display_name']))
{
$this->_out['error'] = "Display name is required";
echo json_encode( $this->_out );
exit;
}
}
}
Now this is working fine if there is no data inserted in the form, but if there is a space (whitespace) it doesn't work.
Any suggestion?

There are a few options to solve this:
Replace all whitespaces with nothing:
if (strlen(preg_replace('/\s/', '', $data['display_name'])) == 0)
{
Use trim to remove leading and trailing whitespaces:
if (strlen(trim($data['display_name'])) == 0)
{
Use str_replace() to get rid of invalid characters:
if (strlen(str_replace(array(' ', "\t"), array('', ''), $data['display_name'])) == 0)
{
Use regular expression to validate a name:
if (!preg_match('/^([A-Za-z0-9-_]+)$/', $data['display_name']))
{

=== checks for type as well along with value comparison, using trim function on variable containing values would give you expected results.

Try this. I have used the ctype_space function below to check for whitespaces
if($action=="create" && ($data['display_name'] === '' || ctype_space($data['display_name']))) {
$this->_out['error'] = "Display name is required";
echo json_encode( $this->_out );
exit;
}

Just use trim function and check if its empty string:
if ($action=="create") {
if (trim($data['display_name']) == '') {
$this->_out['error'] = "Display name is required";
echo json_encode( $this->_out );
exit;
}
}

Related

How to check for white spaces and special characters

I am trying to code a form for a login using php to check it. But I can't get it to check the if I have any whitespaces and special characters for the username. I tried using the [\W]+ but that did not work.
<?php
$usernerr = "";
$passwerr = "";
$usern = "";
$passw = "";
$pattern = '/[\'\/~`\!##\$%\^&\*\(\)_\-\+=\{\}\[\]\|;:"\<\>,\.\?\\\]/';
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if(empty($_POST['uname']))
{
$usernerr = "*Please add a username please!";
}
else
{
$usern = clearInput($_POST['uname']);
if(!preg_match('/s/', $usern) || !preg_match($pattern, $usern))
{
$usernerr = "*Username have only letters and numbers!";
}
$usernerr = "";
}
if(empty($_POST['psw']))
{
$passwerr = "*Please add a password please!";
}
else
{
$passw = clearInput($_POST['psw']);
$passwerr = "";
}
}
function clearInput($input)
{
$input = trim($input);
$input = stripslashes($input);
$input = htmlspecialchars($input);
return $input;
}
?>
Considering the error message you wrote, you are complicating yourself.
Instead of searching for the list of characters that aren't alpha num, search for alpha num only. Try using this pattern, and don't negate the condition.
$pattern = "/^[a-zA-Z0-9]+$/";
// Some code...
if(preg_match($pattern, $usern))
// ^-------------------------------Notice the changes
{
//Username is valid
}
Description of the pattern :
^ from the begining
[a-zA-Z0-9] search an alpha num
+ 1 or more time
$ to the end
/^[a-zA-Z0-9]+$/can be replaced by /^[[:alnum:]]+$/ or /^[a-z\d]+$/i which produce the same effect.

PHP - Get Website Title From User Site Input

I'm trying to get the title of a website that is entered by the user.
Text input: website link, entered by user is sent to the server via AJAX.
The user can input anything: an actual existing link, or just single word, or something weird like 'po392#*#8'
Here is a part of my PHP script:
// Make sure the url is on another host
if(substr($url, 0, 7) !== "http://" AND substr($url, 0, 8) !== "https://") {
$url = "http://".$url;
}
// Extra confirmation for security
if (filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED)) {
$urlIsValid = "1";
} else {
$urlIsValid = "0";
}
// Make sure there is a dot in the url
if (strpos($url, '.') !== false) {
$urlIsValid = "1";
} else {
$urlIsValid = "0";
}
// Retrieve title if no title is entered
if($title == "" AND $urlIsValid == "1") {
function get_http_response_code($theURL) {
$headers = get_headers($theURL);
if($headers) {
return substr($headers[0], 9, 3);
} else {
return 'error';
}
}
if(get_http_response_code($url) != "200") {
$urlIsValid = "0";
} else {
$file = file_get_contents($url);
$res = preg_match("/<title>(.*)<\/title>/siU", $file, $title_matches);
if($res === 1) {
$title = preg_replace('/\s+/', ' ', $title_matches[1]);
$title = trim($title);
$title = addslashes($title);
}
// If title is still empty, make title the url
if($title == "") {
$title = $url;
}
}
}
However, there are still errors occuring in this script.
It works perfectly if an existing url as 'https://www.youtube.com/watch?v=eB1HfI-nIRg' is entered and when a non-existing page is entered as 'https://www.youtube.com/watch?v=NON-EXISTING', but it doesn't work when the users enters something like 'twitter.com' (without http) or something like 'yikes'.
I tried literally everthing: cUrl, DomDocument...
The problem is that when an invalid link is entered, the ajax call never completes (it keeps loading), while it should $urlIsValid = "0" whenever an error occurs.
I hope someone can help you - it's appreciated.
Nathan
You have a relatively simple problem but your solution is too complex and also buggy.
These are the problems that I've identified with your code:
// Make sure the url is on another host
if(substr($url, 0, 7) !== "http://" AND substr($url, 0, 8) !== "https://") {
$url = "http://".$url;
}
You won't make sure that that possible url is on another host that way (it could be localhost). You should remove this code.
// Make sure there is a dot in the url
if (strpos($url, '.') !== false) {
$urlIsValid = "1";
} else {
$urlIsValid = "0";
}
This code overwrites the code above it, where you validate that the string is indeed a valid URL, so remove it.
The definition of the additional function get_http_response_code is pointless. You could use only file_get_contents to get the HTML of the remote page and check it against false to detect the error.
Also, from your code I conclude that, if the (external to context) variable $title is empty then you won't execute any external fetch so why not check it first?
To sum it up, your code should look something like this:
if('' === $title && filter_var($url, FILTER_VALIDATE_URL))
{
//# means we suppress warnings as we won't need them
//this could be done with error_reporting(0) or similar side-effect method
$html = getContentsFromUrl($url);
if(false !== $html && preg_match("/<title>(.*)<\/title>/siU", $file, $title_matches))
{
$title = preg_replace('/\s+/', ' ', $title_matches[1]);
$title = trim($title);
$title = addslashes($title);
}
// If title is still empty, make title the url
if($title == "") {
$title = $url;
}
}
function getContentsFromUrl($url)
{
//if not full/complete url
if(!preg_match('#^https?://#ims', $url))
{
$completeUrl = 'http://' . $url;
$result = #file_get_contents($completeUrl);
if(false !== $result)
{
return $result;
}
//we try with https://
$url = 'https://' . $url;
}
return #file_get_contents($url);
}

Two " Array to string conversion" notices (Prestashop)

I'm not so sure whether it is smart to post both problems in one question, but lets try:
So, I was checking my server's error log and it still has two notices, both about "Array to string conversion in [...]".
The first line should be this:
$replace = $route['keywords'][$key]['prepend'].$params[$key].$route['keywords'][$key]['append'];
Context:
// Build an url which match a route
if ($this->use_routes || $force_routes) {
$url = $route['rule'];
$add_param = array();
foreach ($params as $key => $value) {
if (!isset($route['keywords'][$key])) {
if (!isset($this->default_routes[$route_id]['keywords'][$key])) {
$add_param[$key] = $value;
}
} else {
if ($params[$key]) {
$replace = $route['keywords'][$key]['prepend'].$params[$key].$route['keywords'][$key]['append'];
} else {
$replace = '';
}
$url = preg_replace('#\{([^{}]*:)?'.$key.'(:[^{}]*)?\}#', $replace, $url);
}
}
$url = preg_replace('#\{([^{}]*:)?[a-z0-9_]+?(:[^{}]*)?\}#', '', $url);
if (count($add_param)) {
$url .= '?'.http_build_query($add_param, '', '&');
}
}
The second one is this line:
$uri_path = __PS_BASE_URI__.$id_image.($type ? '-'.$type : '').$theme.'/'.$name.'.jpg';
as part of this:
// legacy mode or default image
$theme = ((Shop::isFeatureActive() && file_exists(_PS_PROD_IMG_DIR_.$ids.($type ? '-'.$type : '').'-'.(int)Context::getContext()->shop->id_theme.'.jpg')) ? '-'.Context::getContext()->shop->id_theme : '');
if ((Configuration::get('PS_LEGACY_IMAGES')
&& (file_exists(_PS_PROD_IMG_DIR_.$ids.($type ? '-'.$type : '').$theme.'.jpg')))
|| ($not_default = strpos($ids, 'default') !== false)) {
if ($this->allow == 1 && !$not_default) {
$uri_path = __PS_BASE_URI__.$ids.($type ? '-'.$type : '').$theme.'/'.$name.'.jpg';
} else {
$uri_path = _THEME_PROD_DIR_.$ids.($type ? '-'.$type : '').$theme.'.jpg';
}
} else {
// if ids if of the form id_product-id_image, we want to extract the id_image part
$split_ids = explode('-', $ids);
$id_image = (isset($split_ids[1]) ? $split_ids[1] : $split_ids[0]);
$theme = ((Shop::isFeatureActive() && file_exists(_PS_PROD_IMG_DIR_.Image::getImgFolderStatic($id_image).$id_image.($type ? '-'.$type : '').'-'.(int)Context::getContext()->shop->id_theme.'.jpg')) ? '-'.Context::getContext()->shop->id_theme : '');
if ($this->allow == 1) {
$uri_path = __PS_BASE_URI__.$id_image.($type ? '-'.$type : '').$theme.'/'.$name.'.jpg';
} else {
$uri_path = _THEME_PROD_DIR_.Image::getImgFolderStatic($id_image).$id_image.($type ? '-'.$type : '').$theme.'.jpg';
}
}
return $this->protocol_content.Tools::getMediaServer($uri_path).$uri_path;
}
public function getMediaLink($filepath)
{
return $this->protocol_content.Tools::getMediaServer($filepath).$filepath;
}
PHP is not my strength, so I have no idea what to do :/
Also I found some other questions about Array to string notices, but it seemed to me like you can't solve them the same way...
Thanks in advance for any help!
This error is appearing because some of the variables in these two lines are supposed to be String but they are actually array.
You need to print all the variables used in these 2 lines using the var_dump() function of PHP, this will tell you which of the variables are actually an Array, but they are supposed to be a String as per your code.
On the basis of the output, you need to modify your code to fix the issue.

Why does preg_match function validate all fields with a specific field argument?

I have a form in which I am using a preg_match function to validate fields. I have a generalized function for the matching. The function validateForm() is being called earlier on in the script with the appropriate values.
When the function is NOT passed any values, all the fields show the error message despite having correctly matching information. Generalized function with no arguments:
function validateForm() {
if(preg_match()) {
return true;
}
else {
return false;
}
} // end function validateForm
When I pass just ONE specific regex/field pair argument, all the fields begin to validate and show the error message when appropriate (so basically the code works as it should despite having a field-specific argument in the function). For example, when I pass this single regex/field argument into preg_match, all the fields begin to validate each field correctly, regardless of the fact that I am only checking for the 'City' field in this case. Example of passing a field-specific argument, in which all the code 'works':
function validateForm($cityRegex, $city) {
if(preg_match($cityRegex, $city)) {
return true;
}
else {
return false;
}
} // end function validateForm
Can someone explain to me why, when passed a specific argument for a specific field, the function will work for all individual preg_match arguments in the code? The script is running as I would want it to, I just do not understand why the specific argument is what makes it validate all fields.
Here is all of the PHP code, if needed:
<?php
$first = '';
$last = '';
$phone = '';
$city = '';
$state = '';
$error_message = '';
$firstLastRegex = '/^[a-zA-Z]{2,15}$/';
$lastRegex = '/^[a-zA-Z]{2,15}$/';
$phoneRegex = '/^(\(\d{3}\))(\d{3}\-)(\d{4})$/';
$cityRegex = '/^[a-zA-Z]{3,20}$/';
$stateRegex = '/^[a-zA-Z]{2}$/';
$validate_first = '';
$validate_last = '';
$validate_phone = '';
$validate_city = '';
$validate_state = '';
$phone_string = '';
if(isset($_POST['submit'])) {
$first = $_POST['firstName'];
$last = $_POST['lastName'];
$phone = $_POST['phoneNumber'];
$city = $_POST['userCity'];
$state = $_POST['userState'];
$show_form = false;
$phone_string = str_replace(array('-', '(', ')'), '', $phone);
$validate_first = validateForm($firstLastRegex, $first);
$validate_last = validateForm($lastRegex, $last);
$validate_phone = validateForm($phoneRegex, $phone);
$validate_city = validateForm($cityRegex, $city);
$validate_state = validateForm($stateRegex, $state);
if($validate_first == false) {
$show_form = true;
$error_message .= "Please enter your FIRST name between 2 and 15 letters.<br>";
}
if($validate_last == false) {
$show_form = true;
$error_message .= "Please enter your LAST name between 2 and 15 letters.<br>";
}
if($validate_phone == false) {
$show_form = true;
$error_message .= "Please enter your phone number in (###)###-### format.<br>";
}
if($validate_city == false) {
$show_form = true;
$error_message .= "Please enter your city name between 3 and 20 letters.<br>";
}
if($validate_state == false) {
$show_form = true;
$error_message .= "Please enter your state's abbreviation (Example: CA).<br>";
}
} // end if isset();
else {
$show_form = true;
$error_message = "";
} // end else
// REGEX FUNCTION
function validateForm() {
if(preg_match()) {
return true;
}
else {
return false;
}
} // end function validateForm
?>
You still need to have arguments for you function. The code below will make your validate function work.
function validateForm($regEx, $field) {
if(preg_match($regEx, $field)) {
return true;
}
else {
return false;
}
} // end function validateForm
I also see other potential issues with not checking if post variables are set before using them, and you are setting $show_form = true for all your if/else cases. I'm sure you can figure everything else out with some debug statements.

php: validate if field starts with certain character

I'm using the Contact Form 7 plugin on wordpress to collect data inputted in the fields, I'm now looking to set up some validation rules using this neat extension: http://code-tricks.com/contact-form-7-custom-validation-in-wordpress/
What I'm after is to only allow one word only in the text field (i.e. no whitespace) and this one word has to begin with the letter 'r' (not case sensitive).
I've written the no white space rule as follows:
//whitespace
if($name == 'WhiteSpace') {
$WhiteSpace = $_POST['WhiteSpace'];
if($WhiteSpace != '') {
if (!preg_match('/\s/',$WhiteSpace)){
$result['valid'] = true;
} else {
$result['valid'] = false;
$result['reason'][$name] = 'Invalid Entry.';
}
}
}
Is it possible to incorporate the second rule into this also? So no whitespace, and the word must begin with the letter 'r'? Any suggestions would be greatly appreciated!
EDIT:
seems core1024 answer does work, but only one of them:
//FirstField
if($name == 'FirstField') {
$FirstField = $_POST['FirstField'];
if($FirstField != '') {
if (!preg_match("/(^[^a]|\s)/i",$FirstField)){
$result['valid'] = true;
} else {
$result['valid'] = false;
$result['reason'][$name] = 'Invalid Entry.';
}
}
}
//__________________________________________________________________________________________________
//SecondField
if($name == 'SecondField') {
$SecondField = $_POST['SecondField'];
if($SecondField != '') {
if (!preg_match("/(^[^r]|\s)/i", $SecondField)) {
$result['valid'] = true;
} else {
$result['valid'] = false;
$result['reason'][$name] = 'Invalid Entry.';
}
}
}
I want to use this code twice, once to validate the first character being a on one field the second instance with the first character being r on another field. But it only seems the SecondField validation rule is working.
Try to use:
preg_match('/^r[^\s]*$/i',$WhiteSpace)
instead of:
!preg_match('/\s/',$WhiteSpace)
You need this:
if (!preg_match("/(^[^r]|\s)/i", $WhiteSpace)) {
It matches any string that doesn't start with r/R or contain space.
Here's a test:
$test = array(
'sad',
'rad',
'ra d'
);
foreach($test as $str) {
echo '"'.$str.'" -> '.preg_match('/(^[^r]|\s)/i', $str).'<br>';
}
And the result:
"sad" -> 1
"rad" -> 0
"ra d" -> 1

Categories