Example #1
1
 /**
  * 执行一个 HTTP 请求
  *
  * @param string 	$url 	执行请求的URL 
  * @param mixed	$params 表单参数
  * 							可以是array, 也可以是经过url编码之后的string
  * @param mixed	$cookie cookie参数
  * 							可以是array, 也可以是经过拼接的string
  * @param string	$method 请求方法 post / get
  * @param string	$protocol http协议类型 http / https
  * @return array 结果数组
  */
 public static function makeRequest($url, $params, $cookie, $method = 'post', $protocol = 'http')
 {
     $query_string = self::makeQueryString1($params);
     $cookie_string = self::makeCookieString($cookie);
     $ch = curl_init();
     if ('get' == $method) {
         curl_setopt($ch, CURLOPT_URL, "{$url}?{$query_string}");
     } else {
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_POST, 1);
         curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
     }
     curl_setopt($ch, CURLOPT_HEADER, false);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
     // disable 100-continue
     curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
     if (!empty($cookie_string)) {
         curl_setopt($ch, CURLOPT_COOKIE, $cookie_string);
     }
     if ('https' == $protocol) {
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
         curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
     }
     $ret = curl_exec($ch);
     $err = curl_error($ch);
     if (false === $ret || !empty($err)) {
         $errno = curl_errno($ch);
         $info = curl_getinfo($ch);
         curl_close($ch);
         return array('result' => false, 'errno' => $errno, 'msg' => $err, 'info' => $info);
     }
     curl_close($ch);
     return array('result' => true, 'msg' => $ret);
 }
function sendPushNotificationToGCM($registration_ids, $message)
{
    $GCM_SERVER_API_KEY = $_ENV["GCM_SERVER_API_KEY"];
    $url = 'https://fcm.googleapis.com/fcm/send';
    $fields = array('registration_ids' => $registration_ids, 'data' => $message);
    // Update your Google Cloud Messaging API Key
    if (!defined('GOOGLE_API_KEY')) {
        define("GOOGLE_API_KEY", $GCM_SERVER_API_KEY);
    }
    $headers = array('Authorization: key=' . GOOGLE_API_KEY, 'Content-Type: application/json');
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
    $result = curl_exec($ch);
    if ($result === FALSE) {
        die('Curl failed: ' . curl_error($ch));
    }
    curl_close($ch);
    return $result;
}
function query($type)
{
    if (!is_null($type)) {
        //get parameter data
        $parameters = Flight::request()->query->getData();
        $cacheKey = $type . json_encode($parameters);
        if (apc_exists($cacheKey)) {
            echo apc_fetch($cacheKey);
        } else {
            $url = 'http://localhost:8080/sparql';
            $query_string = file_get_contents('queries/' . $type . '.txt');
            foreach ($parameters as $key => $value) {
                $query_string = str_replace('{' . $key . '}', $value, $query_string);
            }
            //open connection
            $ch = curl_init();
            //set the url, number of POST vars, POST data
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/sparql-query"));
            curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            //execute post
            $result = curl_exec($ch);
            //close connection
            curl_close($ch);
            apc_store($cacheKey, $result);
            echo $result;
        }
    }
}
 /**
  * @param $url
  * @param $destination
  * @return bool|null
  */
 public function fetch($url, $destination)
 {
     try {
         $ret = null;
         $url = $this->addhttp($url);
         $ch = curl_init($url . '/favicon.ico');
         curl_setopt($ch, CURLOPT_TIMEOUT, 5);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
         $contents = curl_exec($ch);
         $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
         if ($httpCode == 200) {
             $fp = fopen($destination, 'w+');
             fwrite($fp, $contents);
             fclose($fp);
             $ret = true;
             if ($this->converter) {
                 $ret = $this->converter->convert($destination);
             }
         }
         curl_close($ch);
         return $ret;
     } catch (\Exception $e) {
         // hmm ok, let the next Fetcher try its luck
     }
     return null;
 }
