I have a certain script for Feed back. - php

I have a certain script for Feed back. when i submit the form, it shows
"
Warning: substr() expects parameter 2 to be long, string given in /home/jetkvdmn/public_html/genFunctions.php on line 26"
the code below
<?php
$cEpro ="© Redeeming Mission 2012.";
function checkText($ElementVal) {
// If Text is too short
if (strlen($ElementVal)< 3) {
//alert('Text too small');
return false;
} else{
return true;
}
}
function checkEmail($vEmail) {
$invalidChars ="/:,;" ;
if(strlen($vEmail)<1) return false; // Invalid Characters
$atPos = stripos($vEmail,"#",1); // First Position of #
if ($atPos != false)
$periodPos = stripos($vEmail,".", $atPos); //If # is not Found Null . position
for ($i=0; $i<strlen($invalidChars); $i++) { //Check for bad characters
$badChar = substr($invalidChars,i,1); //Pick 1
if(stripos($vEmail,$badChar,0) != false) //If Found
return false;
}
if ($atPos == false) //If # is not found
return false;
if ($periodPos == "") //If . is Null
return false;
if (stripos($vEmail,"##")!=false) //If ## is found
return false;
if (stripos($vEmail,"#.") != false) //#.is found
return false;
if (stripos($vEmail,".#") != false) //.# is found
return false;
return true;
}
?>

$badChar = substr($invalidChars,i,1);
should be
$badChar = substr($invalidChars,$i,1);
^^^

You are passing i to the substr function, instead of $i

Related

PHP Return true in foreach

I want to check if the user is using the default settings. In the example below, I'm trying to check if all "foreached" items return true. If a single foreached item doesn't return true, return false on the whole function.
private function is_using_default_settings() {
// returns a huge array with settings
$merged_preset = $this->options_merged();
foreach($merged_preset as $preset) {
if($preset[5] == 1) {
$section = 'general';
} elseif($preset[5] == 2) {
$section = 'advanced';
} elseif($preset[5] == 3) {
$section = 'technical';
}
$option = get_option($section);
if($preset[3] == $option[$preset[0]] && !is_null($preset[1])) {
return true;
}
}
return false;
}
I've been brainstorming for the past few days to get this sorted on my own, but sadly cannot get it to work. What is the best approach to this?
you can check when is false and block the full foreach then return value, if all is true return value true
try this:
private function is_using_default_settings() {
$returnValue = true;
$merged_preset = $this->options_merged();
foreach($merged_preset as $preset) {
if($preset[5] == 1) {
$section = 'general';
} elseif($preset[5] == 2) {
$section = 'advanced';
} elseif($preset[5] == 3) {
$section = 'technical';
}
$option = get_option($section);
if($preset[3] != $option[$preset[0]] || is_null($preset[1])) {
$returnValue = false;
break;
}
}
return $returnValue;
}
You should return false when any check fails in the foreach, otherwise return true.
function check()
{
foreach($arr as $v)
{
//check fails
if(fail of the check)
return false;
}
return true;
}

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)));

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

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"){

How to clean and simplify this code?

After thinking about This Question and giving an answer to it I wanted to do more about that to train myself.
So I wrote a function which will calc the length of an given function. Th given php-file has to start at the beginning of the needed function.
Example: If the function is in a big phpfile with lots of functions, like
/* lots of functions */
function f_interesting($arg) {
/* function */
}
/* lots of other functions */
then $part3 of my function will require to begin like that (after the starting-{ of the interesting function):
/* function */
}
/* lots of other functions */
Now that's not the problem, but I would like to know if there are an cleaner or simplier ways to do this. Here's my function: (I already cleaned a lot of testing-echo-commands)
(The idea behind it is explained here)
function f_analysis ($part3) {
if(isset($part3)) {
$char_array = str_split($part3); //get array of chars
$end_key = false; //length of function
$depth = 0; //How much of unclosed '{'
$in_sstr = false; //is next char inside in ''-String?
$in_dstr = false; //is nect char inside an ""-String?
$in_sl_comment = false; //inside an //-comment?
$in_ml_comment = false; //inside an /* */-comment?
$may_comment = false; //was the last char an '/' which can start a comment?
$may_ml_comment_end = false; //was the last char an '*' which may end a /**/-comment?
foreach($char_array as $key=>$char) {
if($in_sstr) {
if ($char == "'") {
$in_sstr = false;
}
}
else if($in_dstr) {
if($char == '"') {
$in_dstr = false;
}
}
else if($in_sl_comment) {
if($char == "\n") {
$in_sl_comment = false;
}
}
else if($in_ml_comment) {
if($may_ml_comment_end) {
$may_ml_comment_end = false;
if($char == '/') {
$in_ml_comment = false;
}
}
if($char == '*') {
$may_ml_comment_end = true;
}
}
else if ($may_comment) {
if($char == '/') {
$in_sl_comment = true;
}
else if($char == '*') {
$in_ml_comment = true;
}
$may_comment = false;
}
else {
switch ($char) {
case '{':
$depth++;
break;
case '}':
$depth--;
break;
case '/':
$may_comment = true;
break;
case '"':
$in_dstr = true;
break;
case "'":
$in_sstr = true;
break;
}
}
if($depth < 0) {
$last_key = $key;
break;
}
}
} else echo '<br>$part3 of f_analysis not set!';
return ($last_key===false) ? false : $last_key+1; //will be false or the length of the function
}
Tokenizer (Example) - Learn it, love it.
You could probably reduce the number of state variables a little, but truthfully... yes, it will be messy code. I would probably get rid of $may_ml_comment_end and peek ahead for the next character when I encounter an asterisk, for example. You will need to rewrite your foreach loop to a regular for loop be able to do that without creating a bigger mess though.
PS: I don't see you handling the escape character yet. Without the above approach, that would introduce another boolean variable.
Another problem with your current code is that characters immediately following a / don't get interpreted as they should. However unlikely
echo 5/'2'; // NB: no space in between
is valid in PHP and would break your parser.

Categories