I'm writing an amfPHP function which should take string input. It takes alphanumeric characters without a problem, but unfortunately it returns data as "2" if I send "2.UgnFl4kAWovazp_tVo6fHg__.86400.1260025200-571701419" as parameter.
here is the function (real simple as you can see)
function checkOpenSession($guid, $session_key) {
return $session_key;
}
To bypass this service browser bug, double quote your entry on the service browser if you expect a string on an argument and this string starts with a number. I was having the same problem testing some methods via service browser and it worked fine.
I just tried this with a simple setup, and just writing the results to a file from the service browser and it seems to be ok for me. So the problem would seem to be in the calling end.
Another possibility is that amfphp changes the datatype of the returned value from a string to an int because of the leading integer. Try putting a some alphanumeric character at the start of the return string and see what that does.
This behavior is actually present in the AMFPHP service browser(bug), so it is easy to mistake it as the AMFPHP that is converting number-leading strings to int. However the problem is in the sending code. For instance sending a urlencoded string through the json gateway works properly (Objective C code):
NSString *theUrl = [[NSString alloc] initWithFormat:#"%#/modules/amfphp/amfphp/json.php/MysqlRemoting.checkAuth/%#/%#/1", kServerBaseUrl, userName, passMD5];
NSString *encodedUrl = [theUrl stringByAddingPercentEscapesUsingEncoding: NSASCIIStringEncoding];
Where passMD5 may have a leading number. But if I enter appropriate values for the checkAuth method in the service browser, it is broken.
[edit]
$value = urldecode($value);
if($value != "") {
if($value[0] != '[' && $value[0] != '{' && $value != "null" && $value != "false" && $value != "true") {
$hasAlpha = false;
//check to see if it is a number
$sl = strlen($value);
for ($i = 0; $i < $sl; $i++) {
$char1 = ord($value[$i]);
if($char1 >= 0x30 && $char1 <= 0x39) {
//Then this is a number
} else { //Else leave value as is */
$hasAlpha = true;
}
}
if (!$hasAlpha) $value = json_decode($value, true);
}
else
{
$value = json_decode($value, true);
}
}
double quote your strings... that will work it out.
Related
your text
The above warning is displayed in PHP 8.1 after upgrading from PHP 7.4
Any ideas on how this code can be changed for PHP 8.1 compatibility?
private function cleanInput2($strRawText, $strAllowableChars, $blnAllowAccentedChars)
{
$iCharPos = 0;
$chrThisChar = "";
$strCleanedText = "";
//Compare each character based on list of acceptable characters
while ($iCharPos < strlen($strRawText))
{
// Only include valid characters **
$chrThisChar = substr($strRawText, $iCharPos, 1);
if (strpos($strAllowableChars, $chrThisChar) !== FALSE)
{
$strCleanedText = $strCleanedText . $chrThisChar;
}
elseIf ($blnAllowAccentedChars == TRUE)
{
// Allow accented characters and most high order bit chars which are harmless **
if (ord($chrThisChar) >= 191)
{
$strCleanedText = $strCleanedText . $chrThisChar;
}
}
$iCharPos = $iCharPos + 1;
}
return $strCleanedText;
}
You should check your $strRawText to ensure it's not null before passsing to strlen(). This can be done either with explicit check or adding typehint.
You can also alternatively use null coalescing; which is more concise.
while ($iCharPos < strlen($strRawText ?? '')) ...
This question already has answers here:
The 3 different equals
(5 answers)
Closed 7 years ago.
I'm trying to compare two strings (one from my database and another supplied by the user) and see if they match! The problem I'm having is that they don't seem to match - even though the strings seems to be exactly identical?
My PHP code is below:
public function Verify($pdo, $id, $token) {
$prepsql = $pdo->prepare("SELECT * FROM Profiles WHERE id = '$id' LIMIT 1");
$prepsql->execute();
$currentrow = $prepsql->fetch();
$current = preg_replace("/[^a-zA-Z0-9]+/", "", $currentrow["token"]);
echo '<p>'.var_dump($current).'</p>';
echo '<p>'.var_dump($token).'</p>';
$token = preg_replace("/[^a-zA-Z0-9]+/", "", $token);
if ($current == null || $current = "") {
return false;
} else {
if (strcmp($token, $current) == 0) {
return true;
} else {
return false;
}
}
}
And here is the webpage output:
string(244) "CAAW4HRuZBuB4BACA7GffOAwLHgmLgMMLGQxDAw8IJDCwahZAh0S4wZAcP8Q9DmMwsDpBq7jFcH1EzUIsZBbhKov12utoYFQns0HhgB5xKLeDqtZBRqavaNjNSn7KAcObZAEcavQCRbGlVKZBArfDEHskBSR8qAoU543DVTZCOyHm5oYNDVafwHl0bAkc4jyIhh2YHEPaNpWGC0FhezsSidOgLjnfFq8CeLVxHH0nUZBMLgAZDZD"
<p></p>string(244) "CAAW4HRuZBuB4BACA7GffOAwLHgmLgMMLGQxDAw8IJDCwahZAh0S4wZAcP8Q9DmMwsDpBq7jFcH1EzUIsZBbhKov12utoYFQns0HhgB5xKLeDqtZBRqavaNjNSn7KAcObZAEcavQCRbGlVKZBArfDEHskBSR8qAoU543DVTZCOyHm5oYNDVafwHl0bAkc4jyIhh2YHEPaNpWGC0FhezsSidOgLjnfFq8CeLVxHH0nUZBMLgAZDZD"
<p></p><p>Not authenticated</p>
Not authenticated just means that this function is returning false...
What on earth am I doing wrong? As per advice given on other similar Stack Overflow answers, I've used the regex function to basically only keep alphanumeric characters but that has made no difference? It isn't a trimming issue either as that didn't work!
Any help would be much appreciated!
Thanks!
Here is your problem:
if ($current == null || $current = "") {
// ^ now `$current` is "", an empty string
You assign a new value to $current, an empty string.
You probably want something like:
if ($current == null || $current == "") {
// ^^ now you are comparing
I want to make a db_queryf function for my database abstraction. It will work somewhat like sqlite3_mprintf from SQLite: db_queryf('select * from pages where name=%q', $_GET['name']), where %q will produce a properly escaped string. What is the proper way of making printf-like functions in PHP? Is there any helper functions for that or I should parse it myself?
I am confused... (s)printf plainly allready exists, and you probably want to use SQLite3Stmt::bindValue more for this, unless you want to end up in escaping / sql-injection hell..
Use PDO prepared statements. Replacing into the string isn't good enough, you should be sanitizing.
sprintf()
sprintf('select * from pages where name=\'%s\'', $_GET['name']);
Its very important, that you sanitize everything in $_GET, before you use it!
okay, since I had exactly the same problem, I gave it a shot, and it seems to work quite nicely.
The following function sits inside a database wrapping class, and expects to be called like printf, where %% is transformed to a literal %, %e marks a string argument to be escaped, and %u marks a string argument to taken as-is.
LOGDB is a second database wrapping class, that is responsible for catching and logging all kinds of errors.
public static function query($format)
{
$query = $format . ' ';
$argc = func_num_args();
$argv = func_get_args();
$index_query = 0;
$index_args = 1;
while (($index_query = strpos($query, '%', $index_query)) !== false)
{
switch ($query[$index_query + 1])
{
case '%':
$query = substr_replace($query, '', $index_query, 1);
$index_query++;
break;
case 'e':
if ($index_args >= $argc)
{
LOG::failedQuery($format, "not enough arguments for format");
return false;
}
$query = substr_replace($query, DB::escape($argv[$index_args]), $index_query, 2);
$index_query += strlen($argv[$index_args]);
$index_args++;
break;
case 'u':
if ($index_args >= $argc)
{
LOG::failedQuery($format, "not enough arguments for format");
return false;
}
$query = substr_replace($query, $argv[$index_args], $index_query, 2);
$index_query += strlen($argv[$index_args]);
$index_args++;
break;
default:
LOG::failedQuery($format, "unknown control sequence '%" . $query[$index_query + 1] . "'");
return false;
}
}
if ($index_args != $argc)
{
LOG::failedQuery($format, "too many arguments for format");
return false;
}
$res = mysqli_query(self::$handle, $query);
if (!$res)
LOGDB::failedQuery($query, mysqli_error(self::$handle));
return $res;
}
Note: the code is mostly untested, chances are, it contains a bunch of bugs. use with caution :)
I am attempting to write a recursive descent parser in PHP for the following EBNF:
EXP ::= < TERM > { ( + | - ) < TERM > }
TERM ::= < FACTOR > { ( * | / ) < FACTOR > }
FACTOR ::= ( < EXP > ) | < DIGIT >
DIGIT ::= 0 | 1 | 2 | 3
I followed this guide which I saw recommended on a similar question. (I searched before I posted)
For the most part, I get how it works and I understand the grammar. I think the problem is within my syntax. I am new to PHP, so I have been referencing W3Schools. I currently am getting the following error with my code:
Warning: Wrong parameter count for exp() .... on line 101
I have tried to look up this error and have not had much luck. I read some posts about people passing in the wrong parameter typed, but I do not have any parameters set for that function. Is there something about PHP I am missing here?
Below is my code, I think the logic is correct since I based it off of the parse tree for the grammar. The $input will be coming from a form box on an HTML page. I also picked up the str_split function from a different post when I discovered that PHP4 does not have it built in.
<html>
<body>
<?php
if(!function_exists("exp")){
function exp(){
term();
while($token == "+" | $token == "-"){
if($token == "+"){
match("+");
term();
}
if($token == "-"){
match("-");
term();
}
}
}//end exp
}
if(!function_exists("term")){
function term(){
factor();
while($token == "*" | $token == "/"){
if($token == "*"){
match("*");
factor();
}
if($token == "/"){
match("/");
factor();
}
}
}//end term
}
if(!function_exists("factor")){
function factor(){
if($token == "("){
match("(");
exp();
if($token == ")")
match(")");
}
else if($token == 0|1|2|3){
if($token == 0)
match(0);
if($token == 1)
match(1);
if($token == 2)
match(2);
if($token == 3)
match(3);
}
else
error();
}//end factor
}
if(!function_exists("match")){
function match($expected){
if($token == $expected)
nextToken();
else
error();
}//end match
}
if(!function_exists("next_Token")){
function nextToken(){
$next++;
$token = $tokenStr[$next];
if($token == "$");
legal();
}
}
if(!function_exists("error")){
function error(){
echo "Illegal token stream, try again";
}
}
if(!function_exists("legal")){
function legal(){
echo "Legal token stream, congrats!";
}
}
if(!function_exists('str_split')) {
function str_split($string, $split_length = 1) {
$array = explode("\r\n", chunk_split($string, $split_length));
array_pop($array);
return $array;
}
}
$tokenStr = str_split($input);
$next = 0;
$token = $tokenStr[0];
exp();
?>
</body>
</html>
So basically I want to know what causes that error and why and am I on the right track in terms of creating this parser.
I appreciate any comments, suggestions, criticisms, water baloons, and tomatoes. Thank you for taking the time to read my post. Have a great day/night.
exp() is a builtin PHP function. You cannot define it under that name.
You should have no reason to use the if(!function_exists(' idiom in normal PHP applications. (It's often used more as a workaround when include scripts clash or identical functions are declared at different places.)
Another syntax problem that I noticed is your use of the bitwise OR. The logical OR should be || or just or.
while($token == "*" | $token == "/"){
I'll turn my wild guess into an answer. So maybe this is, where the problem lies?
http://php.net/manual/en/function.exp.php
There is also a function named exp() in PHP already. You may prefix your function names somehow, or it's better to use classes to avoid name collisions.
I`m wonder why this not working
echo gettype($_GET['id']); //returns string
if(is_int($_GET['id']))
{
echo 'Integer';
}
How to validate data passing from GET/POST if it is integer ?
Can use
$validatedValue = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
See http://php.net/filter_input and related functions.
The manual says:
To test if a variable is a number or a
numeric string (such as form input,
which is always a string), you must
use is_numeric().
Alternative you can use the regex based test as:
if(preg_match('/^\d+$/',$_GET['id'])) {
// valid input.
} else {
// invalid input.
}
What about intval?
$int = intval($_GET['id']);
To validate form data (string) as an integer, you should use ctype_digit()
It returns TRUE if every character in the string text is a decimal digit, FALSE otherwise.
(PHP 4 >= 4.0.4, PHP 5)
Reference: http://php.net/manual/en/function.ctype-digit.php
Try:
if(isNumeric($_GET['id'])) {
$cast_int = (int)$_GET['id'];
}
if(isset($cast_int)) {
echo gettype($cast_int)."<br />\n";
if(is_int($cast_int))
{
echo 'Integer'."<br />\n";
}
} else {
echo gettype($_GET['id'])." was passed<br />\n";
}
function isNumeric($numeric) {
return preg_match("/^[0-9]+$/", $numeric);
}
It sounds like you are checking if a string contains an integer, rather than if that variable is an integer. If so, you should check out php's regex (regular expression) functionality. It allows you to check for very specific patterns in a string to validate it for whatever criteria. (such as if it contains only number characters)
Here's the php page
http://php.net/manual/en/function.preg-match.php
and here's a cheat sheet on regular expressions (to make the $pattern string)
http://regexpr.com/cheatsheet/
I take a slightly more paranoid approach to sanitizing GET input
function sanitize_int($integer, $min='', $max='')
{
$int = intval($integer);
if((($min != '') && ($int < $min)) || (($max != '') && ($int > $max)))
return FALSE;
return $int;
}
To be even safer, you can extract only numbers first and then run the function above
function sanitize_paranoid_string($string, $min='', $max='')
{
$string = preg_replace("/[^a-zA-Z0-9]/", "", $string);
$len = strlen($string);
if((($min != '') && ($len < $min)) || (($max != '') && ($len > $max)))
return FALSE;
return $string;
}
Code from: http://libox.net