Example #5
0
 public function process($args)
 {
     $this->output = "";
     if (strlen(trim($args)) > 0) {
         try {
             $url = "https://www.googleapis.com/youtube/v3/search?part=id%2Csnippet&maxResults=3&type=video&q=" . urlencode($args) . "&key=" . $this->apikey;
             $ch = curl_init();
             curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
             curl_setopt($ch, CURLOPT_URL, $url);
             curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
             $respuesta = curl_exec($ch);
             curl_close($ch);
             $resultados = json_decode($respuesta);
             if (isset($resultados->error)) {
                 $this->output = "Ocurrió un problema al realizar la busqueda: " . $resultados->error->errors[0]->reason;
             } else {
                 if (count($resultados->items) > 0) {
                     $videos = array();
                     foreach ($resultados->items as $video) {
                         array_push($videos, "http://www.youtube.com/watch?v=" . $video->id->videoId . " - " . $video->snippet->title);
                     }
                     $this->output = join("\n", $videos);
                 } else {
                     $this->output = "No se pudieron obtener resultados al realizar la busqueda indicada.";
                 }
             }
         } catch (Exception $e) {
             $this->output = "Ocurrió un problema al realizar la busqueda: " . $e->getMessage();
         }
     } else {
         $this->output = "Digame que buscar que no soy adivino.";
     }
 }
Example #6
0
 public function pdt($txn)
 {
     $params = array('at' => $this->atPaypal, 'tx' => $txn, 'cmd' => '_notify-synch');
     $content = '';
     foreach ($params as $key => $val) {
         $content .= '&' . $key . '=' . urlencode($val);
     }
     $c = curl_init();
     curl_setopt($c, CURLOPT_URL, $this->paypalEndpoint);
     curl_setopt($c, CURLOPT_VERBOSE, TRUE);
     curl_setopt($c, CURLOPT_SSL_VERIFYPEER, FALSE);
     curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($c, CURLOPT_POST, 1);
     curl_setopt($c, CURLOPT_POSTFIELDS, $content);
     $response = curl_exec($c);
     if (!$response) {
         echo "FAILED: " . curl_error($c) . "(" . curl_errno($c) . ")";
         curl_close($c);
         return false;
     } else {
         $str = urldecode($response);
         $res = explode("\n", strip_tags($str));
         $result = array();
         foreach ($res as $val) {
             $r = explode("=", $val);
             if (count($r) > 1) {
                 $result[$r[0]] = $r[1];
             }
         }
         curl_close($c);
         return $result;
     }
 }
Example #7
0
 function jws_fetchUrl($url)
 {
     //Can we use cURL?
     if (is_callable('curl_init')) {
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($ch, CURLOPT_TIMEOUT, 20);
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
         $feedData = curl_exec($ch);
         curl_close($ch);
         //If not then use file_get_contents
     } elseif (ini_get('allow_url_fopen') == 1 || ini_get('allow_url_fopen') === TRUE) {
         $feedData = @file_get_contents($url);
         //Or else use the WP HTTP API
     } else {
         if (!class_exists('WP_Http')) {
             include_once ABSPATH . WPINC . '/class-http.php';
         }
         $request = new WP_Http();
         $result = $request->request($url);
         $feedData = $result['body'];
     }
     /*    echo $feedData;
     		exit;*/
     return $feedData;
 }
Example #8
0
 public function getUserInfo()
 {
     $url = 'https://api.github.com/user?' . http_build_query(array('access_token' => $this->token->access_token));
     // Create a curl handle to a non-existing location
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     //Set curl to return the data instead of printing it to the browser.
     curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
     # timeout after 10 seconds, you can increase it
     curl_setopt($ch, CURLOPT_URL, $url);
     #set the url and get string together
     curl_setopt($ch, CURLOPT_USERAGENT, 'dukt-oauth');
     #set the url and get string together
     $json = '';
     if (($json = curl_exec($ch)) === false) {
         throw new \Exception(curl_error($ch));
     }
     curl_close($ch);
     $user = json_decode($json);
     if (!isset($user->id)) {
         throw new \Exception($json);
     }
     // Create a response from the request
     return array('uid' => $user->id, 'nickname' => $user->login, 'name' => $user->name, 'email' => $user->email, 'urls' => array('GitHub' => 'http://github.com/' . $user->login, 'Blog' => $user->blog));
 }
