How do I Parse the response I get back from CURL? - php

I'm sending some data to an external URL using Curl. The server sends me back a response in a string like this:
trnApproved=0&trnId=10000002&messageId=7&messageText=DECLINE
I can assign this string to a variable like this:
$txResult = curl_exec( $ch );
echo "Result:<BR>"; echo $txResult;
But how do I use the data that is sent back? I need a way to get the value of each variable sent back so that I can use it in my PHP script.
Any help would be much appreciated.
Thanks.

The default behavior of Curl is to just dump the data you get back out to the browser. In order to instead capture it to a variable, you need:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$txResult = curl_exec($ch);
That default behavior has always annoyed me. Returning the data from the curl_exec() call seems by far the more correct choice to me.

Use parse_str():
parse_str($txResult, $txArr);
var_dump($txArr);

Related

Making a GET request to another PHP file in PHP

I have created a php file called "brain.php" that takes a get parameter of "message" - so for example "brain.php?msg=hello". It will respond with a JSON array that can be handled by the application.
I have built a JQuery app that can make these requests, and now I'm attempting to do it in PHP but I'm not sure how.
The following code does not work as it thinks the parameter is part of the filename
$response = file_get_contents("../brain.php?msg=hello");
echo $response;
The following code kind of works but simply responds with the entirety of the code instead of the response
$response = file_get_contents("../brain.php");
echo $response;
What is the best way to make the request with the ?msg variable and store the JSON response in a variable for handling?
Thank you!
You can get content from URL using file_get_contents:
$response = file_get_contents('https://httpbin.org/ip?test=test');
$jsonData = json_decode($response, true));
However you need to check if allow_url_fopen is enabled in your php.ini. Alternatively you can do the same with curl:
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://httpbin.org/ip?test=test');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$jsonData = json_decode(curl_exec($curl), true);
curl_close($curl);
First of all, I have to say: you're probably doing this wrong.
This should work better:
In your file, set the variable msg (e.g: $msg = "Hello")
Import the file using include_once('../brain.php')
In brain.php, set the JSON response (or another type) in a variable (e.g: $foo = json_encode(...)) and make necessary adjustments to read $msg variable (e.g.: $_GET['msg'] to $msg)
After including brain.php, use your "new" variable as you wish.

PHP get results from URL

stupid question I think.
I have an API that i want to access. if I simply put the url in my browser it returns all the results correctly.
https://api.mydomain.com/v1/name?user=user1&pass=1234
in my browser this returns array information:
{"firstname":"John","Surname":"Smith"}
I want to be able to use PHP to simply assign the results of the URL page to a variable:
$url="https://api.mydomain.com/v1/name?user=user1&pass=1234";
$result=parse($url);
print_r($result);
This obviously doesnt work but just looking for the correct syntax. done some research but not getting any luck. should be so simple but is not.
advice appreciated as always.
Thanks
Just make a request to your API service:
$url="https://api.mydomain.com/v1/name?user=user1&pass=1234";
$result = file_get_contents($url);
Then, if I understand correctly, your API returns JSON response, so you have to decode it:
$vars = json_decode($result, true);
Which will return an array with all the variables:
echo $vars['firstname']; //"John";
echo $vars['Surname']; //"Smith";
solution: file_get_contents (or maybe you'll need curl if ini_get("allow_url_fopen") !=1 ....)
$url="https://api.mydomain.com/v1/name?user=user1&pass=1234";
$result=parse(file_get_contents($url));
print_r($result);
hope your "parse()" function knows how to parse the result from your api call. i guess you don't know what you're doing, and next you'll be asking why the parse function is not defined :p (it looks like you're looking for json_decode , just a guess.)
i think your parse function would look like:
function parse($apiresponse){return json_decode($apiresponse,true);}
If you have the CURL library installed, you could do this:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.mydomain.com/v1/name?user=user1&pass=1234');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
$vars = json_decode($result, true);
//do something useful with the $vars variable
Cannot you do some search?
Take a look at Google with keywords "PHP get results from URL"

