I am building a hyperlink that includes a base64 encoded set of parameters as shown below:
$params = base64_encode("member_id={$recipient_id}&api_key=".SECRET_KEY);
$link = HOST_ADDRESS."test.php?k=" . $params;
When the link is executed, the following code runs:
// get the encoded string from the link parameter
$link_parm = $_GET['k'];
$link = substr($link_parm, 0);
// url encode the string to ensure all special characters convert properly - attempt to stop errors
urlencode($link);
// decode the rest of the link
$decoded_link = base64_decode($link);
// get the remaining data elements from the link parameter
$msg_data = preg_split( "/[&=]/", $decoded_link);
On occasion, the $msg data is corrupted and looks like this:
member_id=167œÈ&api_key=secretkey
As you can see the member id is corrupted.
Can someone please help me understand what may be causing this?
Thanks.
For starters, there are a few problems with this beside the issue you describe.
What are you trying to do using $link = substr($link_parm, 0);? This could just be written as $link = $link_parm;. Or, you could of course just do $link = $_GET['k']; or even just use $_GET['k'].
urlencode($link); does nothing as you're not catching its result. The argument is not passed by reference.
Your "attempt to stop errors" should probably be handled differently. By throwing an error when you're receiving unexpected input, for instance.
Related
Currently I am trying to fiddle around with the Deezer API and running into a slight issue, I am trying to gather content from this artist.
XYLØ - Nothing Left To Say
https://api.deezer.com/search/track?q=XYLØ - Nothing Left To Say
The page above displays the content in a JSON format, however when I use the following code.
$id = 'XYLØ - Nothing Left To Say';
$h = str_replace(' ', '+', $id);
$json_string = 'https://api.deezer.com/search/track?q='.$h;
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata,true);
I get an empty pallet on my image request.
$obj['data'][0]['album']['cover_medium']
Any ideas on how I can get this to work properly?
Use PHP's built in function for query args,
//changed $h to $id (see below)
$json_string = 'https://api.deezer.com/search/track?q='.urlencode($id);
http://php.net/manual/en/function.urlencode.php
This function is convenient when encoding a string to be used in a query part of a URL, as a convenient way to pass variables to the next page.
You can also do away with this stuff (AKA remove it):
$h = str_replace(' ', '+', $id);
As urlencode does that to!!!.
As a Bonus
You can use
http://php.net/manual/en/function.http-build-query.php
http_build_query — Generates a URL-encoded query string from the associative (or indexed) array provided.
To build the whole query string from an array, which I figure may be useful to someone reading this...
I have a php page which get response from another page as shown:
while($response!=200)
{
$response = include 'xyz.php?one='.$one.'&two='.$two.'&three='.$three.'';
}
But my link always get's something like:
domainname.com/xyz.php?one=content&two=content&three=content
And due to & getting replaced by & I am getting the page not found issue.
I have tried using %26 and directly putting & instead of &, all in vain.
Is there any other simple solution besides using string replace function of PHP to remove & and replace it with &
Check out html_entity_decode
$response = html_entity_decode($response)
I ran a test based on the code you sent and I don't have a problem. That suggests you have something auto-magical going on in your *.ini file (magic quotes, maybe... ugh...). Try to create the string simply as a variable to remove it from the filename context and echo it out to be sure it's right, then use the variable with your include.
$one = 'abc';
$two = 'def';
$three = "ghi";
$file= 'xyz.php?one='.$one.'&two='.$two.'&three='.$three;
echo "\n\n".$file;
$response = include $file;
You can't use URL parameters when accessing a local file, they have to go through the webserver. Try:
$response = file_get_contents("http://localhost/path/to/xyz.php?one='.$one.'&two='.$two.'&three='.$three);
I get a string, from an external clientside script, which must later be attached as part of an url. Now I am wondering what is the best way to santitize such data?
The string I get will have a structure like this:
dynamicVal#staticVal:dynamicVal
This value will then be added to an url:
http://the-page.com/dynamicVal#staticVal:dynamicVal
The url is then used as followed:
$link = htmlspecialchars("http://external-page.com/dynamicVal#staticVal:dynamicVal", ENT_QUOTES);
$var = "'Open URL'";
Problem is, htmlspecialchars wont help to prevent execution of random javascript code, e.g. by adding this alert to the value:
dynamicVal#staticVal:dynamicVal'+alert(\"breakout\")+'
Using rawurlencode wont help either, because it is not a value of a parameter but a real part of the url.
So what is the best way to sanitize the passed string when concatenating to the url?
Thanks in advance.
Edit:
Using rawurlencode only on the dynamic parts actually also didn't solve the issue, the javascript still got executed.
Test snippet:
$splitVal = "#staticVal:";
$tmpArr = explode($splitVal, "dynamicVal#staticVal:dynamicVal'+alert(\"breakout\")+'");
$link = htmlspecialchars(sprintf("http://external-page.com/"."%s$splitVal%s", rawurlencode($tmpArr[0]), rawurlencode($tmpArr[1])), ENT_QUOTES);
echo "'Open URL'";
Edit2:
Using json_encode when passing the string as javascript argument didn't help either.
Adapted test snippet:
$splitVal = "#staticVal:";
$tmpArr = explode($splitVal, "dynamicVal#staticVal:dynamicVal\"+alert('breakout')+\"");
$link = htmlspecialchars(sprintf("http://external-page.com/"."%s$splitVal%s", rawurlencode($tmpArr[0]), rawurlencode($tmpArr[1])), ENT_QUOTES);
echo "'Open URL'";
Adaptions done:
Switched the quotes in the malicous JS.
Moved htmlspecialchars around json_encode, because a double quoted string gets returned which would break the html otherwise.
You should use urlencode() for this. Not on the whole string but on the dynamic parts only.
$link = sprintf('http://external-page.com/%s#staticVal:%s', urlencode('dynamicVal'), urlencode('dynamicVal'));
$var = "'Open URL'";
EDIT:
OK - I see your problem. I didn't realize that you insert the code into a JavaScript function call. You'll have to ensure that the JavaScript interpreter treats your link as a string argument to window.open():
$link = sprintf('http://external-page.com/%s#staticVal:%s', urlencode('dynamicVal'), urlencode('dynamicVal'));
$var = "'Open URL'";
For completenes, I was able to solve that issue by simply putting addslashes on the dynamic part before using rawurlencode.
Both function calls are needed to prevent breaking out. Using addslashes prevents normal quotes (',") and rawurlencode prevents already encoded quotes (%29,%22) to cause harm.
So final solution looks like this:
$splitVal = "#staticVal:";
$tmpArr = explode($splitVal, "dynamicVal#staticVal:dynamicVal'+alert(\"breakout\")+'");
$link = htmlspecialchars(sprintf("http://external-page.com/"."%s$splitVal%s", rawurlencode(addslashes($tmpArr[0])), rawurlencode(addslashes($tmpArr[1]))), ENT_QUOTES);
echo "'Open URL'";
i have a variable in flash that takes its value from a php file using the print function.
The variable is not returning the correct value. It's returning "undefined". I have checked of both flash and php source code for errors, they both seem the be fine.
anyone know what could be causing this?
php print code:
print "return_sponsor=$sponsor";
flash code:
function completeHandler(event:Event):void{
// Clear the form fields
name_txt.text = "";
email_txt.text = "";
MovieClip(parent).gotoAndPlay("finish");
// Load the response from the PHP file
variables.sponny = event.target.data.return_sponsor;
I've not used AS3 in a while, but this might work.
Replace:
variables.sponny = event.target.data.return_sponsor;
With:
var data:URLVariables = new URLVariables(event.target.data);
variables.sponny = data.return_sponsor;
I don't know what type your sponny variable is but that error is generally returned when Flash can't convert types correctly. It happens to me if I am trying to convert a string to a Number or int (or some other numeric type) and there is a non-numeric symbol in the string (so "12a4" would not be able to convert properly for example).
When you are debugging, place event.target.data.return_sponsor in a String variable and check that it is the correct data. If you can't debug, you may have to find a way to show the data on the screen somehow (maybe by printing them to the form?)
name_txt.text = event.target.data.return_sponsor;
I have a problem in my code and I can't figure out what's wrong with it. Perhaps I'm doing some really stupid things I'm not aware of, since I'm a newbie in these topics. Here's the thing... Basically, I'm trying to get a JSON object as a response from a PHP page on my web-server via a NSURLConnection. The PHP page retrieves some info from a DB and then encodes the JSON object, which is simply an array of four numerical strings, e.g., ["1","2","3","4"]. The relevant part of the PHP page is:
<?php
include('mylib.php');
$id = $_GET["id"];
$db = connection();
$stmt = "SELECT col1,col2,col3,col4 FROM mytable WHERE `id` = " .$id;
$ris = mysql_query($stmt,$db);
if ($ris && mysql_num_rows($ris) == 1) {
$arr = mysql_fetch_array($ris);
header('Content-type: application/json');
header("Content-Disposition: attachment; filename=res.json");
$json = json_encode(array($arr[0],$arr[1],$arr[2],$arr[3]));
echo $json;
?>
While I'm getting the data I expect in the format I want when I download the file from a browser, the JSON attachment file starts with an unwanted new line character: in this way, it appears the NSURLConnection stops immediately (I just get the '\n'). I'm not reporting the code for the networking part: it's very standard and it should be correct, since it works for other stuff I do... I tried to remove '\n' through:
$json = trim($json);
but it did't work. The new line is still there. Where does it come from? What should I do? Hope you guys can help me solve this issue... Thanks in advance!
EDIT
Ok! I don't have the new line char anymore (I removed a '\n' at the beginning of mylib.php), but I can't get the JSON object yet via NSURLConnection. It seems the method
connection:didReceiveData:
is never called now. But I don't have error in the connection: it simply receives 0 byte. Note that when I had the '\n' at the beginning, I received 1 byte. From a browser it works perfectly. What should I do?
I know this might sound obvious, but try looking in front of the opening <?php tag.
edit: or possibly at the end of "mylib.php".