Example #9
0
 public function exec()
 {
     $active = null;
     do {
         do {
             $status = curl_multi_exec($this->curlHandle, $active);
         } while ($status == CURLM_CALL_MULTI_PERFORM);
         if ($status != CURLM_OK) {
             break;
         }
         $response = array();
         $respond = curl_multi_info_read($this->curlHandle);
         while ($respond) {
             $callback = $this->requestMap[(string) $respond['handle']];
             $responses[$callback]['content'] = curl_multi_getcontent($respond['handle']);
             $responses[$callback]['httpcode'] = curl_getinfo($respond['handle'], CURLINFO_HTTP_CODE);
             curl_multi_remove_handle($this->curlHandle, $respond['handle']);
             curl_close($respond['handle']);
             $respond = curl_multi_info_read($this->curlHandle);
         }
         if ($active > 0) {
             curl_multi_select($this->curlHandle, 0.05);
         }
     } while ($active);
     return $responses;
 }
Example #10
0
 /**
  * Returns the output of a remote URL. Any [curl option](http://php.net/curl_setopt)
  * may be used.
  *
  *     // Do a simple GET request
  *     $data = Remote::get($url);
  *
  *     // Do a POST request
  *     $data = Remote::get($url, array(
  *         CURLOPT_POST       => TRUE,
  *         CURLOPT_POSTFIELDS => http_build_query($array),
  *     ));
  *
  * @param   string   remote URL
  * @param   array    curl options
  * @return  string
  * @throws  Kohana_Exception
  */
 public static function remote($url, array $options = NULL)
 {
     // The transfer must always be returned
     $options[CURLOPT_RETURNTRANSFER] = TRUE;
     // Open a new remote connection
     $remote = curl_init($url);
     // Set connection options
     if (!curl_setopt_array($remote, $options)) {
         throw new Kohana_Exception('Failed to set CURL options, check CURL documentation: :url', array(':url' => 'http://php.net/curl_setopt_array'));
     }
     // Get the response
     $response = curl_exec($remote);
     // Get the response information
     $code = curl_getinfo($remote, CURLINFO_HTTP_CODE);
     if ($code and $code < 200 or $code > 299) {
         $error = $response;
     } elseif ($response === FALSE) {
         $error = curl_error($remote);
     }
     // Close the connection
     curl_close($remote);
     if (isset($error)) {
         throw new Kohana_OAuth_Exception('Error fetching remote :url [ status :code ] :error', array(':url' => $url, ':code' => $code, ':error' => $error));
     }
     return $response;
 }
Example #11
0
 public static function httpRequest($req, $hash_config = NULL)
 {
     $config = Obj2xml::getConfig($hash_config);
     if ((int) $config['print_xml']) {
         echo $req;
     }
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_PROXY, $config['proxy']);
     curl_setopt($ch, CURLOPT_POST, true);
     curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: text/xml'));
     curl_setopt($ch, CURLOPT_URL, $config['url']);
     curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
     curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, true);
     curl_setopt($ch, CURLOPT_TIMEOUT, $config['timeout']);
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     //curl_setopt($ch, CURLOPT_SSLVERSION, 3);
     $output = curl_exec($ch);
     //$responseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
     if (!$output) {
         throw new \Exception(curl_error($ch));
     } else {
         curl_close($ch);
         if ((int) $config['print_xml']) {
             echo $output;
         }
         return $output;
     }
 }
Example #12
0
 function downloadPackage($src, $dst)
 {
     if (ini_get('allow_url_fopen')) {
         $file = @file_get_contents($src);
     } else {
         if (function_exists('curl_init')) {
             $ch = curl_init();
             curl_setopt($ch, CURLOPT_URL, $src);
             curl_setopt($ch, CURLOPT_HEADER, 0);
             curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
             curl_setopt($ch, CURLOPT_TIMEOUT, 180);
             $safeMode = @ini_get('safe_mode');
             $openBasedir = @ini_get('open_basedir');
             if (empty($safeMode) && empty($openBasedir)) {
                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
             }
             $file = curl_exec($ch);
             curl_close($ch);
         } else {
             return false;
         }
     }
     file_put_contents($dst, $file);
     return file_exists($dst);
 }
function wpc_curl_download($url)
{
    // is cURL installed yet?
    if (!function_exists('curl_init')) {
        die('Sorry cURL is not installed!');
    }
    // OK cool - then let's create a new cURL resource handle
    $ch = curl_init();
    // Now set some options (most are optional)
    // Set URL to download
    curl_setopt($ch, CURLOPT_URL, $url);
    // Set a referer
    curl_setopt($ch, CURLOPT_REFERER, $_SERVER['SERVER_NAME']);
    // User agent
    curl_setopt($ch, CURLOPT_USERAGENT, 'MozillaXYZ/1.0');
    // Include header in result? (0 = yes, 1 = no)
    curl_setopt($ch, CURLOPT_HEADER, 0);
    // Should cURL return or print out the data? (true = return, false = print)
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // Timeout in seconds
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    // Download the given URL, and return output
    $output = curl_exec($ch);
    // Close the cURL resource, and free system resources
    curl_close($ch);
    return $output;
}
 function test_instam($key)
 {
     // returns array, or FALSE
     // snap(basename(__FILE__) . __LINE__, $key_val);
     // http://www.instamapper.com/api?action=getPositions&key=4899336036773934943
     $url = "http://www.instamapper.com/api?action=getPositions&key={$key}";
     $data = "";
     if (function_exists("curl_init")) {
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         $data = curl_exec($ch);
         curl_close($ch);
     } else {
         // not CURL
         if ($fp = @fopen($url, "r")) {
             while (!feof($fp) && strlen($data) < 9000) {
                 $data .= fgets($fp, 128);
             }
             fclose($fp);
         } else {
             //					print "-error 1";		// @fopen fails
             return FALSE;
         }
     }
     /*
     InstaMapper API v1.00
     1263013328977,bold,1236239763,34.07413,-118.34940,25.0,0.0,335
     1088203381874,CABOLD,1236255869,34.07701,-118.35262,27.0,0.4,72
     */
     //			dump($data);
     $ary_data = explode("\n", $data);
     return $ary_data;
 }
Example #15
0
function make_api_call($url, $http_method, $post_data = array(), $uid = null, $key = null)
{
    $full_url = 'https://app.onepagecrm.com/api/v3/' . $url;
    $ch = curl_init($full_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $http_method);
    $timestamp = time();
    $auth_data = array($uid, $timestamp, $http_method, sha1($full_url));
    $request_headers = array();
    // For POST and PUT requests we will send data as JSON
    // as with regular "form data" request we won't be able
    // to send more complex structures
    if ($http_method == 'POST' || $http_method == 'PUT') {
        $request_headers[] = 'Content-Type: application/json';
        $json_data = json_encode($post_data);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
        $auth_data[] = sha1($json_data);
    }
    // Set auth headers if we are logged in
    if ($key != null) {
        $hash = hash_hmac('sha256', implode('.', $auth_data), $key);
        $request_headers[] = "X-OnePageCRM-UID: {$uid}";
        $request_headers[] = "X-OnePageCRM-TS: {$timestamp}";
        $request_headers[] = "X-OnePageCRM-Auth: {$hash}";
    }
    curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
    $result = json_decode(curl_exec($ch));
    curl_close($ch);
    if ($result->status > 99) {
        echo "API call error: {$result->message}\n";
        return null;
    }
    return $result;
}
Example #16
0
 private function executeCurl($url, array $params)
 {
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $url);
     if (isset($params["POST"])) {
         curl_setopt($ch, CURLOPT_POST, 1);
         $queryString = urlencode(http_build_query($params["POST"]));
         curl_setopt($ch, CURLOPT_POSTFIELDS, $queryString);
     }
     if (isset($params["PUT"])) {
         //@TODO
         throw new Exception('The PUT is currently not supported');
     }
     if (isset($params["GET"])) {
         curl_setopt($ch, CURLOPT_HTTPGET, 1);
         $queryString = urlencode(http_build_query($params["GET"]));
         curl_setopt($ch, CURLOPT_URL, $url . '?' . $queryString);
     }
     if (isset($params["HEADERS"])) {
         curl_setopt($ch, CURLOPT_HEADER, 1);
         curl_setopt($ch, CURLOPT_HTTPHEADER, $params["HEADERS"]);
     }
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
     $response = curl_exec($ch);
     curl_close($ch);
     return $response;
 }
 /**
  * Send a cURL HTTP POST request and retrieve response
  * 
  * @param cURL-Handler $curl
  * @return string
  */
 public function send($testmode, $xml)
 {
     $curl = $this->_getCurl($testmode, $xml);
     $result = curl_exec($curl);
     curl_close($curl);
     return $result;
 }
Example #18
0
function toastup($channel, $message)
{
    $channel_uri = urldecode($channel);
    $toast_xml = '<?xml version="1.0" encoding="utf-8" ?>
		<wp:Notification xmlns:wp="WPNotification">
			<wp:Toast>
				<wp:Text1>' . 信息: . '</wp:Text1>
				<wp:Text2>' . $message . '</wp:Text2>
			</wp:Toast>
		</wp:Notification>';
    $headers = array('Content-Type: text/xml', "Content-Length: " . strlen($toast_xml), "X-WindowsPhone-Target: toast", "X-NotificationClass: 2");
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $channel_uri);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 2);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_POSTFIELDS, "{$toast_xml}");
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($ch);
    $response = curl_getinfo($ch);
    curl_close($ch);
    return $response['http_code'];
}
Example #19
0
 /**
  * Make an api request
  *
  * @param string $resource
  * @param array $params
  * @param string $method
  */
 public function call($resource, $params = array())
 {
     $queryString = 'access_token=' . $this->getAccessToken();
     if (!empty($params) && is_array($params)) {
         $queryString .= http_build_query($params);
     }
     $requestUrl = self::API_URL . $resource . '/?' . $queryString;
     $curl = curl_init();
     $curl_options = array(CURLOPT_RETURNTRANSFER => 1, CURLOPT_URL => $requestUrl, CURLOPT_TIMEOUT => 30, CURLOPT_HTTPHEADER => array('Accept: application/json', 'appid: nike'));
     curl_setopt_array($curl, $curl_options);
     $response = curl_exec($curl);
     $curl_info = curl_getinfo($curl);
     //@todo test for curl error
     if ($response === FALSE) {
         throw new Exception(curl_error($curl), curl_errno($curl));
     }
     curl_close($curl);
     //@todo test for any non 200 response
     if ($curl_info['http_code'] != 200) {
         throw new Exception("Response: Bad response - HTTP Code:" . $curl_info['http_code']);
     }
     $jsonArray = json_decode($response);
     if (!is_object($jsonArray)) {
         throw new Exception("Response: Response was not a valid response");
     }
     return $jsonArray;
 }
Example #20
0
 public function request($type, $url, array $params = array(), array $properties = array())
 {
     $params = array_filter($params);
     $ch = curl_init();
     switch (strtolower($type)) {
         case 'post':
             curl_setopt($ch, CURLOPT_POST, true);
             curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
             break;
         case 'get':
             $url = $this->buildQueryString($url, $params);
             break;
         case 'delete':
             $url = $this->buildQueryString($url, $params);
             curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
             break;
         case 'update':
         case 'put':
             curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
             break;
     }
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_HEADER, false);
     curl_setopt($ch, CURLOPT_URL, $url);
     foreach ($properties as $propertyKey => $propertyValue) {
         curl_setopt($ch, $propertyKey, $propertyValue);
     }
     $response = curl_exec($ch);
     $info = curl_getinfo($ch);
     curl_close($ch);
     return new Response($info, $response);
 }
 public function processRequest($method = 'POST')
 {
     $params = http_build_query($this->urlParams);
     if (w2p_check_url($this->url)) {
         if (function_exists('curl_init')) {
             $ch = curl_init($this->url);
             curl_setopt($ch, CURLOPT_POST, 1);
             curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
             curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
             $response = curl_exec($ch);
             curl_close($ch);
         } else {
             /*
              * Thanks to Wez Furlong for the core of the logic for this 
              *   method to POST data via PHP without cURL
              *   http://netevil.org/blog/2006/nov/http-post-from-php-without-curl
              */
             $ctx = stream_context_create($params);
             $fp = @fopen($this->url, 'rb', false, $ctx);
             if (!$fp) {
                 throw new Exception("Problem with {$url}, {$php_errormsg}");
             }
             $response = @stream_get_contents($fp);
             if ($response === false) {
                 throw new Exception("Problem reading data from {$url}, {$php_errormsg}");
             }
         }
         return $response;
     } else {
         //throw an error?
     }
 }
Example #22
0
 function make_call($call_options)
 {
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $call_options['route']);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
     curl_setopt($ch, CURLOPT_USERPWD, $call_options['credentials']);
     curl_setopt($ch, CURLOPT_USERAGENT, $call_options['userAgent']);
     curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: ' . $call_options['contentType']));
     switch ($call_options['method']) {
         case CS_REST_PUT:
             curl_setopt($ch, CURLOPT_CUSTOMREQUEST, CS_REST_PUT);
             curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Length: ' . strlen($call_options['data'])));
             curl_setopt($ch, CURLOPT_POSTFIELDS, $call_options['data']);
             break;
         case CS_REST_POST:
             curl_setopt($ch, CURLOPT_POST, true);
             curl_setopt($ch, CURLOPT_POSTFIELDS, $call_options['data']);
             break;
         case CS_REST_DELETE:
             curl_setopt($ch, CURLOPT_CUSTOMREQUEST, CS_REST_DELETE);
             break;
     }
     $response = curl_exec($ch);
     if (!$response && $response !== '') {
         trigger_error('Error making request with curl_error: ' . curl_error($ch));
     }
     $this->_log->log_message('API Call Info for ' . $call_options['method'] . ' ' . curl_getinfo($ch, CURLINFO_EFFECTIVE_URL) . ': ' . curl_getinfo($ch, CURLINFO_SIZE_UPLOAD) . ' bytes uploaded. ' . curl_getinfo($ch, CURLINFO_SIZE_DOWNLOAD) . ' bytes downloaded' . ' Total time (seconds): ' . curl_getinfo($ch, CURLINFO_TOTAL_TIME), get_class($this), CS_REST_LOG_VERBOSE);
     $result = array('code' => curl_getinfo($ch, CURLINFO_HTTP_CODE), 'response' => $response);
     curl_close($ch);
     return $result;
 }
Example #23
0
 public function updateCurrencies()
 {
     if (extension_loaded('curl')) {
         $data = array();
         $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "currency WHERE code != '" . $this->db->escape($this->config->get('config_currency')) . "' AND date_modified > '" . date(strtotime('-1 day')) . "'");
         foreach ($query->rows as $result) {
             $data[] = $this->config->get('config_currency') . $result['code'] . '=X';
         }
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, 'http://download.finance.yahoo.com/d/quotes.csv?s=' . implode(',', $data) . '&f=sl1&e=.csv');
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         $content = curl_exec($ch);
         curl_close($ch);
         $lines = explode("\n", trim($content));
         foreach ($lines as $line) {
             $currency = substr($line, 4, 3);
             $value = substr($line, 11, 6);
             if ((double) $value) {
                 $this->db->query("UPDATE " . DB_PREFIX . "currency SET value = '" . (double) $value . "', date_modified = NOW() WHERE code = '" . $this->db->escape($currency) . "'");
             }
         }
         $this->db->query("UPDATE " . DB_PREFIX . "currency SET value = '1.00000', date_modified = NOW() WHERE code = '" . $this->db->escape($this->config->get('config_currency')) . "'");
         $this->cache->delete('currency');
     }
 }
Example #24
0
function updateIndex($lang, $file)
{
    $fileData = readFileData($file);
    $filename = $file->getPathName();
    list($filename) = explode('.', $filename);
    $path = $filename . '.html';
    $id = str_replace($lang . '/', '', $filename);
    $id = str_replace('/', '-', $id);
    $id = trim($id, '-');
    $url = implode('/', array(ES_URL, ES_INDEX, $lang, $id));
    $data = array('contents' => $fileData['contents'], 'title' => $fileData['title'], 'url' => $path);
    $data = json_encode($data);
    $size = strlen($data);
    $fh = fopen('php://memory', 'rw');
    fwrite($fh, $data);
    rewind($fh);
    echo "Sending request:\n\tfile: {$file}\n\turl: {$url}\n";
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_PUT, true);
    curl_setopt($ch, CURLOPT_INFILE, $fh);
    curl_setopt($ch, CURLOPT_INFILESIZE, $size);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    $metadata = curl_getinfo($ch);
    if ($metadata['http_code'] > 400) {
        echo "[ERROR] Failed to complete request.\n";
        var_dump($response);
        exit(2);
    }
    curl_close($ch);
    fclose($fh);
    echo "Sent {$file}\n";
}
Example #25
0
 protected function callFunction($class, $function, $params)
 {
     $paramString = "/";
     foreach ($params as $param) {
         $paramString .= urlencode($param) . "/";
     }
     $url = Config::WWWPath . "/server/json.php/v1." . $class . "." . $function . $paramString;
     if (TestConf::verbosity > 3) {
         echo "\tCalling URL: " . $url . "\n";
     }
     if (!function_exists('curl_init')) {
         die('You must have cUrl installed to run this test.');
     }
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $url);
     curl_setopt($ch, CURLOPT_REFERER, Config::WWWPath . '/server/test');
     curl_setopt($ch, CURLOPT_HEADER, 0);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_TIMEOUT, 10);
     $output = curl_exec($ch);
     curl_close($ch);
     if (TestConf::verbosity == 5) {
         echo "\t\tResult: " . $this->stripComments($output) . "\n";
     }
     if (TestConf::verbosity > 5) {
         echo "\t\tResult: " . $output . "\n";
     }
     return $output;
 }
 function translate($text, $d = '')
 {
     $s = 'en';
     if ($d == '') {
         $d = 'en';
     }
     if ($d != 'en') {
         $lang_pair = urlencode($s . '|' . $d);
         $q = rawurlencode($text);
         // Google's API translator URL
         $url = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=" . $q . "&langpair=" . $lang_pair;
         // Make sure to set CURLOPT_REFERER because Google doesn't like if you leave the referrer out
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($ch, CURLOPT_REFERER, "http://www.yoursite.com/translate.php");
         $body = curl_exec($ch);
         curl_close($ch);
         $json = json_decode($body, true);
         $tranlate = $json['responseData']['translatedText'];
         echo $tranlate;
     } else {
         echo $text;
     }
 }
 public function __destruct()
 {
     // Если у нас открыт экземпляр curl, то нужно его закрывать
     if (!is_null(self::$_curlInstance)) {
         curl_close(self::$_curlInstance);
     }
 }
Example #28
0
 /**
  * Cleanup
  */
 protected function close()
 {
     if (is_resource($this->curl)) {
         curl_close($this->curl);
         $this->curl = null;
     }
 }
Example #29
0
 /**
  * Sending Push Notification
  */
 public function send_notification($registation_ids, $message)
 {
     // include config
     include_once './config.php';
     // Set POST variables
     $url = 'https://android.googleapis.com/gcm/send';
     $fields = array('registration_ids' => $registation_ids, 'data' => $message);
     $headers = array('Authorization: key=' . GOOGLE_API_KEY, 'Content-Type: application/json');
     // Open connection
     $ch = curl_init();
     // Set the url, number of POST vars, POST data
     curl_setopt($ch, CURLOPT_URL, $url);
     curl_setopt($ch, CURLOPT_POST, true);
     curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     // Disabling SSL Certificate support temporarly
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
     curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
     // Execute post
     $result = curl_exec($ch);
     if ($result === FALSE) {
         die('Curl failed: ' . curl_error($ch));
     }
     // Close connection
     curl_close($ch);
     echo $result;
 }
Example #30
-1
 /**
  * Make API request
  *
  * @param string $method string API method to request
  * @param array $params Additional request parameters
  * @return array / boolean Response array / boolean false on failure
  */
 public function request($method, $params = array())
 {
     $this->_errors = array();
     if (empty($method)) {
         //Check if API method is not empty
         $this->_errors = array('API method is missing');
         return false;
     }
     //Our request parameters
     $requestParams = array('METHOD' => $method, 'VERSION' => $this->_version) + $this->_credentials;
     //Building our NVP string
     $request = http_build_query($requestParams + $params);
     //cURL settings
     $curlOptions = array(CURLOPT_URL => $this->_endPoint, CURLOPT_VERBOSE => 1, CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2, CURLOPT_CAINFO => dirname(__FILE__) . '/cacert.pem', CURLOPT_RETURNTRANSFER => 1, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => $request);
     $ch = curl_init();
     curl_setopt_array($ch, $curlOptions);
     //Sending our request - $response will hold the API response
     $response = curl_exec($ch);
     //Checking for cURL errors
     if (curl_errno($ch)) {
         $this->_errors = curl_error($ch);
         curl_close($ch);
         return false;
         //Handle errors
     } else {
         curl_close($ch);
         $responseArray = array();
         parse_str($response, $responseArray);
         // Break the NVP string to an array
         return $responseArray;
     }
 }