How can I add a json as part of a url? - php

The question seems quite simple, but I've tried everything that I've read and nothing worked
I have this example url: localhost/test/{"user":"test","password":"test"} so, that json is part of the url how can I add it? I tried the following things
$arrayVariable = array (
"Usuario" => "user",
"Clave" => "test"
);
$res = json_encode($arrayVariable);
but the answer of $res is the following
"{\"Usuario\":\"user\",\"Clave\":\"test\"}"
I've tried str_replace to remove backslashed but it didn't work, I tried the following two functions
$res = str_replace("\\","",$res)
$res = str_replace("\\\\","",$res)
but it didn't work because seems the backslash is part of the " quote
Edit: I can't change the url because is an external API so nothing I can do that way

You could use the urlencode() function.
$arrayVariable = array (
"Usuario" => "user",
"Clave" => "test"
);
$res = urlencode(json_encode($arrayVariable));
But i think you should re-think your logic since this is a very unusual thing to do.

Related

Stuck with REQUST_URI Parsing ( PHP )

I have a page working as I need it to, with the last /arist-name/ parsing into the correct variable, but the client is adding /artist-name/?google-tracking=1234fad to their links, which is breaking it.
http://www.odonwagnergallery.com/artist/pierre-coupey/ WORKS
http://www.odonwagnergallery.com/artist/pierre-coupey/?mc_cid=b7e918fce5&mc_eid=[UNIQID] DOES NOT WORK
$expl = explode("/",$_SERVER["REQUEST_URI"]);
$ArtistURL = $expl[count($expl)-1];
$ArtistURL = preg_replace('/[^a-z,-.]/', '', $ArtistURL);
Please help, I have been searching for a solution. Thanks so much!
PHP has a function called parse_url which should clean up the request uri for you before you try to use it.
parse_url
Parse a URL and return its components
http://php.net/parse_url
Example:
// This
$url_array = parse_url('/artist/pierre-coupey/?mc_cid=b7e918fce5&mc_eid=[UNIQID]');
print_r($url_array);
// Outputs this
Array
(
[path] => /artist/pierre-coupey/
[query] => mc_cid=b7e918fce5&mc_eid=[UNIQID]
)
Here is a demo: https://eval.in/873699
Then you can use the path piece to perform your existing logic.
If all your URLs are http://DOMAIN/artist/SOMEARTIST/
you could do:
$ArtistURL = preg_replace('/.*\/artist\/(.*)\/.*/','$1',"http://www.odonwagnergallery.com/artist/pierre-coupey/oij");
It would work in this context. Specify other possible scenarios if there are others. But #neuromatter answer is more generic, +1.
if you simply want to remove any and all query parameters, this single line would suffice:
$url=explode("?",$url)[0];
this would turn
http://www.odonwagnergallery.com/artist/pierre-coupey/?mc_cid=b7e918fce5&mc_eid=[UNIQID]&anything_else=whatever
into
http://www.odonwagnergallery.com/artist/pierre-coupey/
but if you want to specifically remove any mc_cid and mc_eid parameters, but otherwise keep the url intact:
$url=explode("?",$url);
if(count($url)===2){
parse_str($url[1],$tmp);
unset($tmp['mc_cid']);
unset($tmp['mc_eid']);
$url=$url[0].(empty($tmp)? '':('?'.http_build_query($tmp)));
}else if(count($url)===1){
$url=$url[0];
}else{
throw new \LogicException('malformed url!');
}
this would turn
http://www.odonwagnergallery.com/artist/pierre-coupey/?mc_cid=b7e918fce5&mc_eid=[UNIQID]&anything_else=whatever
into
http://www.odonwagnergallery.com/artist/pierre-coupey/?anything_else=whatever

Trouble Reading json Data from hasoffer API

