Alternative to curl_init()? - php

I'm trying to debug some code using either of these two intrepreters. The code below runs on my GoDaddy site and produces the appropirate output arrays. But, won't run in either of these intrepreters.
Is there a way to modify this code to run in the intrepreters so I can get past line 2 of the code? I inclcuded phpinfo(INFO_MODULES); at the end as an aid.
OR do you know of an online intrepreter that will run this code?
https://3v4l.org/
http://www.runphponline.com/
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = '';
curl_setopt($ch, CURLOPT_URL, "https://api.iextrading.com/1.0/stock/market/batch?symbols=aapl,tsla,ge&types=quote,earnings,stats");
$data = curl_exec($ch);
curl_close($ch);
$data = json_decode($data, true);
// debug -------------------------------
echo ' - ';
echo (count($data)); // number of elements
echo " - " . "<br />\n";
var_dump_pre($data); // dump the array
echo "-" . "<br />\n";
echo "xxxxxxxxxxxxxx-" . "<br />\n";
function var_dump_pre($mixed = null) {
echo '<pre>';
var_dump($mixed);
echo '</pre>';
return null;
}
phpinfo(INFO_MODULES);
?>

http://php.net/manual/en/curl.installation.php
It looks like there are some dependancies that you have to install to use curl_init.
It looks like some poor sap did the work for you at http://phpfiddle.org/
Your code works there.

Since the code ran on my GoDaddy site I was able to copy the data returned from the '$data = curl_exec($ch);' insruction and assign it to a variable name at the start of the code I'm trying to debug. So, the code I'm trying to debug starts out with the intended incomimg data (and doesn't have to go get it). I can now continue to use any of these three online intrepreters:
https://3v4l.org/
http://www.runphponline.com/
http://phpfiddle.org/

Related

PHP - How to share JSON data between files

So I'm trying to make a simple API, I have tried lots of different things. I want to show a random number on my JSON object and a token to go with it, then store both in a database. I don't want this to happen when you visit the webpage I want the data to get sent to a DB and generated from a separate page.
The first step in this is getting data from a different file.
Here's what I tried first:
index.php:
<?php
$odds = rand(1, 100);
?>
<pre style="word-wrap: break-word; white-space: pre-wrap;">
{
"odds": <?php echo $odds;?>
}
</pre>
Here's the file I'm trying to get the data from:
<?php
$url = "https://flugscoding.com/random/";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, "Riverside API");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
if(!$response = curl_exec($ch)) {
echo curl_error($ch);
}
curl_close($ch);
$data = json_decode($response, true);
echo $data->odds;
?>
Error:
Notice: Trying to get property 'odds' of non-object in D:\xxamp\htdocs\random\perp.php on line 16
What I tried after:
index.php:
<?php
$values = array("odds"=>rand(1, 100));
echo json_encode($values);
?>
Here's the file I'm trying to get the data from:
<?php
$json = file_get_contents("index.php");
echo $json;
// echo $json->odds;
?>
Error:
It doesn't show any data or errors, just a blank screen.
Does anyone have any solutions to this problem? I'm trying to make a provably fair system for a friend.
You're really close in both your examples:
#1
$data = json_decode($response, true);
echo $data->odds;
You're passing true into json_decode which makes it an associative array, not an object. So you will need to get the odds with $data['odds']; instead.
#2
$json = file_get_contents("index.php");
echo $json;
file_get_contents can either fetch a local file or remote file. In this case, you're passing a local file, so $json is the contents of the PHP code.
You can either:
(a) redesign it so that index.php is a function, and you can call the function from different files
(b) call index.php remotely and parse the results
a. Create a function in index.php that can get the odds:
<?php
function getData() [
return array("odds"=>rand(1, 100));
}
Then, in another file, you can:
<?php
require_once 'index.php';
$data = getData(); //now you have access to $data['odds'];
b. Call index.php remotely, like this:
$json = file_get_contents("http://localhost/index.php");
print_r(json_decode($json, true));

how loop through a JSON Array of bitcoin transaction data

