HOW TO USE API's in PHP LARAVEL [duplicate] - php

I'm planning to use PHP for a simple requirement. I need to download a XML content from a URL, for which I need to send HTTP GET request to that URL.
How do I do it in PHP?

Unless you need more than just the contents of the file, you could use file_get_contents.
$xml = file_get_contents("http://www.example.com/file.xml");
For anything more complex, I'd use cURL.

For more advanced GET/POST requests, you can install the CURL library (http://us3.php.net/curl):
$ch = curl_init("REMOTE XML FILE URL GOES HERE"); // such as http://example.com/example.xml
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);

http_get should do the trick. The advantages of http_get over file_get_contents include the ability to view HTTP headers, access request details, and control the connection timeout.
$response = http_get("http://www.example.com/file.xml");

Remember that if you are using a proxy you need to do a little trick in your php code:
(PROXY WITHOUT AUTENTICATION EXAMPLE)
<?php
$aContext = array(
'http' => array(
'proxy' => 'proxy:8080',
'request_fulluri' => true,
),
);
$cxContext = stream_context_create($aContext);
$sFile = file_get_contents("http://www.google.com", False, $cxContext);
echo $sFile;
?>

Guzzle is a very well known library which makes it extremely easy to do all sorts of HTTP calls. See https://github.com/guzzle/guzzle. Install with composer require guzzlehttp/guzzle and run composer install. Now code below is enough for a http get call.
$client = new \GuzzleHttp\Client();
$response = $client->get('https://example.com/path/to/resource');
echo $response->getStatusCode();
echo $response->getBody();

