How to use authorization header PHP - 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

Related

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

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();

Twitter API and OAuth - PHP

I've read through the documentation for using the APIs and I'm not quite sure how to incorporate OAuth into my current API calls. Right now, I just use...
file_put_contents("my_url");
... to get the JSON. Is there a way to add the OAuth credentials to that call or will I have to switch to using curl or some other method?
I would recommend using a library, there are many good ones listed here
Depending on the use, sometimes you don't need to bother with OAuth and official Twitter API so here is another lib you won't find in their list :) https://github.com/fbparis/TweetFuck
The answer to my question was to use stream_context_create as an additional argument to file_get_contents since the OAuth parameters get passed in the request headers.
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n" .
"OAuth-Token: xyz\r\n"
)
);
file_get_content('my url',stream_context_create($opts));
The above is not an exact example as its context dependent. But the stream_context_create() function is how you'd dictate what headers are sent when using file_get_contents().

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

What are ways to send data using PHP?

I need to send HTTP POST data to a webpage. My host is missing some extensions (I'm not sure which ones). I tried cURL and fopen, neither of them work.
What are other ways to send data?
Edit: By the way, I can send $_GET data as well. So as long as I can open a url (eg. file_get_contents), it's works.
Checkout the very powerful PHP stream functions.
However, if the file/stream and cURL functions are disabled - then make them on the frontend using AJAX requests. jQuery is good at this as long as the data isn't sensitive.
I built an entire blog system using just jQuery JSONP requests on the frontend since I wanted to move the load to the user instead of my server.
This may work. The context is not really needed, but allows you to set custom timeout and user-agent.
/* Set up array with options for the context used by file_get_contents(). */
$opts = array(
'http'=>array(
'method' => 'GET',
'timeout' => 4,
'header' => "Accept-language: en\r\n" .
"User-Agent: Some UA\r\n"
)
);
/* Create context. */
$context = stream_context_create($opts);
/* Make the request */
$response = #file_get_contents('http://example.com/?foo=bar', null, $context);
if($response === false) {
/* Could not make request. */
}
You can use http_build_query() to build your query string from an array.

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