I have an issue with a website i'm hosting on a shared server where an 'open_basedir' is set... So therefore the credit system throws an error and won't charge the buyers credit card.
Error Message
Warning: curl_setopt() [function.curl-setopt]: CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir is set in
Code
function http_post($method, $server, $port, $url, $vars) {
$postdata = "";
foreach($vars as $key => $value) {
$postdata .= urlencode($key) . "=" . urlencode($value) . "&";
}
$postdata = substr($postdata,0,-1);
$content_length = strlen($postdata);
$headers = "POST $url HTTP/1.1\r\n".
"Accept: */*\r\n".
"Accept-Language: en-nz\r\n".
"Content-Type: application/x-www-form-urlencoded\r\n".
"Host: $server\r\n".
"Connection: Keep-Alive\r\n".
"Cache-Control: no-cache\r\n".
"Content-Length: $content_length\r\n\r\n";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $method . '://' . $server .":". $port . $url);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
$ret = curl_exec($ch);
curl_close($ch);
return $ret;
}
Is there anyway around this without having access to the root PHP.ini and having to switch hosts? Thank you.
There is no way to override the value of open_basedir in php.ini as this would somewhat defeat the purpose. An alternative is to write your own function perform the same functionality as CURLOPT_FOLLOWLOCATION would with open_basedir not set. I have used a variation of this code found from http://php.benscom.com/manual/en/function.curl-setopt.php#102121 which loops your request and does a regex match for Location: in the response headers, following as needed with a new request:
function curl_exec_follow(/*resource*/ $ch, /*int*/ &$maxredirect = null) {
$mr = $maxredirect === null ? 5 : intval($maxredirect);
if (ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off')) {
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $mr > 0);
curl_setopt($ch, CURLOPT_MAXREDIRS, $mr);
} else {
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
if ($mr > 0) {
$newurl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
$rch = curl_copy_handle($ch);
curl_setopt($rch, CURLOPT_HEADER, true);
curl_setopt($rch, CURLOPT_NOBODY, true);
curl_setopt($rch, CURLOPT_FORBID_REUSE, false);
curl_setopt($rch, CURLOPT_RETURNTRANSFER, true);
do {
curl_setopt($rch, CURLOPT_URL, $newurl);
$header = curl_exec($rch);
if (curl_errno($rch)) {
$code = 0;
} else {
$code = curl_getinfo($rch, CURLINFO_HTTP_CODE);
if ($code == 301 || $code == 302) {
preg_match('/Location:(.*?)\n/', $header, $matches);
$newurl = trim(array_pop($matches));
} else {
$code = 0;
}
}
} while ($code && --$mr);
curl_close($rch);
if (!$mr) {
if ($maxredirect === null) {
trigger_error('Too many redirects. When following redirects, libcurl hit the maximum amount.', E_USER_WARNING);
} else {
$maxredirect = 0;
}
return false;
}
curl_setopt($ch, CURLOPT_URL, $newurl);
}
}
return curl_exec($ch);
}
Related
I was using the following code to get gmail contacts and it suddenly stopped working. The same code works with another domain. The credentials are being correctly retrieved from a file. The domain has been verified for google.
Any help would be appreciated.
//setup new google client
$client = new Google_Client();
$client -> setClientid($google_client_id);
$client -> setClientSecret($google_client_secret);
$client -> setRedirectUri($google_redirect_uri);
$client -> setAccessType('online');
$client -> setScopes('https://www.google.com/m8/feeds');
$googleImportUrl = $client -> createAuthUrl();
//echo 'google import url: '.$googleImportUrl.'<br>';
function curl($url, $post = "") {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
if ($post != "") {
curl_setopt($curl, CURLOPT_POST, 5);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
}
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($curl, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
$contents = curl_exec($curl);
curl_close($curl);
if($contents === FALSE) {
die(curl_error($ch));
}
return $contents;
}
if (isset($_GET['code'])) {
$auth_code = $_GET["code"];
$_SESSION['google_code'] = $auth_code;
header('Location: ' . $google_redirect_uri);
}
if(isset($_SESSION['google_code'])) {
$auth_code = $_SESSION['google_code'];
$max_results = 10000;
$fields=array(
'code'=> urlencode($auth_code),
'client_id'=> urlencode($google_client_id),
'client_secret'=> urlencode($google_client_secret),
'redirect_uri'=> urlencode($google_redirect_uri),
'grant_type'=> urlencode('authorization_code')
);
$post = '';
foreach($fields as $key=>$value)
{
$post .= $key.'='.$value.'&';
}
$post = rtrim($post,'&');
$result = curl('https://accounts.google.com/o/oauth2/token',$post);
$response = json_decode($result);
$accesstoken = $response->access_token;
$url = 'https://www.google.com/m8/feeds/contacts/default/full?max-results='.$max_results.'&alt=json&v=3.0&oauth_token='.$accesstoken;
$xmlresponse = curl($url);
$contacts = json_decode($xmlresponse,true);
unset($_SESSION['google_code']);
}
I want users to send their videos on my YT channel via my site.
It worked last year but now Youtube requests users to be authenticated on Youtube.
If it even possible now?
Here is the code:
public function getPostParams()
{
$header = array(
"alg" => "RS256",
"typ" => "JWT"
);
$jwt = array(
"iss" => "gulliapp#appspot.gserviceaccount.com",
"scope" => "https://www.googleapis.com/auth/youtube",
"aud" => "https://accounts.google.com/o/oauth2/token",
"exp" => time() + 3600,
"iat" => time()
);
$jwt_string = JWT::encode($jwt, null, 'RS256', "52e47342c1d175e88a94e0076e7a87474013a798", $header);
$headers = array(
"Content-type: application/x-www-form-urlencoded",
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://accounts.google.com/o/oauth2/token");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_TIMEOUT, 3000);
curl_setopt($ch, CURLOPT_POST, true);
$post = "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=" . $jwt_string ;
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$res = curl_exec($ch);
$url = curl_getinfo($ch);
$token = json_decode($res);
curl_close($ch);
return $token->access_token;
}
public function saveFile($file, $name, $description, $token)
{
$client = new Google_Client();
$client->setClientId(self::$OAUTH2_CLIENT_ID);
$client->setClientSecret(self::$OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$redirect = filter_var('http://gulli.ru/videocontest/add/', FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);
$client->setAccessToken($token);
$client->setAccessType("offline");
$youtube = new Google_Service_YouTube($client);
if ($client->getAccessToken()) {
try{
$videoPath = $file['tmp_name'];
$snippet = new Google_Service_YouTube_VideoSnippet();
$snippet->setTitle("web2016");
$snippet->setDescription("web2016");
$snippet->setTags(array("tag1", "tag2"));
$snippet->setCategoryId("22");
$status = new Google_Service_YouTube_VideoStatus();
$status->privacyStatus = "private";
// Associate the snippet and status objects with a new video resource.
$video = new Google_Service_YouTube_Video();
$video->setSnippet($snippet);
$video->setStatus($status);
$chunkSizeBytes = 1 * 1024 * 1024;
$client->setDefer(true);
$insertRequest = $youtube->videos->insert("status,snippet", $video);
$media = new Google_Http_MediaFileUpload(
$client,
$insertRequest,
'video/*',
null,
true,
$chunkSizeBytes
);
$media->setFileSize(filesize($videoPath));
$status = false;
$handle = fopen($videoPath, "rb");
while (!$status && !feof($handle)) {
$chunk = fread($handle, $chunkSizeBytes);
$status = $media->nextChunk($chunk);
}
fclose($handle);
$client->setDefer(false);
} catch (Google_Service_Exception $e) {
$htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e) {
$htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
}
$_SESSION['token'] = $client->getAccessToken();
}
return false;
}
I have an app set for push notification. The Android code works fine and I receive a push notification. For Apple, the phone just vibrates and makes sound for push notifications, but I don't get a badge or anything else.
Can someone please show me where I am going wrong?
<?php
// function to send Android push notification
function send_message($deviceToken, $message){
$messageArr['message'] = "";
if($message=="")
{
$messageArr['message'] = "Test data";
}
else
{
$messageArr['message'] = $message ;
}
$registatoin_ids = $deviceToken;
return mer_send_notification($registatoin_ids, $messageArr);
}
function mer_curlPost($url, $headers, $fields) {
$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_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 mer_send_notification($registatoin_ids, $message) {
$url = 'https://android.googleapis.com/gcm/send';
$apiKey = 'mykeyishere';
echo 'Test if 4\n';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
$headers = array(
'Authorization: key=' . $apiKey,
'Content-Type: application/json'
);
$result = mer_curlPost($url, $headers, $fields);
return $result;
}
function sendNotification($dataArr, $device_token_array) {
$apns_url = NULL;
$apns_cert = NULL;
$apns_port = 2195;
$development = false;
if ($development) {
$apns_url = 'gateway.sandbox.push.apple.com';
$apns_cert = 'devcert.pem';
} else {
$apns_url = 'gateway.push.apple.com';
$apns_cert = 'prodcert.pem';
}
$stream_context = stream_context_create();
stream_context_set_option($stream_context, 'ssl', 'local_cert', $apns_cert);
stream_context_set_option($stream_context, 'ssl', 'passphrase', 'mypassphrase');
$payload = array();
$payload['aps'] = $dataArr;
$payloadJson = json_encode($payload);
$apns = #stream_socket_client('ssl://' . $apns_url . ':' . $apns_port, $error, $error_string, 2, STREAM_CLIENT_CONNECT, $stream_context);
foreach ($device_token_array as $key => $device_token) {
$apns_message = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $device_token)) . chr(0) . chr(strlen($payloadJson)) . $payloadJson;
$xxx[] = #fwrite($apns, $apns_message);
}
$yyy = #socket_close($apns);
$zzz = #fclose($apns);
$arr = array();
$arr[] = $stream_context;
$arr[] = $apns;
$arr[] = $xxx;
$arr[] = $yyy;
$arr[] = $zzz;
return $arr;
}
The notification format for iOS is different than for Android. See here for iOS format: https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ApplePushService.html#//apple_ref/doc/uid/TP40008194-CH100-SW1
Im using following ruby code to upload files to office 365
uri = URI.parse("#{site_url}/_api/v1.0/me/files/#{folder}/children/#{temp_file.original_filename}/content")
https = Net::HTTP.new(uri.host,uri.port)
https.use_ssl = true
req = Net::HTTP::Put.new(uri.path, initheader = {
'Content-Type' =>'application/octet-stream',
'Authorization' => 'Bearer ' + #current_user.o_auth_token,
'resource' => 'site_url'
})
req.set_form_data(
'file' => temp_file.read,
'Content-Type' => 'application/octet-stream'
)
JSON.parse(https.request(req).body)
The file uploaded to office 365 is corrupt. What's the issue in the code?
The following code in PHP works fine. Please note these are functions within a class and also requires creating a SharepointException class.
public function upload_file($folder_id, $filepath, $filename) {
//remove illegal characters form filename
try {
$filename = $this->clean_filename($filename);
} catch (SharepointException $e) {
throw new SharepointException($e->getMessage());
}
//build uri
if (is_null($folder_id)) {
$uri = $this->base_url . 'files/root/children/'.rawurlencode($filename).'/content?nameConflict=abort';
} else {
$uri = $this->base_url . 'files/'.$folder_id.'/children/'.rawurlencode($filename).'/content?nameConflict=abort';
}
$response = $this->upload($uri, $filepath);
if (array_key_exists('error', $response)) {
throw new SharepointException($response['error']);
}
return $response;
}
private function upload($uri, $filepath) {
$pointer = fopen($filepath, 'r+');
$stat = fstat($pointer);
$pointersize = $stat['size'];
$ch = curl_init($uri);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_PUT, true);
curl_setopt($ch, CURLOPT_INFILE, $pointer);
curl_setopt($ch, CURLOPT_INFILESIZE, (int)$pointersize);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, TRUE);
//Expect:
//HTTP response code 100 workaround
//see http://www.php.net/manual/en/function.curl-setopt.php#82418
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Expect:',
'Content-Type: application/json',
'Authorization: Bearer ' . $this->access_token,
));
$response = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$accepted_codes = array(
'200',
'201',
);
if (!in_array($httpcode, $accepted_codes)) {
//generic error
$error = 'HTTP status code not expected - got '.$httpcode;
//more descriptive error
if ($httpcode == '400') {
$data = json_decode($response, true);
if (isset($data['error']['message'])) {
$error = $data['error']['message'];
}
}
return array('error' => $error);
}
return json_decode($response, true);
}
private function clean_filename($filename) {
$filename = preg_replace('/[*><|}{&#%~:"?\/\\\\]/', '', $filename);
if (strpos('.', $filename) === 0) {
$filename = substr($filename, 1);
}
if (empty($filename)) {
throw new SharepointException('File is empty after removing illegal characters.');
}
return $filename;
}
My question is specific for iContact API. I have register an application and get API id. But I am not able to find accountId and clientFolderId.
Please see this below link :
http://developer.icontact.com/documentation/request-your-accountid-and-clientfolderid/
At above page "Perform a GET on the Accounts resource" How I can perform this to get account id and clientfolderid.
The easiest way I have found: Login to sandbox or to your real iContact account, in the main menu go to Contact -> Sign-up forms, then create just any form, click on view HTML and you will find Account Id there.
This is my full code to get the account id and client folder id, thanks to Carlos Duran above for getting some of my code problems worked out:
/* iContact LIVE * /
$GLOBALS['iContact_settings'] = array(
'apiUrl' => 'https://app.icontact.com',
'apiPage' => '/icp/a/',
'username' => 'username',
'password' => 'password',
'appId' => 'appId'
);
/* iContact SANDBOX */
$GLOBALS['iContact_settings'] = array(
'apiUrl' => 'https://app.sandbox.icontact.com',
'apiPage' => '/icp/a/',
'username' => 'username-beta',
'password' => 'password',
'appId' => 'appId'
);
/**/
$icontact_url = $GLOBALS['iContact_settings']['apiUrl'] . $GLOBALS['iContact_settings']['apiPage'];
$icontact_page = $GLOBALS['iContact_settings']['apiPage'];
$icontact_headers = array(
"GET ".$icontact_page." HTTP/1.0",
"Accept: text/xml",
"Content-Type: text/xml",
"API-Version: 2.2",
"API-AppId: " . $GLOBALS['iContact_settings']['appId'],
"API-Username: " . $GLOBALS['iContact_settings']['username'],
"API-Password: " . $GLOBALS['iContact_settings']['password']
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $icontact_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $icontact_headers);
$data = curl_exec($ch);
curl_close($ch);
$account_id = "";
if (($pos=strpos($data,"<accountId>"))!==false){
$account_id = substr($data, strlen("<accountId>")+$pos);
if (($pos=strpos($account_id,"<"))!==false){
$account_id = substr($account_id, 0, $pos);
}
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $icontact_url ."$account_id/c/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $icontact_headers);
$data = curl_exec($ch);
curl_close($ch);
$client_folder_id = "";
if (($pos=strpos($data,"<clientFolderId>"))!==false){
$client_folder_id = substr($data, strlen("<clientFolderId>")+$pos);
if (($pos=strpos($client_folder_id,"<"))!==false){
$client_folder_id = substr($client_folder_id, 0, $pos);
}
}
I just switched to JSON, way better.
$handle = curl_init();
curl_setopt($handle, CURLOPT_URL, $icontact_url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($handle, CURLOPT_HTTPHEADER, $icontact_headers);
$data = curl_exec($handle);
curl_close($handle);
$decoded = json_decode($data);
$account_id = $decoded->accounts[0]->accountId;
$handle = curl_init();
curl_setopt($handle, CURLOPT_URL, $icontact_url ."$account_id/c/");
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($handle, CURLOPT_HTTPHEADER, $icontact_headers);
$data = curl_exec($handle);
curl_close($handle);
$decoded = json_decode($data);
$client_folder_
id = $decoded->clientfolders[0]->clientFolderId;
And use:
"Accept: application/json",
"Content-Type: application/json",
Instead of text/xml above.
The only way to work with the iContact API, is to send correct headers to the server, then you will be able to make any of the requests and actions that appear in the documentation.
The best way that I found to do this is by setting up a PHP script with cUrl
$url = "https://app.sandbox.icontact.com/icp/a/";
$page = "/icp/a/";
$headers = array(
"GET ".$page." HTTP/1.0",
"Accept: text/html",
"Content-Type: text/html",
"API-Version: 2.2",
"API-AppId: yourapiappid",
"API-Username: yourapiusername",
"API-Password: yourappidpassword"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$data = curl_exec($ch);
Here you get your accountId and the rest is just calling the right url with this script!
Hope it gives you a hint.
"Keep up the good coding."
This PHP iContact API is rather useful https://github.com/icontact