My code is:
$requesturl='https://blockchain.info/tx-index/1fda663d2584425f192eae045d3809950883ebe50f2222f98ef7d31f414f3f96?format=json';
$ch=curl_init($requesturl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$cexecute=curl_exec($ch);
curl_close($ch);
$result = json_decode($cexecute,true);
// to get the first i use
echo $result['out'][0]['addr'];
to get the second I use
echo $result['out'][0]['addr'];
Now my requirement is to look through the array using for each but its throwing error:
foreach ($result['out'] as $adressee) {
echo $adressee.'<br>';
}
for($i=0; $i<count($result['out']); $i++) {
echo $result['out'][$i]["addr"].'<br>';
}
Some Sample codes in PHP manual helped me come up with this solution

Optimizing PHP Code and Storing JSON response to parse it faster?

so I'm trying to figure out why does this PHP code takes too long to run to output the results.
for example this is my apitest.php and here is my PHP Code
<?php
function getRankedMatchHistory($summonerId,$serverName,$apiKey){
$k
$d;
$a;
$timeElapsed;
$gameType;
$championName;
$result;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://".$serverName.".api.pvp.net/api/lol/".$serverName."/v2.2/matchhistory/".$summonerId."?api_key=".$apiKey);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
curl_close($ch);
$matchHistory = json_decode($response,true); // Is the Whole JSON Response saved at $matchHistory Now locally as a variable or is it requested everytime $matchHistory is invoked ?
for ($i = 9; $i >= 0; $i--){
$farm1 = $matchHistory["matches"][$i]["participants"]["0"]["stats"]["minionsKilled"];
$farm2 = $matchHistory["matches"][$i]["participants"]["0"]["stats"]["neutralMinionsKilled"];
$farm3 = $matchHistory["matches"][$i]["participants"]["0"]["stats"]["neutralminionsKilledTeamJungle"];
$farm4 = $matchHistory["matches"][$i]["participants"]["0"]["stats"]["neutralminionsKilledEnemyJungle"];
$elapsedTime = $matchHistory["matches"][$i]["matchDuration"];
settype($elapsedTime, "integer");
$elapsedTime = floor($elapsedTime / 60);
$k = $matchHistory["matches"][$i]["participants"]["0"]["stats"]["kills"];
$d = $matchHistory["matches"][$i]["participants"]["0"]["stats"]["deaths"];
$a = $matchHistory["matches"][$i]["participants"]["0"]["stats"]["assists"];
$championIdTmp = $matchHistory["matches"][$i]["participants"]["0"]["championId"];
$championName = call_user_func('getChampionName', $championIdTmp); // calls another function to resolve championId into championName
$gameType = preg_replace('/[^A-Za-z0-9\-]/', ' ', $matchHistory["matches"][$i]["queueType"]);
$result = (($matchHistory["matches"][$i]["participants"]["0"]["stats"]["winner"]) == "true") ? "Victory" : "Defeat";
echo "<tr>"."<td>".$gameType."</td>"."<td>".$result."</td>"."<td>".$championName."</td>"."<td>".$k."/".$d."/".$a."</td>"."<td>".($farm1+$farm2+$farm3+$farm4)." in ". $elapsedTime. " minutes". "</td>"."</tr>";
}
}
?>
What I'd like to know is how to make the page output faster as it takes around
10~15 seconds to output the results which makes the browser thinks the website is dead like a 500 Internal error or something like it .
Here is a simple demonstration of how long it can take : Here
As you might have noticed , yes I'm using Riot API which is sending the response as a JSON encoded type.
Here is an example of the response that this function handles : Here
What I thought of was creating a temporarily file called temp.php at the start of the CURL function and saving the whole response there and then reading the variables from there so i can speed up the process and after reading the variables it deletes the temp.php that was created thus freeing up disk space. and increasing the speed.
But I have no idea how to do that in PHP Only.
By the way I'd like to tell you that i just started using PHP today so I'd prefer some explanation with the answers if possible .
Thanks for your precious time.
Try benchmarking like this:
// start the timer
$start_curl = microtime(true);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://".$serverName.".api.pvp.net/api/lol/".$serverName."/v2.2/matchhistory/".$summonerId."?api_key=".$apiKey);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// debugging
curl_setopt($ch, CURLOPT_VERBOSE, true);
// start another timer
$start = microtime(true);
$response = curl_exec($ch);
echo 'curl_exec() in: '.(microtime(true) - $start).' seconds<br><br>';
// start another timer
$start = microtime(true);
curl_close($ch);
echo 'curl_close() in: '.(microtime(true) - $start).' seconds<br><br>';
// how long did the entire CURL take?
echo 'CURLed in: '.(microtime(true) - $start_curl).' seconds<br><br>';

PHP How to hit a url and download its xml

I am trying to send this query:
http://api.geonames.org/search?featureCode=PRK&maxRows=10&username=demo&country=US&style=full&adminCode1=AK
To a web service and pull down and parse a bunch of fields there, namely these:
// 1) totalResultsCount
// 2) name
// 3) lat
// 4) lng
// 5) countryCode
// 6) countryName
// 7) adminName1 - gives full state name
// 8) adminName2 - owner of the park.
I am doing this:
$query_string = "http://api.geonames.org/search?featureCode=PRK&maxRows=10&username=demo&country=US&style=full&adminCode1=AK";
Could someone please provide the right code to loop through the results and get values?
Since the response is XML, you can use SimpleXML:
$url = "http://api.geonames.org/search?featureCode=PRK&maxRows=10&username=demo&country=US&style=full&adminCode1=AK";
$xml = new SimpleXMLElement($url, null, true);
echo "totalResultsCount: " . $xml->totalResultsCount . "<br />";
foreach($xml->geoname as $geoname) {
echo $geoname->toponymName . "<br />";
echo $geoname->lat . "<br />";
echo $geoname->countryCode . "<br />";
echo $geoname->countryName . "<br />";
echo $geoname->adminName1 . "<br />";
echo $geoname->adminName2 . "<br />";
}
Which will displays the results as follows:
totalResultsCount: 225
Glacier Bay National Park and Preserve
58.50056
US
United States
Alaska
US.AK.232
...
Firstly, looks like that web service is returning XML rather than JSON. You can use SimpleXML to parse that out.
Secondly, you may want to check out curl
An Example:
$ch = curl_init("http://api.geonames.org/search?featureCode=PRK&maxRows=10&username=demo&country=US&style=full&adminCode1=AK");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$content = curl_exec($ch);
curl_close($ch);
fopen will give you a resource, no the file. Since you're doing a json decode, you'll want to just the whole thing as a string. Easiest way to do this is file_get_contents.
$query = 'http://api.geonames.org/search?featureCode=PRK&maxRows=10&username=demo&country=US&style=full&adminCode1=AK';
$response = file_get_contents($query);
// You really should do error handling on the response here.
$decoded = json_decode($response, true);
echo '<p>Decoded: '.$decoded['lat'].'</p>';

Problem with CURL fetch function

I've created a php script that will allow the removal of user properties. The script first finds all properties associated with a user and then loops to remove all of them.
When I run this for a certain user, it gets down to the foreach loop and it prints out all the the properties ($name2) but it seems to get stuck on the curl_fetch part. When I then try to pull the properties, they still exist for the user. Any ideas why this is happening? The code is below for you to take a look. Thanks in advance.
<?php
$user=$_GET['userid'];
$user_id=str_replace(array('#', '#'), array('%40', '%23'), $user);
print "User-id: $user";
print "<br /><br />";
$url=("https://admin:password#oursite.com/#api/users/=$user_id/properties");
$xmlString=file_get_contents($url);
$delete = "https://admin:password#oursite.com/#api/users/=$user_id/properties/";
$xml = new SimpleXMLElement($xmlString);
function curl_fetch($url,$username,$password,$method='DELETE')
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch,CURLOPT_USERPWD,"$username:$password");
return curl_exec($ch);
}
print "The following properties have been removed: ";
print "<br />";
if(!count($xml->property)) die('No properties exist for this user');
foreach($xml->property as $property) {
$name = $property['name'];
$name2=str_replace(array('#', '#'), array('%40', '%23'), $name);
print $name2;
print "<br />";
curl_fetch($delete . $name2,'admin','password');
}
?>
You're hitting that URL as a GET query. Are you sure doing a delete-type call wouldn't at least require a POST? Think of the chaos that would ensue if a web spider got a list of urls and innocently nuked your entire site by simply indexing it?
My bad, didn't notice that DELETE was the default method in your curl function.
I'd suggest echoing out the complete URL from within the curl function, and verifying that it is being built properly. I can't see anything else obviously wrong with the code, so I'm guessing the URL's incorrect.

Categories