Depending on whether your php setup allows fopen on URLs, you could also simply fopen the url with the get arguments in the string (such as http://example.com?variable=value )
Edit: Re-reading the question I'm not certain whether you're looking to pass variables or not - if you're not you can simply send the fopen request containg http://example.com/filename.xml - feel free to ignore the variable=value part

I like using fsockopen open for this.

On the other hand, using the REST API of servers is very popular in PHP. You can suppose all URLs are parts of a REST API and use many well-designed PHP packages.
Actually, REST API is a way to use services from a site.
So, there are many PHP packages developed to simplify REST API call. For example here is a very nice one:
https://github.com/romanpitak/PHP-REST-Client
Using such packages helps you to fetch resources easily.
So, getting the xml file (that you mentioned about) is as easy as:
$client = new Client('http://example.com');
$request = $client->newRequest('/filename.xml');
$response = $request->getResponse();
echo $response->getParsedResponse();

Related

How to use authorization header PHP

I am trying to use an authorization header in order to use the vimeo API.
It tells me to do this 'Authorization: basic ' + base64(client_id + ':' + client_secret) , which is something I can do.
But nowhere on the internet does it tell me what I actually do with this code? It is not PHP, but does it go in a PHP file? If so then what function do I use on it after storing it? Does it go in an htaccess file?
It is really sad how terrible any and all online documentation is on this.
To summarize, basically what I'm saying is SHOW ME THE CODE
$api_url = 'http://myapiurl';
$client_id = 'myclientid';
$client_secret = 'myclientsecret';
$context = stream_context_create(array(
'http' => array(
'header' => "Authorization: Basic " . base64_encode("$client_id:$client_secret"),
),
));
$result = file_get_contents($api_url, false, $context);
Documentation links:
file_get_contents
stream_context_create
HTTP context options
For more complex requests, you can use cURL, but the library's PHP implementation is a mess and I prefer to avoid it when I can. Guzzle is a library that abstracts a lot of the complexities here.
Vimeo highly recommends you do not write these authentication systems yourself, but use the official libraries: https://github.com/vimeo/vimeo.php.
If you are looking for a custom PHP integration, it varies based on the way you make HTTP requests. guzzle and curl are both http request libraries, with their own ways of setting headers (http://guzzle.readthedocs.org/en/latest/request-options.html#headers and PHP cURL custom headers)
As for base64 encoding your tokens, use the method base64_encode (http://php.net/manual/en/function.base64-encode.php)
$curl = base64_encode("1100032342:F!rSTU99HD");
echo $curl;
RESULT:
MTEwMDAzMjM0MjpGIXJTVFU5OUhE

PHP REST client API call

I'm wondering, is there an easy way to perform a REST API GET call? I've been reading about cURL, but is that a good way to do it?
I also came across php://input but I have no idea how to use it. Does anyone have an example for me?
I don't need advanced API client stuff, I just need to perform a GET call to a certain URL to get some JSON data that will be parsed by the client.
Thanks!
There are multiple ways to make REST client API call:
Use CURL
CURL is the simplest and good way to go. Here is a simple call
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, POST DATA);
$result = curl_exec($ch);
print_r($result);
curl_close($ch);
Use Guzzle
It's a "PHP HTTP client that makes it easy to work with HTTP/1.1 and takes the pain out of consuming web services". Working with Guzzle is much easier than working with cURL.
Here's an example from the Web site:
$client = new GuzzleHttp\Client();
$res = $client->get('https://api.github.com/user', [
'auth' => ['user', 'pass']
]);
echo $res->getStatusCode(); // 200
echo $res->getHeader('content-type'); // 'application/json; charset=utf8'
echo $res->getBody(); // {"type":"User"...'
var_export($res->json()); // Outputs the JSON decoded data
Use file_get_contents
If you have a url and your php supports it, you could just call file_get_contents:
$response = file_get_contents('http://example.com/path/to/api/call?param1=5');
if $response is JSON, use json_decode to turn it into php array:
$response = json_decode($response);
Use Symfony's RestClient
If you are using Symfony there's a great rest client bundle that even includes all of the ~100 exceptions and throws them instead of returning some meaningless error code + message.
try {
$restClient = new RestClient();
$response = $restClient->get('http://www.someUrl.com');
$statusCode = $response->getStatusCode();
$content = $response->getContent();
} catch(OperationTimedOutException $e) {
// do something
}
Use HTTPFUL
Httpful is a simple, chainable, readable PHP library intended to make speaking HTTP sane. It lets the developer focus on interacting with APIs instead of sifting through curl set_opt pages and is an ideal PHP REST client.
Httpful includes...
Readable HTTP Method Support (GET, PUT, POST, DELETE, HEAD, and OPTIONS)
Custom Headers
Automatic "Smart" Parsing
Automatic Payload Serialization
Basic Auth
Client Side Certificate Auth
Request "Templates"
Ex.
Send off a GET request. Get automatically parsed JSON response.
The library notices the JSON Content-Type in the response and automatically parses the response into a native PHP object.
$uri = "https://www.googleapis.com/freebase/v1/mqlread?query=%7B%22type%22:%22/music/artist%22%2C%22name%22:%22The%20Dead%20Weather%22%2C%22album%22:%5B%5D%7D";
$response = \Httpful\Request::get($uri)->send();
echo 'The Dead Weather has ' . count($response->body->result->album) . " albums.\n";
You can use file_get_contents if the fopen wrappers are enabled. See: http://php.net/manual/en/function.file-get-contents.php
If they are not, and you cannot fix that because your host doesn't allow it, cURL is a good method to use.
You can use:
$result = file_get_contents( $url );
http://php.net/manual/en/function.file-get-contents.php

How to add a parameter to the request header sent by a PHP script?

I'm trying to use a web service REST API for which I need to add a parameter for authorization (with the appropriate key, of course) to get a XML result. I'm developing in PHP. How can I add a parameter to the request header in such a situation?
Edit: The way I'm doing the request right now is $xml = simplexml_load_file($query_string);
Are you using curl? (recommended)
I assume that you are using curl to do these requests towards the REST API, if you aren't; use it.
When using curl you can add a custom header by calling curl_setopt with the appropriate parameters, such as in below.
curl_setopt (
$curl_handle, CURLOPT_HTTPHEADER,
array ('Authentication-Key: foobar')
); // make curl send a HTTP header named 'Authentication-key'
// with the value 'foobar'
Documentation:
PHP: cURL - Manual
PHP: curl_setopt - Manual
Are you using file_get_contents or similar?
This method is not recommended, though it is functional.
Note: allow_url_fopen needs to be enabled for file_get_contents to be able to access resources over HTTP.
If you'd like to add a custom header to such request you'll need to create yourself a valid stream context, as in the below snippet:
$context_options = array(
'http' =>array (
'method' => 'GET',
'header' => 'Authentication-Key'
)
);
$context = stream_context_create ($context_options);
$response = file_get_contents (
'http://www.stackoverflow.com', false, $context_options
);
Documentation:
PHP: file_get_contents - Manual
PHP: stream_context_create - Manual
PHP: Runtime Configuration, allow_url_fopen
I'm using neither of the above solutions, what should I do?
[Post OP EDIT]
My recommendation is to fetch the data using curl and then pass it off to the parser in question when all the data is received. Separate data fetching from the processing of the returned data.
[/Post OP EDIT]
When you use $xml = simplexml_load_file($query_string);, the PHP interpreter invokes it's wrapper over fopen to open the contents of a file located at $query_string. If $query_string is a remote file, the PHP interpreter opens a stream to that remote URL and retrieves the contents of the file there (if the HTTP response code 200 OK). It uses the default stream context to do that.
There is a way to alter the headers sent by altering that stream context, however, in most cases, this is a bad idea. You're relying on PHP to always open all files, local or remote, using a function that was meant to take a local file name only. Not only is it a security problem but it also could be the source of a bug that is very hard to track down.
Instead, consider splitting the loading of the remote content using cURL (checking the returned HTTP status code and other sanity checks) and then parsing that content into a SimpleXMLElement object to use. When you use cURL, you can set any headers you want to send with the request by invoking something similar to curl_setopt($ch, CURLOPT_HTTPHEADER, array('HeaderName' => 'value');
Hope this helps.

Reading REST API Response in PHP

I am trying to read Raven SEO Tools API. It is a REST API and currently it is serving the data backup as an XML (or JSON if I choose) when I just request the URL through a web browser. What is the best method to get the response from their server into my own PHP script for me to then play around with.
Any help much appreciated
Cheers
If you only needs to retrieve a URL and parse its info. The easiest way is curl/JSON combination. Note that parsing JSON is faster than parsing XML.
http://www.php.net/manual/en/function.curl-exec.php
http://www.php.net/manual/en/function.json-decode.php
Something simple as:
$url = "http://api.raventools.com/api?key=B1DFC59CA6EC76FF&method=domains&format=json";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT, 4);
$json = curl_exec($ch);
if(!$json) {
echo curl_error($ch);
}
curl_close($ch);
print_r(json_decode($json));
But if you need to call other methods from this API such as DELETE/PUT, etc. Then to have a REST client in PHP is more elegant solution. A comparison on those clients can be found in PHP REST Clients
I founded this code specifically for Raven API https://github.com/stephenyeargin/raventools-api-php
Sample code:
require 'path/to/raventools-api-php/raventools-api-php.class.php';
$Raven = new RavenTools( 'B1DFC59CA6EC76FF' );
$method = 'domains';
$options = array('format'=> 'json');
$responseString = $Raven->getJSON($method, $options);
print_r(json_decode($responseString));
cUrl
cUrl is a command line tool for getting or sending files using URL syntax.
curl -o example.html www.example.com
file_get_contents
<?php
$homepage = file_get_contents('http://www.example.com/api/parameters');
echo $homepage;
?>
Pecl's HTTPRequest class is a very nice client, I've been using it for a couple of Projects. http://pecl.php.net/package/pecl_http
Another pretty cool client is the Buzz client https://github.com/kriswallsmith/Buzz
It also plays nice with Symfony2 if that's of interest to you :)
You can use either one of them, but I think JSON is the easiest and more hassle-free, unless you use SimpleXML. The decision depends on the complexity of your data.
Given that the JSON returned by the API is valid you can convert it to an array or object by using PHP's json_decode() function.
<?php
# retrieve JSON from API here...
# i.e. it is stored in $data as a string
$object = json_decode($data);
$array = json_decode($data, true);
?>
In SimpleXML, it would be as follows:
<?php
$object = simplexml_load_string($data);
?>

How to send a GET request from PHP?

I'm planning to use PHP for a simple requirement. I need to download a XML content from a URL, for which I need to send HTTP GET request to that URL.
How do I do it in PHP?
Unless you need more than just the contents of the file, you could use file_get_contents.
$xml = file_get_contents("http://www.example.com/file.xml");
For anything more complex, I'd use cURL.
For more advanced GET/POST requests, you can install the CURL library (http://us3.php.net/curl):
$ch = curl_init("REMOTE XML FILE URL GOES HERE"); // such as http://example.com/example.xml
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
http_get should do the trick. The advantages of http_get over file_get_contents include the ability to view HTTP headers, access request details, and control the connection timeout.
$response = http_get("http://www.example.com/file.xml");
Remember that if you are using a proxy you need to do a little trick in your php code:
(PROXY WITHOUT AUTENTICATION EXAMPLE)
<?php
$aContext = array(
'http' => array(
'proxy' => 'proxy:8080',
'request_fulluri' => true,
),
);
$cxContext = stream_context_create($aContext);
$sFile = file_get_contents("http://www.google.com", False, $cxContext);
echo $sFile;
?>
Guzzle is a very well known library which makes it extremely easy to do all sorts of HTTP calls. See https://github.com/guzzle/guzzle. Install with composer require guzzlehttp/guzzle and run composer install. Now code below is enough for a http get call.
$client = new \GuzzleHttp\Client();
$response = $client->get('https://example.com/path/to/resource');
echo $response->getStatusCode();
echo $response->getBody();
Depending on whether your php setup allows fopen on URLs, you could also simply fopen the url with the get arguments in the string (such as http://example.com?variable=value )
Edit: Re-reading the question I'm not certain whether you're looking to pass variables or not - if you're not you can simply send the fopen request containg http://example.com/filename.xml - feel free to ignore the variable=value part
I like using fsockopen open for this.
On the other hand, using the REST API of servers is very popular in PHP. You can suppose all URLs are parts of a REST API and use many well-designed PHP packages.
Actually, REST API is a way to use services from a site.
So, there are many PHP packages developed to simplify REST API call. For example here is a very nice one:
https://github.com/romanpitak/PHP-REST-Client
Using such packages helps you to fetch resources easily.
So, getting the xml file (that you mentioned about) is as easy as:
$client = new Client('http://example.com');
$request = $client->newRequest('/filename.xml');
$response = $request->getResponse();
echo $response->getParsedResponse();

Categories