This subsection deals with the additional libraries that we include within the Cliqon Framework, that support the transfer of processing from the PHP scripting engine to a different programming paradigm.

Node

We include the Php Node JS Class authored by Dean Gostisa and names "phpnodejs.php". The following information is gleaned from his Github Readme. Clearly, a working copy of Node must be installed and the location of the Node executable must be configured in /config/config.cfg in the "nodepath" variable.


Beyond that it is simply a case of including the Javascript code that you want to run.


global $clq;

$js = $node->run('

       function test(url) {

               jQuery.get(url, function(data) {

                       console.log(data);

               });

               return "";

       }', // ends Javascript

'test', array('http://www.videodeck.net'), true);

echo $js;

Golang

We include the Goridge library. Goridge is high performance PHP-to-Golang codec library which works over native PHP sockets and Golang net/rpc package. The library allows you to call Go service methods from PHP with minimal footprint, structures and []byte support.


$rpc = new RPC(new SocketRelay("127.0.0.1", 6001));

echo $rpc->call("App.Hi", "Antony");

PHP Request library and Curl

Finally we include the Unirest PHP Request library which is effectively a wrapper for CURL.

Creating a Request

So you're probably wondering how using Unirest makes creating requests in PHP easier, let's look at a working example:


$headers = array('Accept' => 'application/json');

$query = array('foo' => 'hello', 'bar' => 'world');

$response = Request::post('http://mockbin.com/request', $headers, $query);

$response->code;        // HTTP Status code

$response->headers;     // Headers

$response->body;        // Parsed body

$response->raw_body;    // Unparsed body

JSON Requests (application/json)

A JSON Request can be constructed using the Request\Body::Json helper:


$headers = array('Accept' => 'application/json');

$data = array('name' => 'ahmad', 'company' => 'mashape');

$body = Request\Body::json($data);

$response = Request::post('http://mockbin.com/request', $headers, $body);


Notes:


   Content-Type headers will be automatically set to application/json

   the data variable will be processed through json_encode with default values for arguments.

   an error will be thrown if the JSON Extension is not available.

Form Requests (application/x-www-form-urlencoded)

A typical Form Request can be constructed using the Request\Body::Form helper:


$headers = array('Accept' => 'application/json');

$data = array('name' => 'ahmad', 'company' => 'mashape');

$body = Request\Body::form($data);

$response = Request::post('http://mockbin.com/request', $headers, $body);


Notes:


   Content-Type headers will be automatically set to application/x-www-form-urlencoded

   the final data array will be processed through http_build_query with default values for arguments.

Multipart Requests (multipart/form-data)

A Multipart Request can be constructed using the Request\Body::Multipart helper:


$headers = array('Accept' => 'application/json');

$data = array('name' => 'ahmad', 'company' => 'mashape');

$body = Request\Body::multipart($data);

$response = Request::post('http://mockbin.com/request', $headers, $body);


Notes:


   Content-Type headers will be automatically set to multipart/form-data.

   an auto-generated --boundary will be set.

Multipart File Upload

simply add an array of files as the second argument to to the Multipart helper:


$headers = array('Accept' => 'application/json');

$data = array('name' => 'ahmad', 'company' => 'mashape');

$files = array('bio' => '/path/to/bio.txt', 'avatar' => '/path/to/avatar.jpg');

$body = Request\Body::multipart($data, $files);

$response = Request::post('http://mockbin.com/request', $headers, $body);


If you wish to further customize the properties of files uploaded you can do so with the Request\Body::File helper:


$headers = array('Accept' => 'application/json');

$body = array(

   'name' => 'ahmad',

   'company' => 'mashape'

   'bio' => Request\Body::file('/path/to/bio.txt', 'text/plain'),

   'avatar' => Request\Body::file('/path/to/my_avatar.jpg', 'text/plain', 'avatar.jpg')

);


$response = Request::post('http://mockbin.com/request', $headers, $body);


Note: we did not use the Request\Body::multipart helper in this example, it is not needed when manually adding files.

Custom Body

Sending a custom body such rather than using the Request\Body helpers is also possible, for example, using a serialize body string with a custom Content-Type:


$headers = array('Accept' => 'application/json', 'Content-Type' => 'application/x-php-serialized');

