I wanted to do some checking if a string (json), that is been post via a curl call, starts with a specific sub-string. When I kept getting return FALSE
instead of TRUE
I tried to debug it. I first adjusted my code so it will accept $_GET
instead of $_POST
so I can pass along a query string in the url. I always sanitize the data passed in but it seems like my problem has to do with that.
I did an echo var_dump();
on the data and saw that the string count isn't equal for with and without sanitizing.
This is the json: [{"userProfileUrl":"/users/jDoe","avatar":"/images/1.jpg","name":"John Doe","id":1}]
This is how the url for debugging purpose looks like:
example.com?file=[{"userProfileUrl":"/users/jDoe","avatar":"/images/1.jpg","name":"John Doe","id":1}]
This is the code to do the checking:
function verifyFileStart($string, $startString)
{
$len = strlen($startString);
return (substr($string, 0, $len) === $startString);
}
This is with sanitizing:
<?php
define("STARTSWITH", '[{"userProfileUrl":"');
$file = $_GET['file'];
// With Sanitize
$file = filter_var($file, FILTER_SANITIZE_STRING);
$part = STARTSWITH;
echo var_dump(verifyFileStart($file, $part));
echo nl2br("\n\n");
echo var_dump($file);
echo nl2br("\n\n");
echo var_dump($part);
// Here is the function (verifyFileStart) that does the checking
?>
var_dump() Output:
bool(false)
string(128) "[{"userProfileUrl":"/users/jDoe","avatar":"1","name":"John Doe","id":1}]"
string(20) "[{"userProfileUrl":""
This is without sanitizing:
<?php
define("STARTSWITH", '[{"userProfileUrl":"');
$file = $_GET['file'];
/* Without Sanitize
$file = filter_var($file, FILTER_SANITIZE_STRING);*/
$part = STARTSWITH;
echo var_dump(verifyFileStart($file, $part));
echo nl2br("\n\n");
echo var_dump($file);
echo nl2br("\n\n");
echo var_dump($part);
// Here is the function (verifyFileStart) that does the checking
?>
var_dump() Output:
bool(true)
string(72) "[{"userProfileUrl":"/users/jDoe","avatar":"1","name":"John Doe","id":1}]"
string(20) "[{"userProfileUrl":""
Why is the first output with sanitize 128 and the output without sanitize 72?
My function verifyFileStart($string, $startString)
only seems to say the sub-string is found in the string if not sanitized. How should I deal with this and make it work with sanitized data?
Thanks in advance!