Trying to read json Data and I can't get it to work correctly with the following code:
$apiurl = "https://api.hasoffers.com/Apiv3/json?NetworkId=REDACTED&Target=Affiliate_Report&Method=getStats&api_key=REDACTED&fields%5B%5D=Stat.conversions&fields%5B%5D=Stat.unique_clicks&fields%5B%5D=Stat.payout&filters%5BStat.date%5D%5Bconditional%5D=LESS_THAN&filters%5BStat.date%5D%5Bvalues%5D=2016-02-21&filters%5BStat.date%5D%5Bconditional%5D=GREATER_THAN&filters%5BStat.date%5D%5Bvalues%5D=2016-02-21";
$data = json_decode(file_get_contents($apiurl), true);
foreach($data['response']['data'] as $dataline) {
echo "Conversions: {$dataline['Stat']['conversions']} Payout: {$dataline['Stat']['payout']}";
}
The query is generating the following json return, I just can't figure out how to read the stats correctly (it's also looping through 7 lines in the foreach which also makes no sense to me):
{"request":{"Target":"Affiliate_Report","Format":"json","Service":"HasOffers","Version":"2","NetworkId":"REDACTED","Method":"getStats","api_key":"REDACTED","fields":["Stat.conversions","Stat.unique_clicks","Stat.payout"],"filters":{"Stat.date":{"conditional":"GREATER_THAN","values":"2016-02-21"}},"__gaTune":"GA1.2.1289716345.1455904273","__utma":"267117079.1377304869.1455903853.1455904273.1455904273.1","__utmc":"267117079","__utmz":"267117079.1455904273.1.1.utmcsr=developers.hasoffers.com|utmccn=(referral)|utmcmd=referral|utmcct=/","_biz_uid":"1742fd1f613440a4cfbb5a510d1d7def","_biz_nA":"1","_biz_pendingA":"[]","_hp2_id_1318563364":"5257773084071598.0276720083.0714677778","_ga":"GA1.2.1377304869.1455903853"},"response":{"status":1,"httpStatus":200,"data":{"page":1,"current":50,"count":1,"pageCount":1,"data":[{"Stat":{"conversions":"1000","unique_clicks":"1000","payout":"1000.000000"}}],"dbSource":"branddb"},"errors":[],"errorMessage":null}}
If your JSON is exactly that you have posted, it is unvalid JSON, as per the comments.
The invalid part is the REDACTED words without double-quote.
To bypass this error, you can try in this way:
$data = file_get_contents( $apiurl );
$data = preg_replace( '/:REDACTED(?=\W)/', ':"REDACTED"', $data );
$json = json_decode( $data, True );
This will works on example above, but please note that is a trick, and it can not work if some JSON field has a value like "sometext:REDACTED,sometext": it is improbable, but not impossible.
Actually thank you that site helped a lot realized there was a second array also labeled "data" under the first "data" array so I needed to change it to:
$data['response']['data']['data'] as $dataline

How to transform a php $string into a $string() function call?

