PHP: String not appending - php

I'm building up a url to execute with curl. the url will call an api for the LMS that I'm using. Before being able to call anything else, you need to receive a token from the LMS to put in the url. I have gotten the token from the api, and I can echo it and it shows up just fine, when I echo the url after appending the token to it, it doesn't show up.
curl_setopt($c, 'CURLOPT_RETURNTRANSFER', true);
$res = curl_exec($c);
curl_close($c);
$start = strpos($res,"<token>");
$end = $start+37;
$token = substr($res,$start+7,$end-$start);
echo "{$token}<br />";
$url = "/www/api2.php?action=create_user";
$url .= "&login=" . urlencode($username);
$url .= "&password=" . urlencode($password);
$url .= "&name=" . urlencode($data['first_name']);
$url .= "&surname=" . urlencode($data['last_name']);
$url .= "&email=" . urlencode($email);
$url .= "&languages=english";
$url .= "&token=" . $token;
echo "{$url}<br />";
Output of the echo "{$url}<br />";
/www/api2.php?action=create_user&login=foobar3130&password=6116b3f29c&name=Foo&surname=Bar&email=foobar%40gmail.com&languages=english&token=
Output of echo "{$token}<br />";
pUCu2BUAE1heAyQ93fApfhvDE1bjKd
Edit
I added a check to see if $start was false, and it is false. I guess its not actually the token that gets echo'd because if I comment that line out, the string that I have for the token output still gets printed. I'm not sure what it would even be from.
Edit 2
I now have it returning xml but I am not sure how to parse it to get the token. It returns:
<xml><token>Fp1rYkds4fSuTAQxTvLvSiW5NE2FJz</token></xml>

Your edit seems to confirm that curl_exec() isn't returning the data to you - it is sending it directly to the browser. Use the option CURLOPT_RETURNTRANSFER to have it return the value to your variable.

try:
ob_start();
echo "/www/api2.php?action=create_user";
echo "&login=" . urlencode($username);
echo "&password=" . urlencode($password);
echo "&name=" . urlencode($data['first_name']);
echo "&surname=" . urlencode($data['last_name']);
echo "&email=" . urlencode($email);
echo "&languages=english";
echo "&token=" . $token;
$url=ob_get_contents();
ob_end_clean();
echo $url;

From what your script shows, you are trying to parse the Token out of an XML result, with a fixed width of 37 characters.
Judging from your latest comment, that's where the problem lies.
A much better approach would be to use actual XML DOM parsing to get the token from the file.

Related

Discord oAuth2 API ratelimit triggered without any (known) cause

First question! Woho!
I'm currently coding a Dashboard for a Discord bot in PHP.
Recently, when trying to select a server, it would only display 3 malfunctioning items. So I checked the complete array using print_r() and it turned out it rate-limited me.
Now, I got no idea why that happened, as I'm the only person on the server. So what am I doing wrong? Here is the code for listing the selection page:
$all = DiscordAPI("/users/#me/guilds");
foreach ($all as $guild) {
echo "<a href='/?server=" . $guild['id'] . "'><p>";
if ($guild['icon']) {
if (substr($guild['icon'], 0, 2) == "a_") {
echo "<img class='server-icon' src='https://cdn.discordapp.com/icons/" . $guild['id'] . "/" . $guild['icon'] . ".gif?size=64'>";
} else {
echo "<img class='server-icon' src='https://cdn.discordapp.com/icons/" . $guild['id'] . "/" . $guild['icon'] . ".webp?size=64'>";
}
} else {
$words = explode(" ", $guild['name']);
$acronym = "";
foreach ($words as $w) {
$acronym .= $w[0];
}
echo "<img class='server-icon' src='https://cdn.statically.io/avatar/s=64/" . $acronym . "'>";
}
echo $guild['name'];
echo "</p></a>";
}
And here is the code for the DiscordAPI() function:
function DiscordAPI($endpoint)
{
if (!$_SESSION['token']) {
die("No token provided");
}
$ch = curl_init("https://discord.com/api" . $endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Authorization: Bearer " . $_SESSION['token']
));
$data = curl_exec($ch);
curl_close($ch);
return json_decode($data, true);
}
There are 2 API calls before this code to verify that there is a valid token.
Quick sidenote: I got Autism, so I might understand stuff a bit differently. Don't be scared to ask if I worded something hard to understand. Thank you for trying to understand me.

telegram api send message return nothing