How can I make a request with both GET and POST parameters in PHP with cURL?

Other people have already asked how to do this from perl, java, bash, etc. but I need to do it in PHP, and I don't see any question already asked relating specifically to (or with answers for) PHP.
My code:
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
This doesn't work. The destination site has print_r($_GET); print_r($_POST);, so when I examine the $result I should be able to see the fields that are being sent. However, the $_POST array is empty - I only see the get variables. If I remove the ?... query string from the $url, then the POST array is populated correctly. But now I don't have the GET params. How do I do this?
My specific case is, I need to send too much data to fit it in the query string, but I can't send it all as POST because the site I want to submit to is selecting a handler for the posted data based on a variable in the GET string. I can try and have that changed, but ideally I would like to be able to send both get and post data in the same query.
# GET query goes in the URL you're hitting
$ch = curl_init('http://example.com/script.php?query=parameter');
# POST fields go here.
curl_setopt($ch, CURLOPT_POSTFIELDS, array('post' => 'parameter', 'values' => 'go here'));
PHP itself wouldn't decide to ignore the GET parameters if a POST is performed. It'll populate $_GET regardless of what kind of http verb was used to load the page - if there's query parameters in the URL, they'll go into $_GET.
If you're not getting $_POST and $_GET with this, then something is causing a redirect or otherwise killing something. e.g. have you check $_SERVER['REQUEST_METHOD'] to see if your code is actually running as a POST? PHP won't populate $_POST if a post wasn't actually performed. You may have sent a post to the server, but that doesn't mean your code will actually be executed under a POST regime - e.g. a mod_rewrite redirect.
Since you have FOLLOW_REDIRECT turned on, you're simply ASSUMING you're actually getting a post when your code executes.
i don't know maybe you already have but is your $url has the desired get parameters? Like:
$url = "http://example.com/index.php?param1=value1&param2=value2";

How can I send and receive data from an external webpage?

I am building a PHP script that needs to use content loaded from an external webpage, but I don't know how to send/receive data.
The external webpage is http://packer.50x.eu/ .
Basically, I want to send a script (which is manually done in the first form) and receive the output (from the second form).
I want to learn how to do it because it can surely be an useful thing in the future, but I have no clue where to start.
Can anyone help me? Thanks.
You can use curl to receive data from external page. Look this example:
$url = "http://packer.50x.eu/";
$ch = curl_init($url);
// curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // you can use some options for this request
// curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); // or not to use them
// you can set many others options. read about them in manual
$data = curl_exec($ch);
curl_close($ch);
var_dump($data); // < -- here is received page data
curl_setopt manual
Hope, this will help you.
You may want to look at file_get_contents($url) as it is very simple to use, simpler than CURL (more limited though), so your code could look like:
$url = "http://packer.50x.eu/";
$url_content=file_get_contents($url);
echo $url_content;
Look at the documentation as you could use offset and other tricks.

Got url to fetch json data with username and password, how to secure it as javascript source shows username and password

(I am using json with PHP)
Hi i have got a url, from some web service saying:
http://www.example.com?username=$username&password=$password&fname=firstname
Now they said they i can get data with xml or json to retrieve data along with passing my username and password. And when i googled found json is better option. Now i hv done doing json and received the required data successfully.
But i can see all the javascript i hav used to fetch in view-source of page. And so is the username with password.
I am a new programmer when it comes to use json or say fetching data with REST.
Can anyone just let me know the basic idea, that will be enough for me.
What you need to do then is get that URL with PHP. To do this, cURL is most commonly used:
$parameters = array(
'username'=>$username,
'password'=>$password,
'fname'=>$fname
);
$ch = curl_init('http://www.example.com?' . http_build_query($parameters);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
echo $output;
You should see the data from that URL with your code. Now, since it is JSON, we need to decode that:
print_r(json_decode($output));
You should see a PHP object, where you can access its properties as needed.

Categories