My current code:
$operation = "alienFunction";
switch($operation){
case "alphaFunction":
alphaFunction();
break;
case "betaFunction":
betaFunction();
break;
case "alienFunction":
alienFunction($kidsPerPlanet, $planet);
break;
Ok, I have a big list of functions. Some functions have parameters and some have not. The $operation is received from a $_POST variable. I want to do something like this:
$operation = "alphafunction";
$operation();
Or
$operation = "alienFunction";
$operation($kidsPerPlanet, $planet);
As already written in the comments you are looking for call_user_func_array(). Just use it like this:
call_user_func_array($functionName, $argumentArray);
But since you don't know which function you call with which parameters, just define an array and then use the code above, e.g.
$arguments = [
"alphaFunction" => [],
"betaFunction" => [],
"alienFunction" => [$kidsPerPlanet, $planet],
];
call_user_func_array($functionName, $arguments[$functionName]);
Excellent.
Thanks, guys. For functions with no parameters, it's working perfectly.
I'm trying this now:
$userInfo = MySQL_FETCH_ARRAY( MySQL_QUERY( ($autoAuth) ) );
CALL_USER_FUNC_ARRAY($operation, $userInfo);
Inside of one of functions, I have this piece of code inserted into HTML:
ECHO "<p>" . VAR_DUMP($userInfo) . "</p>";
And the result gives me "string(2) "25".
I'm new here. So I don't know what to do. For sure, my question is answered. Now I know how to use a string to call a function. Should I close this, select the best answer and create another question? Should I let it open, while my WHOLE problem is solved? Or should I close it and still comment here to get feedback?
Thanks a lot. I'm loving this. I wish that I can contribute as soon as possible too. :)

simplexml_load_file with & (ampersand) in url with Solr

I am using Solr and have the following query which works fine from my browser:
http://www.someipaddress.com:8983/solr/select?q=*&fq=shopid:40&start=0&rows=18&fq=manufacturer:"Bausch+%26+Lomb"
In part of the return xml I see:
<str>manufacturer:"Bausch & Lomb"</str>
However when I try and get the above url using simplexml_load_file like this:
$xml = simplexml_load_file("http://127.0.0.1:8983/solr/select?q=*&fq=shopid:40&start=0&rows=18&fq=manufacturer:\"Bausch+%26+Lomb\"");
I get no results because Solr is being passed the manufacturer string that looks like this (from print_r):
[str] => Array ( [0] => shopid:40 [1] => manufacturer:"Bausch+%26+Lomb" )
So when I am doing the query through the browser I pass in %26 but it deals with it correctly in the query. But when I use simplexml_load_file it remains as %26 and so the query fails.
Try:
simplexml_load_file(rawurlencode('http://127.0.0.1:8983/solr/select?q=*&fq=shopid:40&start=0&rows=18&fq=manufacturer:"Bausch' .urlencode('&'). 'Lomb"'))
See note on file parameter: http://php.net/manual/en/function.simplexml-load-file.php
Didn't work:
$url = 'http://127.0.0.1:8983/solr/select?q=*&fq=shopid:40&start=0&rows=18';
$url .= '&fq=manufacturer:"Bausch' .urlencode('&'). 'Lomb"';
simplexml_load_file(rawurlencode($url));
Manufacturer part of query came out as: "Bausch&Lomb";
Didn't work:
simplexml_load_file(rawurlencode('http://127.0.0.1:8983/solr/select?q=*&fq=shopid:40&start=0&rows=18&fq=manufacturer:"Bausch ' .urlencode('&'). ' Lomb"'))
Adding spaces next to the words Bausch and Lomb produced simplexml_load file error.
Worked:
simplexml_load_file(rawurlencode('http://127.0.0.1:8983/solr/select?q=*&fq=shopid:40&start=0&rows=18&fq=manufacturer:"Bausch+' .urlencode('&'). '+Lomb"'))
Swapping spaces for + works!
This is how I ended up doing it dynamically.
$manufacturer = urlencode("Bausch & Lomb");
$manufacturer_insert = "&fq=manufacturer:\"$manufacturer\"";
$xml = simplexml_load_file(rawurlencode("http://127.0.0.1:8983/solr/select?q=$shopid_insert$start_insert$rows_insert$sort_insert$manufacturer_insert"));
That works for manufacturers with an ampersand in their name.
It is important to note that if you were passing values with spaces they will now need to be urlencoded before being added. For example:
Before I could just use this for my sort insert:
$sort_insert = "&sort=price desc";
Now I need to urlencode just "price desc". When I tried to urlencode the whole sort_insert string the simplexml query would fail.
After (works):
$sort = urlencode("price desc");
$sort_insert = "&sort=$sort";
Thanks again... Back to the project!

PHP preg_replace problem

This is a follow-up question to the one I posted here (thanks to mario)
Ok, so I have a preg_replace statement to replace a url string with sometext, insert a value from a query string (using $_GET["size"]) and insert a value from a associative array (using $fruitArray["$1"] back reference.)
Input url string would be:
http://mysite.com/script.php?fruit=apple
Output string should be:
http://mysite.com/small/sometext/green/
The PHP I have is as follows:
$result = preg_replace('|http://www.mysite.com/script.php\?fruit=([a-zA-Z0-9_-]*)|e', ' "http://www.mysite.com/" .$_GET["size"]. "/sometext/" .$fruitArray["$1"]. "/"', $result);
This codes outputs the following string:
http://mysite.com/small/sometext//
The code seems to skip the value in $fruitArray["$1"].
What am I missing?
Thanks!
Well, weird thing.
Your code work's perfectly fine for me (see below code that I used for testing locally).
I did however fix 2 things with your regex:
Don't use | as a delimiter, it has meaning in regex.
Your regular expression is only giving the illusion that it works as you're not escaping the .s. It would actually match http://www#mysite%com/script*php?fruit=apple too.
Test script:
$fruitArray = array('apple' => 'green');
$_GET = array('size' => 'small');
$result = 'http://www.mysite.com/script.php?fruit=apple';
$result = preg_replace('#http://www\.mysite\.com/script\.php\?fruit=([a-zA-Z0-9_-]*)#e', ' "http://www.mysite.com/" .$_GET["size"]. "/sometext/" .$fruitArray["$1"]. "/"', $result);
echo $result;
Output:
Rudis-Mac-Pro:~ rudi$ php tmp.php
http://www.mysite.com/small/sometext/green/
The only thing this leads me to think is that $fruitArray is not setup correctly for you.
By the way, I think this may be more appropriate, as it will give you more flexibility in the future, better syntax highlighting and make more sense than using the e modifier for the evil() function to be internally called by PHP ;-) It's also a lot cleaner to read, IMO.
$result = preg_replace_callback('#http://www\.mysite\.com/script\.php\?fruit=([a-zA-Z0-9_-]*)#', function($matches) {
global $fruitArray;
return 'http://www.mysite.com/' . $_GET['size'] . '/sometext/' . $fruitArray[$matches[1]] . '/';
}, $result);
i write it again, i don't understand good where is the error, the evaluation of preg results is very weird in php
preg_replace(
'|http\://([\w\.-]+?)/script\.php\?fruit=([\w_-]+)|e'
, '"http://www.$1/".$_GET["size"]."/sometext/".$fruitArray["$2"]."/";'
, $result
);
It looks like you have forgotten to escape the ?. It should be /script.php\?, with a \? to escape properly, as in the linked answer you provided.
$fruitArray["\$1"] instead of $fruitArray["$1"]

Categories