bjesua bjesua - 3 months ago 20
Javascript Question

Get Webservice Data using PHP

Please excuse me if i coun't explan well, i just need some examples, links or whatever you can provide me to learn how this works.

I'm trying to make this webservice work with PHP, also i have this as an example, that works with JS, but this webservice has some restrictions, like "I cannot consume at least has a different origin lenguage consumer".

This si the example.

$.ajax(
{
type:"POST",
contentType:"application/json;charset=utf-8",
url:"https://somewebsite.com/setsomedata",
data:"{}",
dataType:"json",
async: false,
success: function(msg) {
a("#compInter",msg.d.data1);
a("#ventInter",msg.d.data2);
a("#compAgencia",msg.d.data3);
a("#ventAgencia",msg.d.data4);
},
error: function(textStatus, errorThrown, errorDetail){
alert(errorDetail);
}
});


So, the problem is that i cannot use Jquery/Javascript to consume this data, because i need to use PHP to make this work.

So, i think i'm really lost in this case, that's why i would like to get some help, anything you can provide to make this work.

i'm trying to do this with PHP but i'm still gettint this error :
[failed to open stream: HTTP request failed! HTTP/1.1 500 Internal Server Error ]

and this is my PHP code:

<?php

$result = json_decode(file_get_contents('https://somewebsite.com/setsomedata'),true);
print_r($result);

?>


Again, thank you so much.

Answer

You need to use Curl to consume the data provided by that endpoint. file_get_contents works in some cases, but when you need to pass headers, cookies, etc.. you need Curl.

Here's a Curl class and sample how to use it:

$request = new Curl($yourTargetUrlHere, [
                    'proxy' => [],
                    'headers' => [],
                ]);
$curl->go();
$response = $curl->lastRequest['response']['body']);

And here's the Curl class