$body = serialize((array('foo' => 'hello', 'bar' => 'world'));

$response = Request::post('http://mockbin.com/request', $headers, $body);

Authentication

First, if you are using Mashape:


// Mashape auth

Request::setMashapeKey('<mashape_key>');


Otherwise, passing a username, password (optional), defaults to Basic Authentication:


// basic auth

Request::auth('username', 'password');


The third parameter, which is a bitmask, will Unirest which HTTP authentication method(s) you want it to use for your proxy authentication.


If more than one bit is set, Unirest (at PHP's libcurl level) will first query the site to see what authentication methods it supports and then pick the best one you allow it to use. For some methods, this will induce an extra network round-trip.

Supported Methods

Method                        Description

CURLAUTH_BASIC        HTTP Basic authentication. This is the default choice

CURLAUTH_DIGEST        HTTP Digest authentication. as defined in RFC 2617

CURLAUTH_DIGEST_IE        HTTP Digest authentication with an IE flavor. The IE flavor is simply that libcurl will use a special "quirk"                                that IE is known to have used before version 7 and that some servers require the client to use.

CURLAUTH_NEGOTIATE        HTTP Negotiate (SPNEGO) authentication. as defined in RFC 4559

CURLAUTH_NTLM        HTTP NTLM authentication. A proprietary protocol invented and used by Microsoft.

CURLAUTH_NTLM_WB        NTLM delegating to winbind helper. Authentication is performed by a separate binary application. see                                        libcurl docs for more info

CURLAUTH_ANY                This is a convenience macro that sets all bits and thus makes libcurl pick any it finds suitable. libcurl                                        will automatically select the one it finds most secure.

CURLAUTH_ANYSAFE        This is a convenience macro that sets all bits except Basic and thus makes libcurl pick any it finds                                        suitable. libcurl will automatically select the one it finds most secure.

CURLAUTH_ONLY                This is a meta symbol. OR this value together with a single specific auth value to force libcurl to probe                                        for un-restricted auth and if not, only that single auth algorithm is acceptable.


// custom auth method

Request::proxyAuth('username', 'password', CURLAUTH_DIGEST);


Previous versions of Unirest support Basic Authentication by providing the username and password arguments:


$response = Request::get('http://mockbin.com/request', null, null, 'username', 'password');


This has been deprecated, and will be completely removed in v.3.0.0 please use the Request::auth() method instead

Cookies

Set a cookie string to specify the contents of a cookie header. Multiple cookies are separated with a semicolon followed by a space (e.g., "fruit=apple; colour=red")


Request::cookie($cookie)


Set a cookie file path for enabling cookie reading and storing cookies across multiple sequence of requests.


Request::cookieFile($cookieFile)


$cookieFile must be a correct path with write permission.

Request Object


Request::get($url, $headers = array(), $parameters = null)

Request::post($url, $headers = array(), $body = null)

Request::put($url, $headers = array(), $body = null)

Request::patch($url, $headers = array(), $body = null)

Request::delete($url, $headers = array(), $body = null)


   url - Endpoint, address, or uri to be acted upon and requested information from.

   headers - Request Headers as associative array or object

   body - Request Body as associative array or object


You can send a request with any standard or custom HTTP Method:


Request::send(Method::LINK, $url, $headers = array(), $body);

Request::send('CHECKOUT', $url, $headers = array(), $body);

Response Object

Upon recieving a response Unirest returns the result in the form of an Object, this object should always have the same keys for each language regarding to the response details.


   code - HTTP Response Status Code (Example 200)

   headers - HTTP Response Headers

   body - Parsed response body where applicable, for example JSON responses are parsed to Objects / Associative Arrays.

   raw_body - Un-parsed response body

Advanced Configuration

You can set some advanced configuration to tune Unirest-PHP:

Custom JSON Decode Flags

Unirest uses PHP's JSON Extension for automatically decoding JSON responses. sometime you may want to return associative arrays, limit the depth of recursion, or use any of the customization flags. To do so, simply set the desired options using the jsonOpts request method:


Request::jsonOpts(true, 512, JSON_NUMERIC_CHECK & JSON_FORCE_OBJECT & JSON_UNESCAPED_SLASHES);

Timeout

You can set a custom timeout value (in seconds):


Request::timeout(5); // 5s timeout

Proxy

Set the proxy to use for the upcoming request. You can also set the proxy type to be one of CURLPROXY_HTTP, CURLPROXY_HTTP_1_0, CURLPROXY_SOCKS4, CURLPROXY_SOCKS5, CURLPROXY_SOCKS4A, and CURLPROXY_SOCKS5_HOSTNAME - check the cURL docs for more info.


// quick setup with default port: 1080

Request::proxy('10.10.10.1');


// custom port and proxy type

Request::proxy('10.10.10.1', 8080, CURLPROXY_HTTP);


// enable tunneling

Request::proxy('10.10.10.1', 8080, CURLPROXY_HTTP, true);

Proxy Authenticaton

Passing a username, password (optional), defaults to Basic Authentication:


// basic auth

Request::proxyAuth('username', 'password');


The third parameter, which is a bitmask, will Unirest which HTTP authentication method(s) you want it to use for your proxy authentication. If more than one bit is set, Unirest (at PHP's libcurl level) will first query the site to see what authentication methods it supports and then pick the best one you allow it to use. For some methods, this will induce an extra network round-trip. See Authentication for more details on methods supported.


// basic auth

Request::proxyAuth('username', 'password', CURLAUTH_DIGEST);

Default Request Headers

You can set default headers that will be sent on every request:


Request::defaultHeader('Header1', 'Value1');

Request::defaultHeader('Header2', 'Value2');


You can set default headers in bulk by passing an array:


Request::defaultHeaders(array(

   'Header1' => 'Value1',

   'Header2' => 'Value2'

));


You can clear the default headers anytime with:


Request::clearDefaultHeaders();

Default cURL Options

You can set default cURL options that will be sent on every request:


Request::curlOpt(CURLOPT_COOKIE, 'foo=bar');


You can set options bulk by passing an array:


Request::curlOpts(array(

   CURLOPT_COOKIE => 'foo=bar'

));


You can clear the default options anytime with:


Request::clearCurlOpts();

SSL validation

You can explicitly enable or disable SSL certificate validation when consuming an SSL protected endpoint:


Request::verifyPeer(false); // Disables SSL cert validation


By default is true.

Utility Methods


// alias for `curl_getinfo`

Request::getInfo()


// returns internal cURL handle

Request::getCurlHandle()




Created with the Personal Edition of HelpNDoc: Generate EPub eBooks with ease