本文整理汇总了PHP中curl::setHeader方法的典型用法代码示例。如果您正苦于以下问题:PHP curl::setHeader方法的具体用法?PHP curl::setHeader怎么用?PHP curl::setHeader使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类curl
的用法示例。
在下文中一共展示了curl::setHeader方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: __construct
/**
* Constructor.
*
* @throws \moodle_exception
* @return void
*/
public function __construct()
{
if (!($this->config = get_config('search_solr'))) {
throw new \moodle_exception('missingconfig', 'search_solr');
}
if (empty($this->config->server_hostname) || empty($this->config->indexname)) {
throw new \moodle_exception('missingconfig', 'search_solr');
}
$this->engine = new engine();
$this->curl = $this->engine->get_curl_object();
// HTTP headers.
$this->curl->setHeader('Content-type: application/json');
}
示例2: setup_oauth_http_header
public function setup_oauth_http_header($params)
{
$total = array();
ksort($params);
foreach ($params as $k => $v) {
$total[] = rawurlencode($k) . '="' . rawurlencode($v) . '"';
}
$str = implode(', ', $total);
$str = 'Authorization: OAuth ' . $str;
$this->http->setHeader('Expect:');
$this->http->setHeader($str);
}
示例3: __construct
/**
* Constructor.
*
* @throws \moodle_exception
* @return void
*/
public function __construct()
{
if (!($this->config = get_config('search_solr'))) {
throw new \moodle_exception('missingconfig', 'search_solr');
}
if (empty($this->config->server_hostname) || empty($this->config->indexname)) {
throw new \moodle_exception('missingconfig', 'search_solr');
}
$this->curl = new \curl();
// HTTP headers.
$this->curl->setHeader('Content-type: application/json');
if (!empty($this->config->server_username) && !empty($this->config->server_password)) {
$authorization = $this->config->server_username . ':' . $this->config->server_password;
$this->curl->setHeader('Authorization', 'Basic ' . base64_encode($authorization));
}
$this->url = rtrim($this->config->server_hostname, '/');
if (!empty($this->config->server_port)) {
$this->url .= ':' . $this->config->server_port;
}
$this->url .= '/solr/' . $this->config->indexname;
$this->schemaurl = $this->url . '/schema';
}
示例4: send_message
/**
* Processes the message and sends a notification via airnotifier
*
* @param stdClass $eventdata the event data submitted by the message sender plus $eventdata->savedmessageid
* @return true if ok, false if error
*/
public function send_message($eventdata)
{
global $CFG;
require_once $CFG->libdir . '/filelib.php';
if (!empty($CFG->noemailever)) {
// Hidden setting for development sites, set in config.php if needed.
debugging('$CFG->noemailever active, no airnotifier message sent.', DEBUG_MINIMAL);
return true;
}
// Skip any messaging suspended and deleted users.
if ($eventdata->userto->auth === 'nologin' or $eventdata->userto->suspended or $eventdata->userto->deleted) {
return true;
}
// Site id, to map with Moodle Mobile stored sites.
$siteid = md5($CFG->wwwroot . $eventdata->userto->username);
// Airnotifier can handle custom requests using processors (that are Airnotifier plugins).
// In the extra parameter we indicate which processor to use and also additional data to be handled by the processor.
// Here we clone the eventdata object because will be deleting/adding attributes.
$extra = clone $eventdata;
// Delete attributes that may content private information.
if (!empty($eventdata->userfrom)) {
$extra->userfromid = $eventdata->userfrom->id;
$extra->userfromfullname = fullname($eventdata->userfrom);
unset($extra->userfrom);
}
$extra->usertoid = $eventdata->userto->id;
unset($extra->userto);
$extra->processor = 'moodle';
$extra->site = $siteid;
$extra->date = !empty($eventdata->timecreated) ? $eventdata->timecreated : time();
$extra->notification = !empty($eventdata->notification) ? 1 : 0;
// We are sending to message to all devices.
$airnotifiermanager = new message_airnotifier_manager();
$devicetokens = $airnotifiermanager->get_user_devices($CFG->airnotifiermobileappname, $eventdata->userto->id);
foreach ($devicetokens as $devicetoken) {
if (!$devicetoken->enable) {
continue;
}
// Sending the message to the device.
$serverurl = $CFG->airnotifierurl . ':' . $CFG->airnotifierport . '/api/v2/push/';
$header = array('Accept: application/json', 'X-AN-APP-NAME: ' . $CFG->airnotifierappname, 'X-AN-APP-KEY: ' . $CFG->airnotifieraccesskey);
$curl = new curl();
$curl->setHeader($header);
$params = array('device' => $devicetoken->platform, 'token' => $devicetoken->pushid, 'extra' => $extra);
// JSON POST raw body request.
$resp = $curl->post($serverurl, json_encode($params));
}
return true;
}
示例5: post
public function post()
{
global $CFG;
$success = false;
if (!empty($CFG->enable_user_sync_post)) {
require_once dirname(__FILE__) . '/lib/curl.php';
$curl = new curl();
$curl->setHeader('x-access-token: ' . $CFG->user_sync_post_token);
$parameters = array('starttime' => $this->starttime * 1000, 'endtime' => $this->endtime * 1000, 'status' => $this->status, 'message' => $this->postmessage . "\n" . ($this->log ? $this->subject . "\n" . $this->log : ''));
$result = $curl->post("http://mcp.srv.ualberta.ca/user/sync/send", $parameters);
if ($curl->error) {
echo 'curl error! ' . var_export($curl->info, true);
echo 'POST result:' . $result;
$success = false;
} else {
$success = true;
}
}
return $success;
}
示例6: sendOAuthBodyPOST
function sendOAuthBodyPOST($method, $endpoint, $oauth_consumer_key, $oauth_consumer_secret, $content_type, $body)
{
$hash = base64_encode(sha1($body, TRUE));
$parms = array('oauth_body_hash' => $hash);
$test_token = '';
$hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
$test_consumer = new OAuthConsumer($oauth_consumer_key, $oauth_consumer_secret, NULL);
$acc_req = OAuthRequest::from_consumer_and_token($test_consumer, $test_token, $method, $endpoint, $parms);
$acc_req->sign_request($hmac_method, $test_consumer, $test_token);
// Pass this back up "out of band" for debugging
global $LastOAuthBodyBaseString;
$LastOAuthBodyBaseString = $acc_req->get_signature_base_string();
// echo($LastOAuthBodyBaseString."\m");
$headers = array();
$headers[] = $acc_req->to_header();
$headers[] = "Content-type: " . $content_type;
$curl = new \curl();
$curl->setHeader($headers);
$response = $curl->post($endpoint, $body);
return $response;
}
示例7: curl_request
public function curl_request($action, $collection = null)
{
$curl = new curl();
switch ($action) {
case 'user':
$url = $this->backpack . "/displayer/convert/email";
$param = array('email' => $this->email);
break;
case 'groups':
$url = $this->backpack . '/displayer/' . $this->backpackuid . '/groups.json';
break;
case 'badges':
$url = $this->backpack . '/displayer/' . $this->backpackuid . '/group/' . $collection . '.json';
break;
}
$curl->setHeader(array('Accept: application/json', 'Expect:'));
$options = array('FRESH_CONNECT' => true, 'RETURNTRANSFER' => true, 'FORBID_REUSE' => true, 'HEADER' => 0, 'CONNECTTIMEOUT' => 3, 'CURLOPT_POSTREDIR' => 3);
if ($action == 'user') {
$out = $curl->post($url, $param, $options);
} else {
$out = $curl->get($url, array(), $options);
}
return json_decode($out);
}
示例8: download_file_content
/**
* Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
* Due to security concerns only downloads from http(s) sources are supported.
*
* @category files
* @param string $url file url starting with http(s)://
* @param array $headers http headers, null if none. If set, should be an
* associative array of header name => value pairs.
* @param array $postdata array means use POST request with given parameters
* @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
* (if false, just returns content)
* @param int $timeout timeout for complete download process including all file transfer
* (default 5 minutes)
* @param int $connecttimeout timeout for connection to server; this is the timeout that
* usually happens if the remote server is completely down (default 20 seconds);
* may not work when using proxy
* @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
* Only use this when already in a trusted location.
* @param string $tofile store the downloaded content to file instead of returning it.
* @param bool $calctimeout false by default, true enables an extra head request to try and determine
* filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
* @return stdClass|string|bool stdClass object if $fullresponse is true, false if request failed, true
* if file downloaded into $tofile successfully or the file content as a string.
*/
function download_file_content($url, $headers = null, $postdata = null, $fullresponse = false, $timeout = 300, $connecttimeout = 20, $skipcertverify = false, $tofile = NULL, $calctimeout = false)
{
global $CFG;
// Only http and https links supported.
if (!preg_match('|^https?://|i', $url)) {
if ($fullresponse) {
$response = new stdClass();
$response->status = 0;
$response->headers = array();
$response->response_code = 'Invalid protocol specified in url';
$response->results = '';
$response->error = 'Invalid protocol specified in url';
return $response;
} else {
return false;
}
}
$options = array();
$headers2 = array();
if (is_array($headers)) {
foreach ($headers as $key => $value) {
if (is_numeric($key)) {
$headers2[] = $value;
} else {
$headers2[] = "{$key}: {$value}";
}
}
}
if ($skipcertverify) {
$options['CURLOPT_SSL_VERIFYPEER'] = false;
} else {
$options['CURLOPT_SSL_VERIFYPEER'] = true;
}
$options['CURLOPT_CONNECTTIMEOUT'] = $connecttimeout;
$options['CURLOPT_FOLLOWLOCATION'] = 1;
$options['CURLOPT_MAXREDIRS'] = 5;
// Use POST if requested.
if (is_array($postdata)) {
$postdata = format_postdata_for_curlcall($postdata);
} else {
if (empty($postdata)) {
$postdata = null;
}
}
// Optionally attempt to get more correct timeout by fetching the file size.
if (!isset($CFG->curltimeoutkbitrate)) {
// Use very slow rate of 56kbps as a timeout speed when not set.
$bitrate = 56;
} else {
$bitrate = $CFG->curltimeoutkbitrate;
}
if ($calctimeout and !isset($postdata)) {
$curl = new curl();
$curl->setHeader($headers2);
$curl->head($url, $postdata, $options);
$info = $curl->get_info();
$error_no = $curl->get_errno();
if (!$error_no && $info['download_content_length'] > 0) {
// No curl errors - adjust for large files only - take max timeout.
$timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024)));
}
}
$curl = new curl();
$curl->setHeader($headers2);
$options['CURLOPT_RETURNTRANSFER'] = true;
$options['CURLOPT_NOBODY'] = false;
$options['CURLOPT_TIMEOUT'] = $timeout;
if ($tofile) {
$fh = fopen($tofile, 'w');
if (!$fh) {
if ($fullresponse) {
$response = new stdClass();
$response->status = 0;
$response->headers = array();
$response->response_code = 'Can not write to file';
$response->results = false;
//.........这里部分代码省略.........
示例9: test_curl_post
public function test_curl_post()
{
$testurl = $this->getExternalTestFileUrl('/test_post.php');
// Test post request.
$curl = new curl();
$contents = $curl->post($testurl, 'data=moodletest');
$response = $curl->getResponse();
$this->assertSame('200 OK', reset($response));
$this->assertSame(0, $curl->get_errno());
$this->assertSame('OK', $contents);
// Test 100 requests.
$curl = new curl();
$curl->setHeader('Expect: 100-continue');
$contents = $curl->post($testurl, 'data=moodletest');
$response = $curl->getResponse();
$this->assertSame('200 OK', reset($response));
$this->assertSame(0, $curl->get_errno());
$this->assertSame('OK', $contents);
}
示例10: makeRequest
/**
* Send an API request to Google.
*
* This method overwrite the parent one so that the Google SDK will use our class
* curl to proceed with the requests. This allows us to have control over the
* proxy parameters and other stuffs.
*
* Note that the caching support of the Google SDK has been removed from this function.
*
* @param Google_HttpRequest $request the http request to be executed
* @return Google_HttpRequest http request with the response http code, response
* headers and response body filled in
* @throws Google_IOException on curl or IO error
*/
public function makeRequest(Google_HttpRequest $request)
{
if (array_key_exists($request->getRequestMethod(), self::$ENTITY_HTTP_METHODS)) {
$request = $this->processEntityRequest($request);
}
$curl = new curl();
$curl->setopt($this->curlParams);
$curl->setopt(array('CURLOPT_URL' => $request->getUrl()));
$requestHeaders = $request->getRequestHeaders();
if ($requestHeaders && is_array($requestHeaders)) {
$parsed = array();
foreach ($requestHeaders as $k => $v) {
$parsed[] = "{$k}: {$v}";
}
$curl->setHeader($parsed);
}
$curl->setopt(array('CURLOPT_CUSTOMREQUEST' => $request->getRequestMethod(), 'CURLOPT_USERAGENT' => $request->getUserAgent()));
$respdata = $this->do_request($curl, $request);
// Retry if certificates are missing.
if ($curl->get_errno() == CURLE_SSL_CACERT) {
error_log('SSL certificate problem, verify that the CA cert is OK.' . ' Retrying with the CA cert bundle from google-api-php-client.');
$curl->setopt(array('CURLOPT_CAINFO' => dirname(__FILE__) . '/io/cacerts.pem'));
$respdata = $this->do_request($curl, $request);
}
$infos = $curl->get_info();
$respheadersize = $infos['header_size'];
$resphttpcode = (int) $infos['http_code'];
$curlerrornum = $curl->get_errno();
$curlerror = $curl->error;
if ($curlerrornum != CURLE_OK) {
throw new Google_IOException("HTTP Error: ({$resphttpcode}) {$curlerror}");
}
// Parse out the raw response into usable bits.
list($responseHeaders, $responseBody) = self::parseHttpResponse($respdata, $respheadersize);
// Fill in the apiHttpRequest with the response values.
$request->setResponseHttpCode($resphttpcode);
$request->setResponseHeaders($responseHeaders);
$request->setResponseBody($responseBody);
return $request;
}
示例11: block_intuitel_submit_to_intuitel
/**
*
* @param string $xml
* @param array $aditional_params
* @return mixed
*/
function block_intuitel_submit_to_intuitel($xml, $aditional_params = array())
{
$intuitelEndPoint = block_intuitel_get_service_endpoint();
//debugging('connecting to: '.$intuitelEndPoint,DEBUG_DEVELOPER);
$rest_client = new curl();
$rest_client->setHeader(array('Content-Type: application/xml'));
$return = $rest_client->post($intuitelEndPoint, $xml, ['CURLOPT_POST' => true, 'CURLOPT_RETURNTRANSFER' => true, 'CURLOPT_TIMEOUT' => 120]);
$info = $rest_client->info;
if ($info['http_code'] != 200) {
throw new ProtocolErrorException('Intuitel Service did not respond correctly. Please report to the administrator. Error code:' . $info['http_code'] . ' Cause:' . $rest_client->error . ' Response:' . $return, $info['http_code']);
}
return $return;
}
示例12: array
//.........这里部分代码省略.........
$params['client_secret'] = $this->_oauth_config->auth_lenauth_mailru_client_secret;
$params['grant_type'] = $this->_settings[$authprovider]['grant_type'];
break;
//odnoklassniki.ru was wrote by school programmers at 1st class and it not used mojority. bye-bye!
/*case 'ok':
$params['client_id'] = $this->_oauth_config->ok_app_id;
$params['client_secret'] = $this->_oauth_config->ok_secret_key;
break;*/
//odnoklassniki.ru was wrote by school programmers at 1st class and it not used mojority. bye-bye!
/*case 'ok':
$params['client_id'] = $this->_oauth_config->ok_app_id;
$params['client_secret'] = $this->_oauth_config->ok_secret_key;
break;*/
default:
// if authorization provider is wrong
throw new moodle_exception('Unknown OAuth Provider', 'auth_lenauth');
}
// url for catch token value
// exception for Yahoo OAuth, because it like..
if ($code) {
$params['code'] = $authorizationcode;
}
if ($redirect_uri) {
$params['redirect_uri'] = $this->_lenauth_redirect_uri($authprovider);
}
//require cURL from Moodle core
require_once $CFG->libdir . '/filelib.php';
// requires library with cURL class
$curl = new curl();
//hack for twitter and Yahoo
if (!empty($curl_options) && is_array($curl_options)) {
$curl->setopt($curl_options);
}
$curl->resetHeader();
// clean cURL header from garbage
//Twitter and Yahoo has an own cURL headers, so let them to be!
if (!$curl_header) {
$curl->setHeader('Content-Type: application/x-www-form-urlencoded');
} else {
$curl->setHeader($curl_header);
}
// cURL REQUEST for tokens if we hasnt it in $_COOKIE
if ($this->_send_oauth_request) {
if ($this->_curl_type == 'post') {
$curl_tokens_values = $curl->post($this->_settings[$authprovider]['request_token_url'], $encode_params ? $this->_generate_query_data($params) : $params);
} else {
$curl_tokens_values = $curl->get($this->_settings[$authprovider]['request_token_url'] . '?' . ($encode_params ? $this->_generate_query_data($params) : $params));
}
}
// check for token response
if (!empty($curl_tokens_values) || !$this->_send_oauth_request) {
$token_values = array();
// parse token values
switch ($authprovider) {
case 'facebook':
if ($this->_send_oauth_request || !isset($_COOKIE[$authprovider]['access_token'])) {
parse_str($curl_tokens_values, $token_values);
$expires = $token_values['expires'];
//5183999 = 2 months
$access_token = $token_values['access_token'];
if (!empty($expires) && !empty($access_token)) {
setcookie($authprovider . '[access_token]', $access_token, time() + $expires, '/');
} else {
throw new moodle_exception('Can not get access for "access_token" or/and "expires" params after request', 'auth_lenauth');
}
} else {
示例13: http_request
private function http_request($resource, $method, $body = null)
{
$jobe = get_config('qtype_coderunner', 'jobe_host');
$apikey = get_config('qtype_coderunner', 'jobe_apikey');
$headers = array('Content-Type: application/json; charset=utf-8', 'Accept: application/json');
if (!empty($apikey)) {
$headers[] = "X-API-KEY: {$apikey}";
}
$url = "http://{$jobe}/jobe/index.php/restapi/{$resource}";
$curl = new curl();
$curl->setHeader($headers);
if ($method === self::HTTP_GET) {
if (!empty($body)) {
throw new coding_exception("Illegal HTTP GET: non-empty body");
}
$response = $curl->get($url);
} else {
if ($method === self::HTTP_POST) {
if (empty($body)) {
throw new coding_exception("Illegal HTTP POST: empty body");
}
$bodyjson = json_encode($body);
$response = $curl->post($url, $bodyjson);
} else {
throw new coding_exception('Invalid method passed to http_request');
}
}
if ($response !== FALSE) {
$returncode = $curl->info['http_code'];
$responsebody = $response === '' ? '' : json_decode($response);
} else {
$returncode = -1;
$responsebody = '';
}
return array($returncode, $responsebody);
}
示例14: validate_receiver
public function validate_receiver($receiver)
{
$plagiarismsettings = $this->get_settings();
$url = URKUND_INTEGRATION_SERVICE . '/receivers' . '/' . trim($receiver);
$headers = array('Accept-Language: ' . $plagiarismsettings['urkund_lang']);
$allowedstatus = array(URKUND_STATUSCODE_PROCESSED, URKUND_STATUSCODE_NOT_FOUND, URKUND_STATUSCODE_BAD_REQUEST, URKUND_STATUSCODE_GONE);
// Use Moodle curl wrapper.
$c = new curl(array('proxy' => true));
$c->setopt(array());
$c->setopt(array('CURLOPT_RETURNTRANSFER' => 1, 'CURLOPT_HTTPAUTH' => CURLAUTH_BASIC, 'CURLOPT_USERPWD' => $plagiarismsettings['urkund_username'] . ":" . $plagiarismsettings['urkund_password']));
$c->setHeader($headers);
$response = $c->get($url);
$httpstatus = $c->info['http_code'];
if (!empty($httpstatus)) {
if (in_array($httpstatus, $allowedstatus)) {
if ($httpstatus == URKUND_STATUSCODE_PROCESSED) {
// Valid address found, return true.
return true;
} else {
return $httpstatus;
}
}
}
return false;
}
示例15: send_message
/**
* Processes the message and sends a notification via airnotifier
*
* @param stdClass $eventdata the event data submitted by the message sender plus $eventdata->savedmessageid
* @return true if ok, false if error
*/
public function send_message($eventdata)
{
global $CFG;
if (!empty($CFG->noemailever)) {
// Hidden setting for development sites, set in config.php if needed.
debugging('$CFG->noemailever active, no airnotifier message sent.', DEBUG_MINIMAL);
return true;
}
// Skip any messaging suspended and deleted users.
if ($eventdata->userto->auth === 'nologin' or $eventdata->userto->suspended or $eventdata->userto->deleted) {
return true;
}
// Site id, to map with Moodle Mobile stored sites.
$siteid = md5($CFG->wwwroot . $eventdata->userto->username);
// Mandatory notification data that need to be sent in the payload. They have variable length.
// We need to take them in consideration to calculate the maximum message size.
$notificationdata = array("site" => $siteid, "type" => $eventdata->component . '_' . $eventdata->name, "device" => "xxxxxxxxxx", "notif" => "x", "userfrom" => !empty($eventdata->userfrom) ? fullname($eventdata->userfrom) : '');
// Calculate the size of the message knowing Apple payload must be lower than 256 bytes.
// Airnotifier using few bytes of the payload, we must limit our message to even less characters.
$maxmsgsize = 205 - core_text::strlen(json_encode($notificationdata));
$message = s($eventdata->smallmessage);
// If the message size is too big make it shorter.
if (core_text::strlen($message) >= $maxmsgsize) {
// Cut the message to the maximum possible size. -4 for the the ending 3 dots (...).
$message = core_text::substr($message, 0, $maxmsgsize - 4);
// We need to check when the message is "escaped" then the message is not too long.
$encodedmsgsize = core_text::strlen(json_encode($message));
if ($encodedmsgsize > $maxmsgsize) {
$totalescapedchar = $encodedmsgsize - core_text::strlen($message);
// Cut the message to the maximum possible size (taking the escaped character in account).
$message = core_text::substr($message, 0, $maxmsgsize - 4 - $totalescapedchar);
}
$message = $message . '...';
}
// We are sending to message to all devices.
$airnotifiermanager = new message_airnotifier_manager();
$devicetokens = $airnotifiermanager->get_user_devices($CFG->airnotifiermobileappname, $eventdata->userto->id);
foreach ($devicetokens as $devicetoken) {
if (!$devicetoken->enable) {
continue;
}
// Sending the message to the device.
$serverurl = $CFG->airnotifierurl . ':' . $CFG->airnotifierport . '/notification/';
$header = array('Accept: application/json', 'X-AN-APP-NAME: ' . $CFG->airnotifierappname, 'X-AN-APP-KEY: ' . $CFG->airnotifieraccesskey);
$curl = new curl();
$curl->setHeader($header);
$params = array('alert' => $message, 'date' => !empty($eventdata->timecreated) ? $eventdata->timecreated : time(), 'site' => $siteid, 'type' => $eventdata->component . '_' . $eventdata->name, 'userfrom' => !empty($eventdata->userfrom) ? fullname($eventdata->userfrom) : '', 'device' => $devicetoken->platform, 'notif' => !empty($eventdata->notification) ? '1' : '0', 'token' => $devicetoken->pushid);
$resp = $curl->post($serverurl, $params);
}
return true;
}