class Curl {
/** @var _ch Curl Handler Resource */
private $_ch;

/** @var _url Url to call */
private $_url;

/* Last Response. Raw result from curl */
public $lastRequest;

/* Last Request. Formatted */
public $lastResponse;

/* Errores generated */
public $errors = array();

/** @var _params Array containing data for Methods */
private $_params;

private $_cookiesJar = array();

private $_options = array();

/* Hold the number of redirections issued by Location on go() */
private $_redirections = 0;

/* HTTP Response codes. Currently not used, but usefull to have them here
in case we need to check cURL responses */
private $_codes = array(
    100 => 'Continue',
    101 => 'Switching Protocols',
    200 => 'OK',
    201 => 'Created',
    202 => 'Accepted',
    203 => 'Non-Authoritative Information',
    204 => 'No Content',
    205 => 'Reset Content',
    206 => 'Partial Content',
    300 => 'Multiple Choices',
    301 => 'Moved Permanently',
    302 => 'Found',
    303 => 'See Other',
    304 => 'Not Modified',
    305 => 'Use Proxy',
    306 => '(Unused)',
    307 => 'Temporary Redirect',
    400 => 'Bad Request',
    401 => 'Unauthorized',
    402 => 'Payment Required',
    403 => 'Forbidden',
    404 => 'Not Found',
    405 => 'Method Not Allowed',
    406 => 'Not Acceptable',
    407 => 'Proxy Authentication Required',
    408 => 'Request Timeout',
    409 => 'Conflict',
    410 => 'Gone',
    411 => 'Length Required',
    412 => 'Precondition Failed',
    413 => 'Request Entity Too Large',
    414 => 'Request-URI Too Long',
    415 => 'Unsupported Media Type',
    416 => 'Requested Range Not Satisfiable',
    417 => 'Expectation Failed',
    500 => 'Internal Server Error',
    501 => 'Not Implemented',
    502 => 'Bad Gateway',
    503 => 'Service Unavailable',
    504 => 'Gateway Timeout',
    505 => 'HTTP Version Not Supported',
);

public function __construct($url = false, $options = array())
{
    $this->_options = $options;

    return $this->browse($url, $this->_options);
}

public function __destruct()
{
    curl_close($this->_ch);
}

/**
 * Sets cURL options
 */
private function _setOpt($flag, $value)
{
    curl_setopt($this->_ch, $flag, $value);
}

/**
 * Explodes into an array a string of colon separated cookies
 *
 * @param  string $cookies   The cookies to be exploded
 * @param  string $returnKey Return only the value for the specified key
 *
 * @return array           Associative array
 */
private function _explodeCookies($cookies, $returnKey = false)
{
    if (empty($cookies))
        return;

    $newArray = array();
    foreach (explode(';', $cookies) as $value) {
        preg_match_all('/^(.*)=(.*)$/i', $value, $c);
        if (isset($c[1][0])) {
            $newArray[trim($c[1][0])] = $c[2][0];
        }
    }

    if ($returnKey) {
        return isset($newArray[$returnKey]) ? $newArray[$returnKey] : null;
    }

    return $newArray;
}

/**
 * Implodes an array of cookies into a string of cookies
 *
 * @param  array $cookies The cookies to be imploded
 *
 * @return string          The resulting string with the cookies colon separated
 */
private function _implodeCookies($cookies)
{
    $cookieStr = '';
    foreach ((array)$cookies as $key => $value) {
        if ($key) {
            $cookieStr .= $key . '=' . $value . ';';
        }
    }

    return $cookieStr;
}

/**
 * Saves cookies to _cookieJar variable
 */
private function _saveCookies()
{
    $parsedUrl = parse_url($this->_url);

    // Save cookies (always, it doesn't matter if 'session' is true or false)
    preg_match_all('|Set-Cookie: (.*);|U', $this->lastRequest['response']['headers'], $matches);
    if (!empty($matches[1])) {
        $currentCookies                        = $this->_cookiesJar[$parsedUrl['host']];
        $newCookies                            = array_merge((array)$this->_explodeCookies($currentCookies), (array)$this->_explodeCookies(implode(';', $matches[1])));
        $this->_cookiesJar[$parsedUrl['host']] = $this->_implodeCookies($newCookies);
    }
    $_SESSION['curl_cookies'][$parsedUrl['host']] = $this->_cookiesJar[$parsedUrl['host']];
}

/**
 * Merges an array recursively. Used to merge options
 */
private function _mergeRecursive(array $array1, $array2 = null)
{
    $merged = $array1;
    if (is_array($array2)) {
        foreach ($array2 as $key => $val) {
            if (is_array($array2[$key])) {
                $merged[$key] = isset($merged[$key]) && is_array($merged[$key]) ? $this->_mergeRecursive($merged[$key], $array2[$key]) : $array2[$key];
            } else {
                $merged[$key] = $val;
            }
        }
    }

    return $merged;
}

/**
 * Prepares the connection with URL and browsing options
 */
public function browse($url = false, $options = array())
{
    if (count($options)) {
        $this->_options = $this->_mergeRecursive($this->_options, $options);
    }

    $this->_options = $this->_mergeRecursive(array(
        'ua' => 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0',
        'cookies' => '',
        'timeout' => 30,
        'proxy' => array(
            'ip' => '',
            'port' => '',
            'username' => '',
            'password' => '',
        ),
        'ssl' => false,
        'postdata' => array(),
        'session' => true, // should we use cookies set by previous calls?
        'referer' => '',
        'headers' => array(
            'Connection: Keep-Alive',
            'Accept-Language: en-US',
            'X-Cache:',
            'X-Cache-Lookup:',
            // 'Proxy-Authorization:', // can't set this, proxy fails authentication
            // 'Accept-Encoding: gzip', // can't set this, response doesn't get unzipped
            // 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8', // can't set this on post
        ),
        'cb' => false, // callback to manipulate the options
    ), $this->_options);

    if (is_callable($this->_options['cb'])) {
        $_fn            = $this->_options['cb'];
        $this->_options = $_fn($this->_options, $this);
    }

    // Init curl
    $this->_ch = curl_init();
    if (!empty($url)) {
        $this->_url = $url;
    }

    if (!empty($this->_url)) {
        // prepare the cookie jar
        $parsedUrl                             = parse_url($this->_url);
        $this->_cookiesJar[$parsedUrl['host']] = !empty($this->_cookiesJar[$parsedUrl['host']]) ? $this->_cookiesJar[$parsedUrl['host']] : '';
        curl_setopt($this->_ch, CURLOPT_URL, $this->_url);
    }

    curl_setopt($this->_ch, CURLOPT_USERAGENT, $this->_options['ua']);
    curl_setopt($this->_ch, CURLOPT_RETURNTRANSFER, true);

    // We set this to false, to grab cookies set on the request.
    // Setting to true will cause to follow redirection but the cookies wont be stored.
    // We save cookies, parse Location, and then issue a new request to the new Location
    curl_setopt($this->_ch, CURLOPT_FOLLOWLOCATION, false);

    curl_setopt($this->_ch, CURLOPT_SSL_VERIFYPEER, $this->_options['ssl']); // do not verify CA
    curl_setopt($this->_ch, CURLOPT_VERBOSE, true);
    curl_setopt($this->_ch, CURLOPT_HEADER, true);
    curl_setopt($this->_ch, CURLINFO_HEADER_OUT, true);
    curl_setopt($this->_ch, CURLOPT_FRESH_CONNECT, false);
    curl_setopt($this->_ch, CURLOPT_AUTOREFERER, false);
    curl_setopt($this->_ch, CURLOPT_COOKIESESSION, true);
    curl_setopt($this->_ch, CURLOPT_TIMEOUT, $this->_options['timeout']);

    if (!empty($this->_options['referer'])) {
        curl_setopt($this->_ch, CURLOPT_REFERER, $this->_options['referer']);
    }

    // Prepare proxy
    if (!empty($this->_options['proxy']['ip'])) {
        curl_setopt($this->_ch, CURLOPT_PROXY, $this->_options['proxy']['ip']);
        curl_setopt($this->_ch, CURLOPT_PROXYPORT, $this->_options['proxy']['port']);
        curl_setopt($this->_ch, CURLOPT_PROXYTYPE, 'HTTP');

        if (!empty($this->_options['proxy']['username'])) {
            curl_setopt($this->_ch, CURLOPT_PROXYUSERPWD, $this->_options['proxy']['username'] . ':' . $this->_options['proxy']['password']);
        }
    }

    // Prepare POST data
    if (!empty($this->_options['postdata'])) {
        $this->setPost($this->_options['postdata']);
    }

    // Prepare cookies and session
    if ($this->_options['session']) {
        @session_start();

        // pull cookies that we might have in session
        if ($this->_url && !empty($_SESSION['curl_cookies'][$parsedUrl['host']])) {
            $this->_cookiesJar[$parsedUrl['host']] = $_SESSION['curl_cookies'][$parsedUrl['host']];
        }
    }

    // Prepare headers
    curl_setopt($this->_ch, CURLOPT_HTTPHEADER, $this->_options['headers']);

    return $this;
}

/**
 * Sends the request to the specified URL
 */
public function go()
{
    if (isset($this->_params['GET'])) {
        $this->_url .= '?' . $this->_params['GET'];
    }

    // Set cokies and session info here because clearCache() can be called
    // prior sending the request
    $parsedUrl = parse_url($this->_url);
    if (!empty($this->_options['cookies'])) {
        curl_setopt($this->_ch, CURLOPT_COOKIE, $this->_options['cookies']);
    } elseif ($this->_url && $this->_options['session'] && !empty($this->_cookiesJar[$parsedUrl['host']])) {
        curl_setopt($this->_ch, CURLOPT_COOKIE, $this->_cookiesJar[$parsedUrl['host']]);
    }

    try {
        $this->lastResponse = curl_exec($this->_ch);
    } catch (Exception $e) {
        $this->errors[] = $e->getMessage();

        return false;
    }

    $headerSent = curl_getinfo($this->_ch, CURLINFO_HEADER_OUT);

    // Get the headers
    $parts = explode("\r\n\r\nHTTP/", $this->lastResponse);
    $parts = (count($parts) > 1 ? 'HTTP/' : '') . array_pop($parts);
    @list($responseHeader, $responseBody) = explode("\r\n\r\n", $parts, 2);

    preg_match_all('/^Location:(.*)$/mi', $this->lastResponse, $matches);
    $location = '';
    if (!empty($matches[1])) {
        $location = trim($matches[1][0]);
    }

    // Put request in the structure
    $this->lastRequest = array(
        'request' => array(
            'headers' => curl_getinfo($this->_ch, CURLINFO_HEADER_OUT),
            'url' => $this->_url,
            'proxy' => !empty($this->_options['proxy']['ip']) ? implode(':', $this->_options['proxy']) : '',
            'body' => !empty($this->_options['postdata']) ? $this->_options['postdata'] : '',
        ),
        'response' => array(
            'headers' => $responseHeader,
            'time' => curl_getinfo($this->_ch, CURLINFO_TOTAL_TIME),
            'location' => $location,
            'info' => curl_getinfo($this->_ch),
            'body' => $responseBody,
        ),
    );
    $this->_saveCookies();

    // Follow new location redirect
    if ($this->_redirections > 10) {
        die('Loop redirection');
    }

    if (!empty($this->lastRequest['response']['location'])) {
        $this->_redirections++;
        $this->browse($this->lastRequest['response']['location'])->go();
    } else {
        $this->_redirections = 0;
    }

    return $this->lastRequest;
}

/**
 * Destroys session and clears cookies.
 */
public function clearCache()
{
    @session_destroy();
    $parsedUrl                             = parse_url($this->_url);
    $this->_cookiesJar[$parsedUrl['host']] = '';
}

/**
 * Sets the POST params to be sent
 */
public function setPost($params)
{
    $this->_params['POST'] = $params;
    curl_setopt($this->_ch, CURLOPT_POST, true);
    curl_setopt($this->_ch, CURLOPT_POSTFIELDS, is_array($this->_params['POST']) ? http_build_query($this->_params['POST']) : $this->_params['POST']);
}

/**
 * Sets the GET params to be sent
 */
public function setGet($params)
{
    $this->_params['GET'] = http_build_query($params);
}

public function getCookie($key)
{
    $parsedUrl = parse_url($this->_url);

    return $this->_explodeCookies($this->_cookiesJar[$parsedUrl['host']], $key);
}

public function debug()
{
    $this->lastRequest['response']['body'] = htmlspecialchars($this->lastRequest['response']['body'], ENT_QUOTES, 'UTF-8');
    echo '<pre>' . print_r($this->lastRequest, 1) . '</pre>';
    die();
}
}