NetUtils

The following functions are not required by API. These functions are used by examples, and in case you need it you can copy and use. 

Sample Code: 

<?php
namespace rhz\cg\server\util;

use rhz\cg\server\rest\RestUtils;
use stdClass;

/**
 * Created by IntelliJ IDEA.
 * User: user
 * Date: 5/21/13
 * Time: 11:26 AM
 *
 * Utility functions for network operations
 */
class NetUtils {

    /**
     * Perform POST post
     * @param $url
     * @param $data
     * @return array
     */
    public static function httpPost($url, $data) {
        $data_url = http_build_query($data);
        $data_len = strlen($data_url);

        $opts = array(
            'http' => array(
                'method' => "POST",
                'header' => "Connection: close\r\nContent-Length: $data_len\r\nContent-type: application/x-www-form-urlencoded\r\n",
                'content' => $data_url
            )
        );
        $context = stream_context_create($opts);
        $content = file_get_contents($url, false, $context);
        return array(
            'content' => $content,
            'headers' => $http_response_header
        );
    }

    /**
     * Get the request protocol
     * @return string
     */
    public static function getProtocol() {
        $isSecure = false;
        if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
            $isSecure = true;
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') {
            $isSecure = true;
        }
        return $isSecure ? 'https' : 'http';
    }


    public static function isHttpsRequest() {
        return self::getProtocol() == "https";
    }


    /**
     * Perform GET using curl API.
     * @param string $url base url
     * @param array $data params
     * @param string $errorBuf
     * @param $cookieSession
     * @param array $headers
     * @return bool|mixed mixed true on success or false on failure
     */
    public static function curlGET($url, $data, &$errorBuf = null, $cookieSession = null, $headers = null) {
        if ($data == null) {
            $data = array();
        }
        $url = $url . "?" . http_build_query($data);

        $curl = curl_init();
        $options = array(
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_URL => $url,
            CURLOPT_CONNECTTIMEOUT => 5,
            CURLOPT_TIMEOUT => 30
        );
        if ($cookieSession != null) {
            $options[CURLOPT_COOKIE] = $cookieSession;
        }
        if ($headers != null) {
            $options[CURLOPT_HTTPHEADER] = $headers;
        }
        curl_setopt_array($curl, $options);
        $response = curl_exec($curl);
        $response = self::processCurlResponse($response, curl_getinfo($curl), $curl, $errorBuf);

        curl_close($curl);
        return $response;
    }

    /**
     * Perform GET using curl API.
     * @param string $url base url
     * @param array $data params
     * @param string $user user name or key
     * @param string $password password
     * @param int $authType type of authentication. One of the following:
     * CURLAUTH_BASIC, CURLAUTH_DIGEST, CURLAUTH_GSSNEGOTIATE, CURLAUTH_NTLM, CURLAUTH_ANY, CURLAUTH_ANYSAFE
     * @param string $errorBuf
     * @param string $cookieSession can be used to pass cookie for session Id for example: session_name=session_id
     * @param array $headers
     * @return bool|mixed
     */
    public static function curlGETWithAuth($url, $data, $user, $password, $authType, &$errorBuf = null, $cookieSession = null, $headers = null) {
        if ($data == null) {
            $data = array();
        }
        $url = $url . "?" . http_build_query($data);

        $curl = curl_init();
        $options = array(
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_URL => $url,
            CURLOPT_HTTPAUTH => $authType,
            CURLOPT_USERPWD => $user . ":" . $password,
            CURLOPT_CONNECTTIMEOUT => 5,
            CURLOPT_TIMEOUT => 30
        );
        if ($cookieSession != null) {
            $options[CURLOPT_COOKIE] = $cookieSession;
        }
        if ($headers != null) {
            $options[CURLOPT_HTTPHEADER] = $headers;
        }
        curl_setopt_array($curl, $options);
        $response = curl_exec($curl);
        $response = self::processCurlResponse($response, curl_getinfo($curl), $curl, $errorBuf);

        curl_close($curl);
        return $response;
    }


    /**
     * Perform POST using curl API.
     * @param $url
     * @param $data
     * @param string $errorBuf
     * @param $cookieSession
     * @param $headers
     * @return bool|mixed
     */
    public static function curlPOST($url, $data, &$errorBuf = null, $cookieSession = null, $headers = null) {
        if ($data == null) {
            $data = array();
        }
        $curl = curl_init();
        $options = array(
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_URL => $url,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => http_build_query($data),
            CURLOPT_CONNECTTIMEOUT => 5,
            CURLOPT_TIMEOUT => 30
        );
        if ($cookieSession != null) {
            $options[CURLOPT_COOKIE] = $cookieSession;
        }
        if ($headers != null) {
            $options[CURLOPT_HTTPHEADER] = $headers;
        }
        curl_setopt_array($curl, $options);
        $response = curl_exec($curl);
        $response = self::processCurlResponse($response, curl_getinfo($curl), $curl, $errorBuf);

        curl_close($curl);
        return $response;
    }


    /**
     * Perform POST with authentication using curl API.
     * @param $url
     * @param $data
     * @param string $user user name or key
     * @param string $password password
     * @param int $authType type of authentication. One of the following:
     * CURLAUTH_BASIC, CURLAUTH_DIGEST, CURLAUTH_GSSNEGOTIATE, CURLAUTH_NTLM, CURLAUTH_ANY, CURLAUTH_ANYSAFE
     * @param string $errorBuf
     * @param $cookieSession
     * @param $headers
     * @return bool|mixed
     */
    public static function curlPOSTWithAuth($url, $data, $user, $password, $authType, &$errorBuf = null, $cookieSession, $headers = null) {
        if ($data == null) {
            $data = array();
        }
        $curl = curl_init();
        $options = array(
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_URL => $url,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => http_build_query($data),
            CURLOPT_HTTPAUTH => $authType,
            CURLOPT_USERPWD => $user . ":" . $password,
            CURLOPT_CONNECTTIMEOUT => 5,
            CURLOPT_TIMEOUT => 30
        );
        if ($cookieSession != null) {
            $options[CURLOPT_COOKIE] = $cookieSession;
        }
        if ($headers != null) {
            $options[CURLOPT_HTTPHEADER] = $headers;
        }
        curl_setopt_array($curl, $options);
        $response = curl_exec($curl);
        $response = self::processCurlResponse($response, curl_getinfo($curl), $curl, $errorBuf);
        curl_close($curl);
        return $response;
    }


    /**
     * Sent PUT request
     * 

* Note: for some reason put requires request parameters to be send in the URL. * Sending the data in the body does not seems to work. * * @param $url * @param $data * @param null $errorBuf * @param null $cookieSession * @param null $headers * @return bool|mixed|string */ public static function curlPUT($url, $data, &$errorBuf = null, $cookieSession = null, $headers = null) { if ($data == null) { $data = array(); } $payload = http_build_query($data); $curl = curl_init($url."?".$payload); $options = array( CURLOPT_CUSTOMREQUEST => "PUT", CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => 2, CURLOPT_POSTFIELDS => $payload, CURLOPT_CONNECTTIMEOUT => 5, CURLOPT_TIMEOUT => 30 ); if ($cookieSession != null) { $options[CURLOPT_COOKIE] = $cookieSession; } if ($headers != null) { $options[CURLOPT_HTTPHEADER] = $headers; } curl_setopt_array($curl, $options); $response = curl_exec($curl); $response = self::processCurlResponse($response, curl_getinfo($curl), $curl, $errorBuf); curl_close($curl); return $response; } /** * Get the top level domain from host * @param $url * @return string */ public static function getDomain($url) { $arr = parse_url($url); $host = $arr["host"]; return strtolower($host); } /** * Perform PUT with authentication using curl API. * @param $url * @param $data * @param string $user user name or key * @param string $password password * @param int $authType type of authentication. One of the following: * CURLAUTH_BASIC, CURLAUTH_DIGEST, CURLAUTH_GSSNEGOTIATE, CURLAUTH_NTLM, CURLAUTH_ANY, CURLAUTH_ANYSAFE * @param string $errorBuf * @param $cookieSession * @param $headers * @return bool|mixed */ public static function curlPUTWithAuth($url, $data, $user, $password, $authType, &$errorBuf = null, $cookieSession, $headers = null) { if ($data == null) { $data = array(); } $payload = http_build_query($data); $curl = curl_init($url."?".$payload); $options = array( CURLOPT_CUSTOMREQUEST => "PUT", CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => 2, CURLOPT_POSTFIELDS => $payload, CURLOPT_HTTPAUTH => $authType, CURLOPT_USERPWD => $user . ":" . $password, CURLOPT_CONNECTTIMEOUT => 5, CURLOPT_TIMEOUT => 30 ); if ($cookieSession != null) { $options[CURLOPT_COOKIE] = $cookieSession; } if ($headers != null) { $options[CURLOPT_HTTPHEADER] = $headers; } curl_setopt_array($curl, $options); $response = curl_exec($curl); $response = self::processCurlResponse($response, curl_getinfo($curl), $curl, $errorBuf); curl_close($curl); return $response; } /** * Perform DELETE curl API. * @param $url * @param $data * @param string $errorBuf * @param $cookieSession * @param $headers * @return bool|mixed */ public static function curlDELETE($url, $data, &$errorBuf = null, $cookieSession = null, $headers = null) { if ($data == null) { $data = array(); } $curl = curl_init($url. "?".http_build_query($data)); $options = array( CURLOPT_RETURNTRANSFER => 1, CURLOPT_CUSTOMREQUEST => "DELETE", CURLOPT_CONNECTTIMEOUT => 5, CURLOPT_TIMEOUT => 30 ); if ($cookieSession != null) { $options[CURLOPT_COOKIE] = $cookieSession; } if ($headers != null) { $options[CURLOPT_HTTPHEADER] = $headers; } curl_setopt_array($curl, $options); $response = curl_exec($curl); $response = self::processCurlResponse($response, curl_getinfo($curl), $curl, $errorBuf); curl_close($curl); return $response; } /** * Perform DELETE with authentication using curl API. * @param $url * @param $data * @param string $user user name or key * @param string $password password * @param int $authType type of authentication. One of the following: * CURLAUTH_BASIC, CURLAUTH_DIGEST, CURLAUTH_GSSNEGOTIATE, CURLAUTH_NTLM, CURLAUTH_ANY, CURLAUTH_ANYSAFE * @param null $errorBuf * @param $cookieSession * @param $headers * @return bool|mixed */ public static function curlDELETEWithAuth($url, $data, $user, $password, $authType, &$errorBuf = null, $cookieSession = null, $headers = null) { if ($data == null) { $data = array(); } $curl = curl_init($url); $options = array( CURLOPT_RETURNTRANSFER => 1, CURLOPT_POST => true, CURLOPT_CUSTOMREQUEST => "DELETE", CURLOPT_POSTFIELDS => http_build_query($data), CURLOPT_HTTPAUTH => $authType, CURLOPT_USERPWD => $user . ":" . $password, CURLOPT_CONNECTTIMEOUT => 5, CURLOPT_TIMEOUT => 30 ); if ($cookieSession != null) { $options[CURLOPT_COOKIE] = $cookieSession; } if ($headers != null) { $options[CURLOPT_HTTPHEADER] = $headers; } curl_setopt_array($curl, $options); $response = curl_exec($curl); $response = self::processCurlResponse($response, curl_getinfo($curl), $curl, $errorBuf); curl_close($curl); return $response; } /** * Path tokens array is an array of tokens that compose the value from $_SERVER["PATH_INFO"]. * The tokens are used to identify the specific controller (and model) to handle the request. *

* It is possible to specify the requested response type by appending either ".json" or ".xml" * to the end of last path token. * */ public static function getPathTokens() { $pathInfo = $_SERVER["PATH_INFO"]; if (strpos($pathInfo, "/") == 0) { $pathInfo = substr($pathInfo, 1); } if (strrpos($pathInfo, "/") == strlen($pathInfo) - 1) { $pathInfo = substr($pathInfo, 0, strlen($pathInfo) - 1); } return explode("/", $pathInfo); } /** * Get the top level domain from host * @param $url * @return string */ public static function getTLD($url) { $arr = parse_url($url); $host = $arr["host"]; $tokens = explode(".", $host); if (count($tokens) == 0 || count($tokens) == 1) { return $host; } $tokens = array_slice($tokens, 1); $tld = implode(".", $tokens); return strtolower($tld); } /** * Get the URL of the current domain * @static * @return string */ public static function getHostUrl() { $pageURL = 'http'; if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") { $pageURL .= "s"; } $pageURL .= "://"; if ($_SERVER["SERVER_PORT"] != "80") { $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"]; } else { $pageURL .= $_SERVER["SERVER_NAME"]; } return $pageURL; } public static function getHTTPSDomain() { return "https://" . $_SERVER["SERVER_NAME"] . ":443"; } /** * Get the URL of the current page * @static * @return string */ public static function getCurrentUrl() { return self::getHostUrl() . $_SERVER["REQUEST_URI"]; } /** * Send mail to shop owner to notify about successful installation * @param string $to the target Email address * @param string $subject mail Subject title * @param $message * @param string $from * @return bool true if mail was sent else false */ static function sendMail($to, $subject, $message, $from = "admin@contentglass.com") { $headers = self::prepareMailHeader($from); return mail($to, $subject, $message, $headers); } /** * Prepare the headers for sending email. * * @param $from * @return string */ static function prepareMailHeader($from) { $headers = "MIME-Version: 1.0\n"; $headers .= "Content-type: text/html; charset=iso-8859-1\n"; $headers .= "From: " . $from . "\n"; $headers .= "X-Sender: <" . $from . ">\n"; $headers .= "X-Mailer: PHP . phpversion()\n"; return $headers; } /** * Process the response from curl call - if the response can't be parsed as json and was returned with error code * prepare the error from curl or general error for the received error code and return fail. *

* If however response can be parsed as json, return the response string as is regardless of error state to * allow caller to process response data. * * * @param string $response * @param $curlInfo * @param $curl * @param $errorBuf * @return bool|string the response string or false if error detected and response can't be parsed as json. */ static function processCurlResponse($response, $curlInfo, $curl, &$errorBuf) { if (!$response || json_decode($response) == false) { if ($curlInfo["http_code"] != 200 && $curlInfo["http_code"] != 201) { //this is an error that can't be parsed as json and was returned with error code. $errorBuf = curl_error($curl); if (strlen($errorBuf) == 0) { $errorBuf = RestUtils::getStatusCodeMessage($curlInfo["http_code"]); } $response = false; } } return $response; } } <?php

Sample Response: