/** * 初始化 */ public static function init() { $object = new Curl(); $object->cookiePath(); //初始cookie路径 return $object; }
/** * get the next song in the playlist */ private function nextSong() { $curl = new Curl(); $songArray = $curl->getArray("http://8tracks.com/sets/" . $this->playToken . "/next?mix_id=" . $this->mixId . "&api_version=2&format=jsonh"); $status = $songArray["status"]; if (!preg_match('/(200)/', $status)) { if (preg_match('/(403)/', $status)) { $this->output->error("8tracks made a boo boo. (" . $status . ")", 403); } else { $this->output->error("8tracks made a boo boo. (" . $status . ")"); } } if (isset($songArray["set"]["track"]["id"])) { $songId = $songArray["set"]["track"]["id"]; $title = $songArray["set"]["track"]["name"]; $artist = $songArray["set"]["track"]["performer"]; $album = $songArray["set"]["track"]["release_name"]; $duration = $songArray["set"]["track"]["play_duration"]; $songUrl = $songArray["set"]["track"]["url"]; $song = $this->db->select("SELECT mixId FROM 8tracks_playlists_songs WHERE mixId=? AND songId=? LIMIT 1", array($this->mixId, $songId), array("%d", "%d")); if (empty($song)) { $this->db->insert("8tracks_playlists_songs", array("mixId" => $this->mixId, "songId" => $songId, "trackNumber" => $this->trackNumber), array("%d", "%d", "%d")); $song = $this->db->select("SELECT songId FROM 8tracks_songs WHERE songId=? LIMIT 1", array($songId), array("%d")); if (empty($song)) { $this->db->insert("8tracks_songs", array("songId" => $songId, "title" => $title, "artist" => $artist, "album" => $album, "duration" => $duration, "songUrl" => $songUrl), array("%d", "%s", "%s", "%s", "%d", "%s")); } } } else { $this->output->error("That's all we could find."); } }
public static function getIp() { $co = new Curl(self::$ifconfigIp); $co->setopt(CURLOPT_RETURNTRANSFER, true); $ip = $co->exec(); return $ip; }
public static function getProblemInfo($problemId) { // 新建一个curl $ch = new Curl(); $url = 'http://acm.hdu.edu.cn/showproblem.php?pid=' . $problemId; $html = $ch->get($url); if (empty($html) || $ch->error()) { $ch->close(); return false; } $ch->close(); $problemInfo = array(); $matches = array(); // 获取标题 preg_match('/<td align=center><h1 style=\'color:#1A5CC8\'>(.*)<\\/h1>/sU', $html, $matches); $problemInfo['title'] = ''; if (!empty($matches[1])) { $problemInfo['title'] = trim($matches[1]); $problemInfo['title'] = iconv('GBK', 'UTF-8', $problemInfo['title']); } // 获取来源 preg_match('/>Source.*<a.*\\/search.php.*>(.*)<\\/a>/sU', $html, $matches); $problemInfo['source'] = ''; if (!empty($matches[1])) { $problemInfo['source'] = trim($matches[1]); $problemInfo['source'] = iconv('GBK', 'UTF-8', $problemInfo['source']); } $problemInfo['problem_id'] = $problemId; $problemInfo['problem_code'] = $problemId; return $problemInfo; }
/** * @param Curl $ch * * @throws \Exception */ private function safeRemove(Curl $ch) { $return = curl_multi_remove_handle($this->multiHandle, $ch->getHandle()); if ($return !== 0) { throw new \Exception('Error occurred: ' . $return); } }
public function expressTakeUp($userID, $expressID) { $curl = new Curl(); $data = array("expressID" => $expressID, "userID" => $userID); $curl->post($this->url['expressTake'], $data); return $curl->response; }
public static function getProblemInfo($problemId) { // 新建一个curl $ch = new Curl(); $url = 'http://poj.org/problem?id=' . $problemId; $html = $ch->get($url); if (empty($html) || $ch->error()) { $ch->close(); return false; } $ch->close(); $problemInfo = array(); $matches = array(); // 获取标题 preg_match('/<div class="ptt" lang="en-US">(.*)<\\/div>/sU', $html, $matches); $problemInfo['title'] = ''; if (!empty($matches[1])) { $problemInfo['title'] = trim($matches[1]); } // 获取来源 preg_match('/<a href="searchproblem\\?field=source.*>(.*)<\\/a>/sU', $html, $matches); $problemInfo['source'] = ''; if (!empty($matches[1])) { $problemInfo['source'] = trim($matches[1]); } $problemInfo['problem_id'] = $problemId; $problemInfo['problem_code'] = $problemId; return $problemInfo; }
function testValidatedSsl() { $curl = new Curl(); $curl->setValidateSsl(true); $response = $curl->get('https://www.facebook.com/'); $this->assertEquals(200, $response->headers['Status-Code']); }
public function doRequest($url) { $url = Util::sanitizeURL($url); if (false && !Util::validateURL($url)) { $response = array('errorCode' => 1008, 'errorMsg' => _('Invalid url') . $url); $this->sendJSON($response); } $curl = new Curl($url); // real url after all redirects. $url = $curl->getRealUrl(); $qid = Util::generateQid($url); $outfile = Config::$outputDir . "/{$qid}.png"; if (!file_exists($outfile)) { if (!$curl->isReachable()) { $response = array('errorCode' => 1009, 'errorMsg' => _('Site is unreachable please try again later')); $this->sendJSON($response); } } if ($this->queueRequest($qid, $url)) { Log::info("Queue {$url}"); $response = array('items' => array(array('title' => $curl->getTitle(), 'qid' => $qid))); $this->sendJSON($response); } else { $response = array('errorCode' => 1009, 'errorMsg' => sprintf(_('Error: %s'), $this->db->error)); $this->sendJSON($response); } }
private function sendRequest($url, $method, $headers = null, $body = null) { $this->curl->headers = array(); $this->curl->options = array(); $this->curl->options['CURLOPT_SSL_VERIFYHOST'] = false; $this->curl->options['CURLOPT_SSL_VERIFYPEER'] = false; $this->curl->headers['Accept'] = VMware_VCloud_SDK_Constants::VCLOUD_ACCEPT_HEADER . ';' . 'version=' . $this->apiVersion; if ($this->authToken) { $this->curl->headers[VMware_VCloud_SDK_Constants::VCLOUD_AUTH_TOKEN] = $this->authToken; } else { $this->curl->options['CURLOPT_USERPWD'] = $this->username . ':' . $this->password; } if ($headers) { $h = $this->curl->headers; $h = array_merge($h, $headers); $this->curl->headers = $h; } $response = $this->curl->{$method}($url, $body); // var_dump($url,$method,$this->curl,$body); if (!is_object($response) && $this->curl->error()) { // var_dump($url,$method,$headers,$body,$this->curl); throw new Exception($this->curl->error()); } if (!$this->authToken) { $this->authToken = $response->headers[VMware_VCloud_SDK_Constants::VCLOUD_AUTH_TOKEN]; } return $response; }
function initialize() { if (!$this->fetched) { $config =& get_config(); $assetUrl = $config['asset_service'] . $this->node['AssetID']; $curl = new Curl(); $curl->create($assetUrl); $curl->option(CURLOPT_HEADER, true); $curl->option(CURLOPT_NOBODY, true); $response = $curl->execute(); if ($response) { $headers = http_parse_headers($response); $this->size = $headers['Content-Length']; $this->contentType = $headers['Content-Type']; if (isset($headers['ETag'])) { $this->etag = $headers['ETag']; } else { if (isset($headers['Etag'])) { $this->etag = $headers['Etag']; } else { $this->etag = ''; } } } else { log_message('error', "InventoryFile: Failed to fetch headers from {$assetUrl}"); } $this->fetched = true; } }
function test_error() { assert_throws('CurlException', function () { $curl = new Curl(); $curl->get('diaewkaksdljf-invalid-url-dot-com.com'); }); }
public function get($url_mixed, $data = array()) { if (is_array($url_mixed)) { $curl_multi = curl_multi_init(); $this->_multi_parent = true; $this->curls = array(); foreach ($url_mixed as $url) { $curl = new Curl(); $curl->_multi_child = true; $curl->setOpt(CURLOPT_URL, $this->_buildURL($url, $data), $curl->curl); $curl->setOpt(CURLOPT_HTTPGET, true); $this->_call($this->_before_send, $curl); $this->curls[] = $curl; $curlm_error_code = curl_multi_add_handle($curl_multi, $curl->curl); if (!($curlm_error_code === CURLM_OK)) { //throw new \ErrorException('cURL multi add handle error: ' .curl_multi_strerror($curlm_error_code)); } } foreach ($this->curls as $ch) { foreach ($this->_options as $key => $value) { $ch->setOpt($key, $value); } } do { $status = curl_multi_exec($curl_multi, $active); } while ($status === CURLM_CALL_MULTI_PERFORM || $active); foreach ($this->curls as $ch) { $this->exec($ch); } } else { $this->setopt(CURLOPT_URL, $this->_buildURL($url_mixed, $data)); $this->setopt(CURLOPT_HTTPGET, true); return $this->exec(); } }
/** * Вызов метода ApiVK * @param $sMethod * @param $mParams * @return bool|mixed */ private function CallMethod($sMethod, $mParams) { if (is_array($mParams)) { if (!isset($mParams['access_token'])) { if (!$this->sAccessToken) { return false; } $mParams['access_token'] = $this->sAccessToken; } $oCurl = new Curl(); $oCurl->SetUrl('https://api.vk.com/method/' . $sMethod); $oCurl->SetPostfields($mParams); $sResult = $oCurl->GetResponseBody(true); } else { $sParams = $mParams; if (!strpos($mParams, 'access_token')) { if (!$this->sAccessToken) { return false; } $sParams = $mParams . '&access_token=' . $this->sAccessToken; } $oCurl = new Curl(); $oCurl->SetUrl('https://api.vk.com/method/' . $sMethod . '?' . $sParams); $sResult = $oCurl->GetResponseBody(true); } if ($sResult === false) { throw new Exception($oCurl->Error()); } $oCurl->close(); return json_decode($sResult); }
function fAlamat($lat = 0, $lon = 0) { include_once './curl.class.php'; $curl = new Curl(); // $a = $curl->post('http://ws.geonames.org/extendedFindNearby?lng='.$lon.'&lat='.$lat); $a = $curl->post('http://maps.google.com/maps/geo?q=' . $lat . ',' . $lon . '&gl=id&output=xml'); /* $r["negara"] = $a["geonames"]["geoname"][2]["name"]; $r["propinsi"] = $a["geonames"]["geoname"][3]["name"]; $r["kota"] = $a["geonames"]["geoname"][4]["name"]; */ $r["koordinat"] = $a['kml']['Response']['name']; $r["alamat"] = $a['kml']['Response']['Placemark']['address']; $r["negara"] = $a['kml']['Response']['Placemark']['AddressDetails']['Country']['CountryName']; $r["propinsi"] = $a['kml']['Response']['Placemark']['AddressDetails']['Country']['AdministrativeArea']['AdministrativeAreaName']; //if (empty($a['kml']['Response']['Placemark']['AddressDetails']['Country']['AdministrativeArea']['SubAdministrativeArea']['SubAdministrativeAreaName'])){ $r["kota"] = $a['kml']['Response']['Placemark']['AddressDetails']['Country']['AdministrativeArea']['SubAdministrativeArea']['Locality']['LocalityName']; $r["daerah"] = $a['kml']['Response']['Placemark']['AddressDetails']['Country']['AdministrativeArea']['SubAdministrativeArea']['Locality']['DependentLocalityName']; $r["jalan"] = $a['kml']['Response']['Placemark']['AddressDetails']['Country']['AdministrativeArea']['SubAdministrativeArea']['Locality']['Thoroughfare']['ThoroughfareName']; //} else { // $r["kota"] = $a['kml']['Response']['Placemark']['AddressDetails']['Country']['AdministrativeArea']['SubAdministrativeArea']['Locality']['LocalityName'] . "," . $a['kml']['Response']['Placemark'][0]['AddressDetails']['Country']['AdministrativeArea']['SubAdministrativeArea']['SubAdministrativeAreaName']; // $r["daerah"] = $a['kml']['Response']['Placemark']['AddressDetails']['Country']['AdministrativeArea']['SubAdministrativeArea']['Locality']['DependentLocality']['DependentLocalityName']; // $r["jalan"] = $a['kml']['Response']['Placemark']['AddressDetails']['Country']['AdministrativeArea']['SubAdministrativeArea']['Locality']['DependentLocality']['Thoroughfare']['ThoroughfareName']; //} return $r; }
function webservice_post($url, $params, $jsonRequest = FALSE) { // Parse the RequestMethod out of the request for debugging purposes if (isset($params['RequestMethod'])) { $requestMethod = $params['RequestMethod']; } else { $requestMethod = ''; } if (empty($url)) { log_message('error', "Canceling {$requestMethod} POST to an empty URL"); return array('Message' => 'Web service URL is not configured'); } if ($jsonRequest) { $params = json_encode($params); } // POST our query and fetch the response $curl = new Curl(); $response = $curl->simple_post($url, $params); //log_message('debug', sprintf('Response received from %s POST to %s: %s', $requestMethod, $url, $response)); // JSON decode the response $response = json_decode($response, TRUE); if (!isset($response)) { $response = array('Message' => 'Invalid or missing response'); } return $response; }
/** * @param string $response * @dataProvider readDataProvider */ public function testRead($response) { self::$curlExectClosure = function () use($response) { return $response; }; $this->assertEquals(file_get_contents(__DIR__ . '/_files/curl_response_expected.txt'), $this->model->read()); }
public function execute() { $curl_options = array(CURLOPT_RETURNTRANSFER => TRUE, CURLOPT_URL => $this->generate_url()); $curl = new Curl($curl_options); $res = $curl->execute(); return json_decode($res); }
function post($url, $data) { $curlObj = new Curl(); $curlObj->setUrl($url); $curlObj->setPost($data); return $curlObj->run(); }
public function process_user($username, $password, $facility_code) { $curl = new Curl(); $response = array(); //Get Supplier $supplier = $this->get_supplier($facility_code); if ($supplier == "kemsa") { //Use nascop url $url = $this->default_url; $post = array("email" => $username, "password" => $password); $url = $this->default_url . 'sync/user'; $curl->post($url, $post); } else { //Use escm url $curl->setBasicAuthentication($username, $password); $curl->setOpt(CURLOPT_RETURNTRANSFER, TRUE); $url = $this->default_url . 'user/' . $username; $curl->get($url); } //Handle Response if ($curl->error) { $response['error'] = TRUE; $response['content'] = array($curl->error_code); } else { $response['error'] = FALSE; $response['content'] = json_decode($curl->response, TRUE); } return json_encode($response); }
public function getToken() { $username = self::CONFIG_USERNAME; $password = self::CONFIG_PASSWORD; $time = time(); $hash = md5("{$username}@{$password}@{$time}"); $auth = "{$username}@{$time}@{$hash}"; $ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : ''; $url = 'http://axe.mappy.com/1v1/token/generate.aspx?' . 'auth=' . urlencode($auth) . '&' . 'ip=' . urldecode($ip); /** $remote = @fopen($url, 'rb'); if ( false === $remote ) return false; $token = ''; while ( !( feof($remote) ) ) $token .= fread($remote, 8192); fclose($remote); */ $curl = new Curl($url); $curl->request(); $resp = $curl->response(); $curl->disconnect(); return $resp['body']; }
public function postUpdateCard() { // Add Curl library require_once app_path() . "/libraries/Curl/Curl.php"; // Get Product $product = Product::where('code', Input::get('code'))->first(); // Get Expiry month and year $expiry = explode(' / ', Input::get('ccExpire')); // Put all values in session Session::flash('ccNum', Input::get('ccNum')); Session::flash('ccExpire', Input::get('ccExpire')); Session::flash('ccCVC', Input::get('ccCVC')); $data = array('email' => Input::get('email'), 'code' => Input::get('code'), 'number' => Input::get('ccNum'), 'exp_month' => !empty($expiry[0]) ? $expiry[0] : NULL, 'exp_year' => !empty($expiry[1]) ? $expiry[1] : NULL, 'cvc' => Input::get('ccCVC')); $data['key'] = DKHelpers::GenerateHash($data, $product->api_key); $url = url() . "/api/v1/update-card"; // Post data to IPN $curl = new Curl(); $response = $curl->simple_post($url, $data, array(CURLOPT_BUFFERSIZE => 10)); $response = json_decode($response); if (empty($response->error)) { $success = "Your card (**** **** **** {$response->last4}) has been updated successfully."; return Redirect::back()->with('success', $success); } else { return Redirect::back()->with('error', $response->error); } }
public function shelves($action, $parameters, $curl = null) { if (is_null($curl)) { $curl = new Curl(); } $response = Response::buildFromCurlResponse($curl->fetchInfo()); return $response; }
function test_mock() { Curl::initMock(); Curl::mockResult("helloworld"); $curl = new Curl(); $res = $curl->exec(); $this->assertEquals($res, "helloworld"); }
/** * Send Http request and return response * * For now we need only get requests * * @param $method * @param $path * @param $params * @throws SurvariumException * @return Response */ private function sendHttpRequest($method, $path, $params) { $this->request = new Request($method, $path, $params, $this->consumer, $this->signatureProcessor); $this->response = new Response(); $transporter = new Curl($this->request, $this->response); $transporter->send(); return $this->getResponse(); }
/** * @param string $url * @return Curl */ public function create($url) { $curl = new Curl($url); foreach ($this->options as $option) { $curl->addOption($option[0], $option[1]); } return $curl; }
private function postRequest($url, $fields) { $curl = new Curl(); $curl->addHeader('Authorization: Bearer ', $fields['code']); $curl->addOption(CURLOPT_RETURNTRANSFER, true); $request = $curl->post($url, $fields); return $request; }
/** * static proxy create */ public static function create($url) { $curl = new Curl($url); if ($url) { $curl->setUrl($url); } return $curl; }
function __scrapeTVShow($url, $offset=0, $count=12) { if ($this->stats) { $this->stats->start('icefilms.info:tv', "$url"); } $curl = new Curl(); $html = $curl->get($url); if (!$html) { return false; } $dom = new DOMDocument(); @$dom->loadHTML($html); // Suppress warnings - odds are there are PLENTY! $xpath = new DOMXPath($dom); $nodes = $xpath->query("//h1"); $seasons = array(); foreach ($nodes as $header) { // Scrape IMDB info (name, id, metainfo) $name = $header->nodeValue; # and starts-with(@href, 'http://www.imdb.com/title/tt')", $header); $imdblinks = $xpath->query(".//a[@class='iframe' and starts-with(@href, 'http://www.imdb.com/title/tt')]", $header); $metaInfo = array(); foreach ($imdblinks as $imdblink) { $imdblink = $imdblink->attributes->getNamedItem('href')->nodeValue; if (preg_match('|/title/(tt[0-9]+)|', $imdblink, $matches)) { $id = $matches[1]; $metaInfo = $this->metahandler->getMetaInfo($id); $metaInfo['id'] = $id; } break; } $metaInfo['name'] = $name; // Scrape seasons $nodes = $xpath->query("//span[@class='list']/h4|//span[@class='list']/a[@href and starts-with(@href, '/ip.php')]"); $season = FALSE; foreach ($nodes as $node) { // Should be both h4 and a nodes. if ($node->nodeName == 'h4') { if ($season) { $seasons[] = $season; } $season = array('name' => $node->nodeValue, 'episodes' => array()); } else if ($node->nodeName == 'a' && $season) { $episode = array('name' => $node->nodeValue, 'url' => $node->attributes->getNamedItem('href')->nodeValue); $season['episodes'][] = $episode; } } if ($season) { $seasons[] = $season; } break; } $data = array('show' => $metaInfo, 'seasons' => $seasons, 'count' => sizeof($nodes)); $this->pagecache->cacheMovies($url, 0, 0, $data); if ($this->stats) { $this->stats->end('icefilms.info:tv'); } return $data; }
/** * Returns a MetaInfo object. **/ function getMetaInfo($id) { if ($this->stats) { $this->stats->start('tmdb', "getMetaInfo, $id"); } $curl = new Curl(); // TODSELECT s1.name, ROUND(s1.microtime/1000) 'sec', COUNT(*), MIN(s2.microtime), AVG(s2.microtime), MAX(s2.microtime) FROM `icerss_stats` s1, `icerss_stats` s2 WHERE s1.name = s2.name GROUP BY s1.name, secO: protect against injections? $jsonData = $curl->get('http://api.themoviedb.org/2.1/Movie.imdbLookup/en/json/' . $this->api_key . '/' . $id); $data = json_decode($jsonData, true); if (!$data) { return False; } $data = $data[0]; $genres = array(); if (array_key_exists('genres', $data)) { foreach ($data['genres'] as $genre) { $genres[] = $genre['name']; } } // [0.0 - 10.0] -> 0-5 $rating = floatval($data['rating']) / 2; $writers = preg_split(COMMA, $data->Writer); $actors = preg_split(COMMA, $data->Actors); $plot = array('en' => $data['overview']); $poster = 'N/A'; if (array_key_exists('posters', $data)) { foreach ($data['posters'] as $img) { if ($img['image']['size'] == 'cover') { $poster = $img['image']['url']; break; } } } $runtime = intval($data['runtime']); // Minutes $runtime = intval(floor($runtime / 60)) . ' hr ' . ($runtime % 60) . ' mins'; $year = $data['released']; if (strlen($year) > 4) { $year = substr($year, 0, 4); } $tmdb = $data['id']; // TODO: Fetch director, writers + actors if ($this->stats) { $this->stats->end('tmdb'); } return array( 'id' => $id, 'title' => $data['name'], 'year' => $year, 'genres' => $genres, 'plot' => $plot, 'poster' => $poster, 'runtime' => $runtime, 'rating' => $rating, 'director' => '', 'writers' => array(), 'actors' => array() ); }