I want to send message via telegram api but it's not working, and not send any message. this is what i tried so far:
function sendTelegram($chatID, $msg) {
echo "sending message to " . $chatID . "\n";
$token = "botxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$getUpdate = "http://api.telegram.org/" . $token . "/getUpdates";
$url = "https://api.telegram.org/" . $token . "/sendMessage?chat_id=" . $chatID;
$url = $url . "&text=" . urlencode($msg);
$ch = curl_init();
$optArray = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true
);
curl_setopt_array($ch, $optArray);
$result = curl_exec($ch);
curl_close($ch);
}
$msg = "Hi";
$chatID = "88132232";
sendTelegram($chatID, $msg);
My progress:
I made a new bot via #botfather and got a token.
Then sent a message to this bot with my telegram.
I got chat id in getUpdates.
https://api.telegram.org/botxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/getUpdates
and also send message via:
https://api.telegram.org/botxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/sendMessage?chat_id=88132232&text=hi
It works find when i go to this url but when i want to do this dynamically it give me nothing just echo sending message to 88132232 with no error. I searched and read many topics but no success, any idea what i missed? Before using curl i used get_file_contents but it also not worked.
You set CURLOPT_RETURNTRANSFER
CURLOPT_RETURNTRANSFER: TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
Please return $result in sendTelegram() function, and echo it.
function sendTelegram($chatID, $msg) {
// ...
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$result = sendTelegram($chatID, $msg);
echo $result; // JSON String
Probably you have error but in curl you should get curl error like this:
if(curl_error($ch)){
echo 'error:' . curl_error($ch);
}
And most problem is SSL. get your error and back. but i tested your code, as #Sean said, your code working fine, try it on php fiddle website. if you get SSL error, read this.

Etsy API Pagination with PHP

So, I'm fairly new to working with APIs, and am just trying to play around with using the Etsy API to display a certain set of listings.
By default, the API returns a set of 25 results, and can do a max of 100 at a time. I'd like to show more than that, so I'm trying to add pagination to my call. Here's what I've got so far:
<?php
//setting API key
define("API_KEY", XXX);
//setting request url
$url = "https://openapi.etsy.com/v2/listings/active?keywords=unicorn,unicorns&includes=Images:1:0&api_key=" . API_KEY;
while (isset($url) && $url != '') {
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$response_body=curl_exec($curl);
curl_close($curl);
$response = json_decode($response_body);
foreach ($response->results as $listing) {
echo "<li>" . $listing->title . " ~*~ " . $listing->price . " " . $listing->currency_code . " ~*~ " . 'View on Etsy!' . "</li>" . "<br>";
}
$url = $response->pagination->next_page;
}
?>
I thought this would loop through and return the next set of 25 results, but it didn't. Anyone have experience working with this? Is there somewhere I'm getting tripped up?
Thanks!
In your while block, you are assigning the value of the next_page property to $url.
But the actual value is an int, 2, not an url.
Instead append the next_page to the initial url, as a query string variable.
$url .= "&page=" . $response->pagination->next_page;
See below an example on how you can isolate each process to a function.
We move the curl operation into its own function where it returns an object from json_decode.
We move the whole processing of the listings into a separate function, where for now, it just prints out the listings.
This second function is recursive, meaning, that if the next page exists it will call the first function, get the response, then process it.
<?php
//setting API key
define("API_KEY", 'br4j52uzdtlcpp6qxb6we3ge');
function get_listings($page=1){
$url = "https://openapi.etsy.com/v2/listings/active?keywords=unicorn,unicorns&includes=Images:1:0&api_key=" . API_KEY;
$url .= "&page=$page";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$response_body=curl_exec($curl);
curl_close($curl);
$responseObject = json_decode($response_body);
return $responseObject;
}
function process_listings($responseObject){
foreach ($responseObject->results as $listing) {
echo "Title: " . $listing->title . PHP_EOL .
"Price " . $listing->price . PHP_EOL .
"Currency code " . $listing->currency_code . PHP_EOL .
'URL ' . $listing->url . PHP_EOL;
}
print PHP_EOL . "Pagination " . $responseObject->pagination->next_page . PHP_EOL;
$next_page = $responseObject->pagination->next_page;
if ($next_page) {
$nextPageResponse = get_listings($next_page);
process_listings($nextPageResponse);
}
}
$firstPage = get_listings(); // page 1 is default
process_listings($firstPage);

Parse XML File that is Dyanamically Generated

I am integrating the API from our monitoring software (PRTG) into our website and attempting to use a function that generates a list of data in XML format. As it is generated as needed, the URL doesn't point to an existing file.
I tried using "simplexml_load_file" and "simplexml_load_string" and passing the URL with no luck. I've also tried use "file_put_contents" to first save the file, but it also fails since the URL doesn't actually point to a file.
How can this be made to work?
<?php
$prtg_url = "http://prtg.domain.net:8080/";
$prtg_user = "username";
$prtg_hash = "passwordhash";
function getSensorData($deviceid)
{
$sensor_xml_file = $GLOBALS['prtg_url'] . "api/table.xml?content=sensors&output=xml&columns=objid,type,device,sensor,status&id=" . $deviceid . "&username=" . $GLOBALS['prtg_user'] . "&passhash=" . $GLOBALS['prtg_hash'];
file_put_contents("sensor.xml", fopen($sensor_xml_file, 'r'));
$sensors = simplexml_load_file("sensor.xml");
foreach ($sensors->item as $sensor)
{
$sensor_ping = $sensor->ping;
$sensor_id = $sensor->objid;
$sensor_type = $sensor->type;
$sensor_typeraw = $sensor->type_raw;
echo $sensor_ping . "</br>";
echo $sensor_id . "</br>";
echo $sensor_type . "</br>";
echo $sensor_typeraw . "</br>";
}
}
getSensorData("3401");
?>
It may be something to do with the file handler. You could try using simplexml_load_file() with your URL. For example:
$url = $GLOBALS['prtg_url']
. "api/table.xml?content=sensors&output=xml&columns=objid,type,device,sensor,status&id="
. $deviceid . "&username=" . $GLOBALS['prtg_user']
. "&passhash=" . $GLOBALS['prtg_hash']);
$xml = simplexml_load_file($url);
try this:
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_URL, $sensor_xml_file);
$xmlString = curl_exec($c);
curl_close($c);
$sensors = simplexml_load_string($xmlString);
$opts = array('http' =>
array(
'method' => 'GET',
'header' => "Content-Type: text/xml\r\n",
'timeout' => 60
)
);
$context = stream_context_create($opts);
$url = $GLOBALS['prtg_url']
. "api/table.xml?content=sensors&output=xml&columns=objid,type,device,sensor,status&id="
. $deviceid . "&username=" . $GLOBALS['prtg_user']
. "&passhash=" . $GLOBALS['prtg_hash']);
$result = file_get_contents($url, false, $context);
echo $results;
This forces a 60 second timeout on the operation, that way you can see if it actually fetches any results. If it does return incomplete results, switch to using XMLReader for your parser.

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>';

Categories