Passing Special Characters to PHP via AJAX - php

I'm collecting form data, sending that to PHP validation script through AJAX call. The issue is on special characters the php validation script is not working as expected.
HTML:
<input type="text" name="firstName" class="firstName"
placeholder="[first name]" required autofocus maxlength="25" size="25" />
JS:
$(".button").click(function () {
var firstName = encodeURIComponent($("input.firstName").val());
var datastring = "firstName=" + firstName;
$.ajax({
type: "POST",
url: "/scripts/validateSignup.php",
data: datastring,
cache: false,
success: function (errorMessage) {
//print to screen
}
});
});
PHP Validation
$postData = $_POST;
if (Filter::validateString($postData['firstName']) == false) {
echo "Oops! Some characters used in your first name are not valid.";
}
PHP Filter
//Returns true if string is good, false otherwise
public static function validateString($string) {
$string = trim($string);
if ($string == null || $string == "") {
return false;
} else {
if (preg_match("/[^\.\,\-\_\'\"\#\?\!\:\;\$\#\%\&\+\= a-zA-Z0-9()]/", $string) == true) {
return false;
} else {
return true;
}
}
}
On an empty string it prints error to screen just fine. But if I do something like "~!##$%^&*()", then it accepts the string as good and doesnt throw and error, even though the result of preg_match == false.

$string = trim($string);
if ($string == null || $string == "") {
return false;
} else {
if (preg_match("/[^\.,\-_'\"#?!:;\$#&\+=\sa-zA-Z0-9\(\)]/", $string) == true) {
return false;
} else {
return true;
}
}
That is more valid regex, but not the result you want: you're checking for pretty much all input, so it'll match "abcd" and return false as well. There are 11 characters with special meanings to regular expressions, only those and the " need to be escaped: ^$[]()|.*+-

Try this:-
<?php
$string = "tes$%tname"; // invalid string
//$string = "testname"; // valid string
if(test($string) == false)
{
echo "String is invalid";
}
function test($string){
$string = trim($string);
if ($string == null || $string == "") {
return false;
} else {
if (preg_match("/[^\.,\-_'\"#?!:;\$#&\+=\sa-zA-Z0-9\(\)]/",$string) == true) {
return false;
} else {
return true;
}
}
}
?>
PHPFiddle is here:- http://phpfiddle.org/main/code/cdu-xg2

Related

How can I show dynamic error message using PHP?

I have a html form and this form is validating by PHP with jQuery/Ajax request.
Currently it's working perfectly. Now I want to show a dynamic error message.
For e. g:
I am validating integer number using following function :
function only_number ($string) {
if( preg_match('/^[0-9]+$/', $string ) ) {
return true;
} else {
return false;
}
}
This function is implementing by following way :
$msg = array();
$msg['error'] = false;
if(empty($emp_id)) {
$msg[] = 'Select assign to';
$msg['error'] = true;
} elseif( only_number($emp_id) === false ) {
$msg[] = 'Assign to must be numeric value';
$msg['error'] = true;
}
echo json_encode($msg);
You see that I am showing error message
Assign to must be numeric value
in the function implemented page e.g. update.php
It's very time consuming that I need to type several type of error message every time.
NOW, I want to write this error message in the function and it will show/implemented on validating page like : update.php page.
How can I do this ?
You can return array from your function. E.g:
function only_number ($string) {
$result = array(
'success' => false,
'error' => '',
);
if( preg_match('/^[0-9]+$/', $string ) ) {
$result['success'] = true;
} else {
$result['error'] = 'Assign to must be numeric value';
}
return $result;
}
And check:
if (empty($emp_id)) {
$msg[] = 'Select assign to';
$msg['error'] = true;
} else {
$check = only_number($emp_id);
if ($check['success'] == false) {
$msg[] = $check['error'];
$msg['error'] = true;
}
}
In stead of returning true/false you can also return a string with the error message
function only_number ($string) {
if (empty ($string) return 'Select assign to';
if(!preg_match('/^[0-9]+$/', $string ) ) return 'Assign to must be numeric value';
else return 'no error';
}
next in your code
if (only_number($emp_id) <> 'no error') echo (json_encode(only_number($emp_id)));

Nested if statement not firing

I am posting data to my db, however, before I do I have set in my php to echo out any issues. When the 'data != 'signup success' it should run the if within it, this does not work. Any ideas ?
PHP:
if($u == ""){
echo "Please create a username";
exit();
}
Js:
var submitBtn = $('#signUpBtn');
submitBtn.on('click', function() {
var fn = $('#fname'),
ln = $('#lname'),
u = $('#uname'),
e = $('#email'),
p = $('#pword1'),
p2 = $('#pword2'),
fnVal = fn.val(),
lnVal = ln.val(),
uVal = u.val(),
eVal = e.val(),
pVal = p.val(),
p2Val = p2.val();
$.post('phpsrc/parsers/signUp.php',
{fn: fnVal, ln: lnVal, u: uVal, e: eVal, p: pVal},
function(data) {
if (data != 'signup success') {
if (data === 'Please create a username') {
alert('uname');
}
} else {
}
}
);
});
You'd be better off json encoding the data:
if($u == ""){
$data = array("response" => "Please create a username");
exit(json_encode($data));
}
Allowing you to check the response in your ajax request like this:
function(data) {
if (data.response !== 'signup success') {
if (data.response == 'Please create a username') {
alert('uname');
}
} else {
alert('something');
}
}

php function return a Boolean and use it on condition

im not sure on how i am going to explain this correctly.
I wanted a function to validate a string which i figured correctly.
But i want the function to return a boolean value.
And outside a function i need to make a condition that if the function returned false, or true that will do something. Here's my code.
i am not sure if this is correct.
<?php
$string1 = 'hi';
function validatestring($myString, $str2) {
if(!empty($myString)) {
if(preg_match('/^[a-zA-Z0-9]+$/', $str2)) {
}
}
else {
return false;
}
}
if(validatestring == FALSE) {
//put some codes here
}
else {
//put some codes here
}
?>
EDIT : Now what if there are more than 1 condition inside the function?
<?php
$string1 = 'hi';
function validatestring($myString, $myString2) {
if(!empty($myString)) {
if(preg_match('/^[a-zA-Z0-9]+$/', $str2)) {
return true;
}
else {
retun false;
}
}
else {
return false;
}
}
if(validatestring($myString, $myString2) === FALSE) {
//put some codes here
}
else {
//put some codes here
}
?>
Functions need brackets and parameter. You dont have any of them.
This would be correct:
if(validatestring($myString) === false) {
//put some codes here
}
An easier and more elegant method would be this:
if(!validatestring($myString)) {
//put some codes here
}
<?php
$string1 = 'hi';
function validatestring($myString) {
if(!empty($myString)) {
return true;
}
else {
return false;
}
}
if(validatestring($string1) === FALSE) {
//put some codes here
}
else {
//put some codes here
}
?>
Sidenote, since empty() already returns false ,you could simplify by doing:
function validateString($string){
return !empty($string);
}
if(validateString($myString){
// ok
}
else {
// not ok
}
To make a check and test later:
$check = validateString($myString);
if($check){ }
There's no need to check == false or === false, the function already returns a boolean, it would be redundant.
store $string1 to $myString in the function
myString=string1
<?php
$string1 = 'hi';
function validatestring($myString) {
myString=string1;
if(!empty($myString)) {
return true;
}
else {
return false;
}
}
if(validatestring() === FALSE) {
//put some codes here
}
else {
//put some codes here
}
?>

PHP: checking if YT url is valid and if video exists

The function purpose is to validate the URLs of a YouTube video and check if the video exists. This is a snippet of my actual code. I manipulate the string to my desired format and then i proceed to check if it is valid and exists. If it passes the test, then i echo the results. The problem is that I am not calling the function correctly.
I am getting this echo even though the video does exist:
The video does not exist or invalid url
Edited: and added isValidURL function
*Code for checking if video exist or is invalid:*
if($_POST)
{
// After applying url manipulation and getting the url in a proper format result = $formatted_url
function isValidURL($formatted_url) {
$formatted_url = trim($formatted_url);
$isValid = true;
if (strpos($formatted_url, 'http://') === false && strpos($formatted_url, 'https://') === false) {
$formatted_url = 'http://'.$formatted_url;
}
//first check with php's FILTER_VALIDATE_URL
if (filter_var($formatted_url, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED) === false) {
$isValid = false;
} else {
//not all invalid URLs are caught by FILTER_VALIDATE_URL
//use our own mechanism
$host = parse_url($formatted_url, PHP_URL_HOST);
$dotcount = substr_count($host, '.');
//the host should contain at least one dot
if ($dotcount > 0) {
//if the host contains one dot
if ($dotcount == 1) {
//and it start with www.
if (strpos($host, 'www.') === 0) {
//there is no top level domain, so it is invalid
$isValid = false;
}
} else {
//the host contains multiple dots
if (strpos($host, '..') !== false) {
//dots can't be next to each other, so it is invalid
$isValid = false;
}
}
} else {
//no dots, so it is invalid
$isValid = false;
}
}
//return false if host is invalid
//otherwise return true
return $isValid;
}
$isValid = getYoutubeVideoID($formatted_url);
function isYoutubeVideo($formatted_url) {
$isValid = false;
//validate the url, see: http://snipplr.com/view/50618/
if (isValidURL($formatted_url)) {
//code adapted from Moridin: http://snipplr.com/view/19232/
$idLength = 11;
$idOffset = 3;
$idStarts = strpos($formatted_url, "?v=");
if ($idStarts !== FALSE) {
//there is a videoID present, now validate it
$videoID = substr($formatted_url, $idStarts + $idOffset, $idLength);
$http = new HTTP("http://gdata.youtube.com");
$result = $http->doRequest("/feeds/api/videos/".$videoID, "GET");
//returns Array('headers' => Array(), 'body' => String);
$code = $result['headers']['http_code'];
//did the request return a http code of 2xx?
if (substr($code, 0, 1) == 2) {
$isValid = true;
}
}
}
return $isValid;
}
$isValid = isYoutubeVideo($formatted_url);
parse_str($parsed_url['query'], $parsed_query_string);
$v = $parsed_query_string['v'];
if ( $isValid == true ) {
//Iframe code
echo htmlentities ('<iframe src="http://www.youtube.com/embed/'.$v.'" frameborder="0" width="'.$wdth.'" height="'.$hth.'"></iframe>');
//Old way to embed code
echo htmlentities ('<embed src="http://www.youtube.com/v/'.$v.'" width="'.$wdth.'" height="'.$hth.'" type="application/x-shockwave-flash" wmode="transparent" embed="" /></embed>');
}
else {
echo ("The video does not exist or invalid url");
}
}
?>
You are missing the isValidURL() function. Try changing this line:
if (isValidURL($formatted_url)) {
to
if(preg_match('/http:\/\/www\.youtube\.com\/watch\?v=[^&]+/', $formatted_url, $result)) {
or
$test = parse_url($formatted_url);
if($test['host']=="www.youtube.com"){

detect empty field - problem

I am trying detect in ajax what is the field that is empty. (echo $field; >>> output is radios)
This if (!data.livre && data.livre == "radios") { checks if data.livre is not true (that is working) and now i want to check if the echo is radios or not. If is radios i showed to the user: empty radios
function check($form) {
$fields = array("radios", "age");
foreach($fields as $field) {
if(empty($form[$field])) {
echo $field;
return false;
}
}
return true;
}
$data = array();
$data['livre'] = $val-> check($form);
echo json_encode($data);
JSON output:
radios{"livre":false}
js
success: function(data) {
if (!data.livre && data.livre == "radios") { //problem here
$("#msgbox1").fadeTo(200, 0.1, function() {
$(this).html('empty radios').addClass('messageboxerror1').fadeTo(900, 1);
});
}
}
EDIT: What is the best way to identify if the field that is empty is radios or age ?
thanks
If the result can be that only radios or age or none of both can be empty then you have to edit your check to !data.livres || data.livres == "radios" || data.livres == "age". It will then print the message if your json output is the following:
{livres: false}
or
{livres: "radios"}
or
{livres: "age"}
Edit: Changes according to your comment
if (!data.livre) { //problem here
// Do whatever you want to do when livres is false
} else if (data.livre == "radios") {
// Do whatever you want to do when livres is "radios"
} else if (data.livre == "age") {
// Do whatever you want to do when livres is "age"
}

Categories