I need a local CORS proxy to load images from an external source. These images should be rendered in the canvas object.
For this I use the solution from https://github.com/softius/php-cross-domain-proxy
However no images are loaded but there is an empty response
This is the Part where Images should be rendered in a Canvas Object
loadImages() {
this.images.forEach((value, index) => {
const image = {};
image.img = new Image();
image.img.crossOrigin = 'anonymous';
image.img.src = 'https://cors-anywhere.herokuapp.com/' + value.packshot;
//image.img.src = '/proxy.php?csurl=' + value.packshot;
image.img.onload = (() => {
// some code
});
});
},
this works
https://cors-anywhere.herokuapp.com/http://download.falk-ross.eu/ws/picture/163_06_051_f-2015-nc_01.jpg
this doesn't work /proxy.php?csurl=http://download.falk-ross.eu/ws/picture/163_06_051_f-2015-nc_01.jpg
anyone knows advice?
got it - with many thanks to this greate community. sometimes the solutions comes in when asking the question
<?php
$url = ($_POST['url']) ? $_POST['url'] : $_GET['url'];
$headers = ($_POST['headers']) ? $_POST['headers'] : $_GET['headers'];
$mimeType = ($_POST['mimeType']) ? $_POST['mimeType'] : $_GET['mimeType'];
$session = curl_init($url);
if ($_POST['url']) {
$postvars = '';
while ($element = current($_POST)) {
$postvars .= key($_POST) . '=' . $element . '&';
next($_POST);
}
curl_setopt($session, CURLOPT_POST, true);
curl_setopt($session, CURLOPT_POSTFIELDS, $postvars);
}
curl_setopt($session, CURLOPT_HEADER, $headers == 'true');
curl_setopt($session, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($session);
if ($mimeType != '') {
header('Content-Type: ' . $mimeType);
}
echo $response;
curl_close($session);
Related
I get JSON from the Soundcloud API by using code in section【A】.
But I want to get it without using $type, like in code【B】.
In other words, I want to get that information by only giving $target.
What should I do?
$r = soundcloud_responce();
var_dump( $r );
function soundcloud_responce(){
$client_id = 'xxx';
$type = 'tracks';
$q = 'words';
// code【A】
// If I have $type, So this process ok.
$url = "https://api.soundcloud.com/";
$url .= $type;
$url .= "?client_id=$client_id";
$url .= "&q=$q";
// code【B】
// I want to do same process with $target but without $type
$target = "https://soundcloud.com/accountname/trackname";
$target = str_replace('https://soundcloud.com/', '', $target);
$url = "https://api.soundcloud.com/";
$url .= $target;
$url .= "?client_id=$client_id";
// curl
$ch = curl_init();
$headers = [
'Accept: application/json',
'Content-Type: application/json',
];
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$res = curl_exec($ch);
$json = json_decode($res);
curl_close($ch);
return $json;
}
(Add 2020-02-21-09:38 #Tokyo)
I tried this code【C】but this also failed.
// code【C】
// I tried with oembed but this also failed.
$target = "https://soundcloud.com/accountname/trackname";
$url = 'http://soundcloud.com/oembed?format=json&url='.$target;
(Add 2020-02-21-10:12 #Tokyo)
I tried this code【D】but this also failed.
// code【D】
// I tried with resolve but this also failed.
$target = "https://soundcloud.com/accountname/trackname";
$url = "https://api.soundcloud.com/resolve?url=$target&client_id=$client_id";
I tried this code【E】this is successful!
Thank you for giving me good advice, #showdev.
// code【E】
// this is successful!
$target = "https://soundcloud.com/accountname/trackname";
$target = urlencode($target);
$url = "https://api.soundcloud.com/resolve.json?url=$target&client_id=$client_id";
I am experimenting with the Cloudsight API (Image recognition) and am seeing speed issues in response time. Their website advertises a 6-12 second response time, but I am routinely seeing responses taking up to and well over 20 seconds.
I would like to know if this is something on CloudSights end and that is just the response time, or if my code is causing these delays by being unoptimized or doing unnecessary work.
The following is my PHP code, it works fully, I can upload an image and read/display the response. My HTML code is a simple form that calls this PHP file.
<?php
$filename = $_FILES['fileToUpload']['name'];
$filedata = $_FILES['fileToUpload']['tmp_name'];
$filesize = $_FILES['fileToUpload']['size'];
$filetype = $_FILES['fileToUpload']['type'];
/*$tmpfile = $_FILES['fileToUpload']['tmp_name'];
$filename = basename($_FILES['fileToUpload']['name']);*/
$ch = curl_init("https://api.cloudsightapi.com/image_requests");
//$ch = curl_init("http://requestb.in/131zwlo1");
$postFields = [
"image_request[locale]" => "en-US",
"image_request[language]" => "en-US",
"image_request[image]" => "#$filedata".";filename=#$filename".";type=#$filetype"
];
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: CloudSight [key]", "Content-Type:multipart/form-data"));
$result = curl_exec($ch);
curl_close($ch);
$result = json_decode($result, true);
$token = $result['token'];
$status = $result['status'];
sleep(3);
while($status == "not completed"){
sleep(1);
$cht = curl_init("http://api.cloudsightapi.com/image_responses/$token");
curl_setopt($cht, CURLOPT_RETURNTRANSFER, true);
curl_setopt($cht, CURLOPT_HTTPHEADER, array("Authorization: CloudSight 6-j8FTD-h1ZtnlYgacdSEQ"));
$result = curl_exec($cht);
curl_close($cht);
$result = json_decode($result, true);
$status = $result['status'];
};
$name = $result['name'];
$reason = $result['reason'];
if($name != ""){
echo "\nName: $name";
};
if($reason != ""){
echo "\nReason Skipped: $reason";
};
?>
I am using this PHP Class for Instagram's API: https://github.com/cosenary/Instagram-PHP-API.
It works perfectly but I can't seem to access the rate limit information for each call I make.
Inside the class, this is the method that makes the call:
protected function _makeCall($function, $auth = false, $params = null, $method = 'GET') {
if (false === $auth) {
$authMethod = '?client_id=' . $this->getApiKey();
} else {
if (true === isset($this->_accesstoken)) {
$authMethod = '?access_token=' . $this->getAccessToken();
} else {
throw new \Exception("Error: _makeCall() | $function - This method requires an authenticated users access token.");
}
}
if (isset($params) && is_array($params)) {
$paramString = '&' . http_build_query($params);
} else {
$paramString = null;
}
$apiCall = self::API_URL . $function . $authMethod . (('GET' === $method) ? $paramString : null);
$headerData = array('Accept: application/json');
if (true === $this->_signedheader && 'GET' !== $method) {
$headerData[] = 'X-Insta-Forwarded-For: ' . $this->_signHeader();
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiCall);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headerData);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if ('POST' === $method) {
curl_setopt($ch, CURLOPT_POST, count($params));
curl_setopt($ch, CURLOPT_POSTFIELDS, ltrim($paramString, '&'));
} else if ('DELETE' === $method) {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
}
$jsonData = curl_exec($ch);
if (false === $jsonData) {
throw new \Exception("Error: _makeCall() - cURL error: " . curl_error($ch));
}
curl_close($ch);
return json_decode($jsonData);
}
The information I need to access from Instagram's API is:
X-Ratelimit-Limit
X-Ratelimit-Remaining
(http://instagram.com/developer/limits/ for more information about Instagram's limits).
For obvious reasons I need the app I'm creating to "shut itself down" before the rate limit kicks in. By accessing the rate limit information I can achieve this.
I have found a Gist that should work with this class but I can't seem to get it to work: https://gist.github.com/cosenary/6af4cf4b509518169b88
Also this topic here on Stackoverflow seems to be fruitless:
Instagram API count limits using HTTP header
If anyone could help me out here that would be amazing!
Best regards,
Peter de Leeuw
I have modified the function _makeCall and it is as follows by adding first curl_setopt($ch, CURLOPT_HEADER, true); and calling the function processHeader() as cosenary suggested on this gist cosenary/ratelimit.php:
protected function _makeCall($function, $auth = false, $params = null, $method = 'GET') {
if (false === $auth) {
// if the call doesn't requires authentication
$authMethod = '?client_id=' . $this->getApiKey();
} else {
// if the call needs an authenticated user
if (true === isset($this->_accesstoken)) {
$authMethod = '?access_token=' . $this->getAccessToken();
} else {
throw new \Exception("Error: _makeCall() | $function - This method requires an authenticated users access token.");
}
}
if (isset($params) && is_array($params)) {
$paramString = '&' . http_build_query($params);
} else {
$paramString = null;
}
$apiCall = self::API_URL . $function . $authMethod . (('GET' === $method) ? $paramString : null);
// signed header of POST/DELETE requests
$headerData = array('Accept: application/json');
if (true === $this->_signedheader && 'GET' !== $method) {
$headerData[] = 'X-Insta-Forwarded-For: ' . $this->_signHeader();
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiCall);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headerData);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if ('POST' === $method) {
curl_setopt($ch, CURLOPT_POST, count($params));
curl_setopt($ch, CURLOPT_POSTFIELDS, ltrim($paramString, '&'));
} else if ('DELETE' === $method) {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
}
$jsonData = curl_exec($ch);
// split header from JSON data
// and assign each to a variable
list($headerContent, $jsonData) = explode("\r\n\r\n", $jsonData, 2);
// convert header content into an array
$headers = $this->processHeaders($headerContent);
// get the 'X-Ratelimit-Remaining' header value
$ratelimitRemaining = $headers['X-Ratelimit-Remaining'];
$this->setHeaderLimit($ratelimitRemaining);
if (false === $jsonData) {
throw new \Exception("Error: _makeCall() - cURL error: " . curl_error($ch));
}
curl_close($ch);
return json_decode($jsonData);
}
the processHeader() method which processes the header and the set and get methods for the $rateLimitRemaining are as follows :
private function processHeaders($headerContent){
$headers = array();
foreach (explode("\r\n", $headerContent) as $i => $line) {
if($i===0){
$headers['http_code'] = $line;
}else{
list($key,$value) = explode(':', $line);
$headers[$key] = $value;
}
}
return $headers;
}
private function setHeaderLimit($HeaderLimit){
$this->HeaderLimit = $HeaderLimit;
}
public function getHeaderLimit(){
return $this->HeaderLimit;
}
You can access the X-Ratelimit-Remaining now from another class just by calling the getHeaderLimit()
*Don't forget to declare the public field HeaderLimit within the class where _makeCall() resides, which in this case is Instagram.php.
**I have tested this solution and it works perfectly.
Hope this helps you guys :)
I have the ZF first old function working before but somehow ZF it was failing, and then i made the unittest module.
I am trying to use the google translation v2 but it never works anymore, did Google stop there service for public use or is it PHP Bug or somewhere else confusing very much.
Always returning 403 with both following functions.
Any idea whats going wrong?
<?php
## Test: How to's
/*
$ php tst.php
403
$ curl http://ajax.googleapis.com/ajax/services/language/translate -d "v=1.0&q=dog&langpair=en|ru" -H "Referer: http://google.com"
{"responseData": null, "responseDetails": "Please use Translate v2. See http://code.google.com/apis/language/translate/overview.html", "responseStatus": 403}sun#sun-M14xR2:/var/www/html/vooyz.com/unittest$
*/
// V1 - Old not working
function googleTranslatePostV1($text, $destLang = 'nl', $srcLang = 'en') {
$url = 'http://ajax.googleapis.com/ajax/services/language/translate';
$http_response = '';
$text = urlencode($text);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_REFERER, !empty($_SERVER["HTTP_REFERER"]) ? $_SERVER["HTTP_REFERER"] : "");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "v=1.0&q=" . $text . "&langpair=$srcLang|$destLang");
$http_response = curl_exec($ch);
$json = json_decode($http_response, true);
if ($json['responseStatus'] != '200') {
return $json['responseStatus'];
} else {
return $json['responseData']['translatedText'];
}
curl_close($ch);
}
// V2 - Curl way not working
function googleTranslatePostV2($text, $destLang = 'nl', $srcLang = 'en') {
$url = 'https://www.googleapis.com/language/translate/v2';
$http_response = '';
$text = urlencode($text);
$postArr = array('key' => 'sdfdsfdsfds',
'q' => $text,
'source' => $srcLang,
'target' => $destLang);
$ch = curl_init();
//curl_setopt($ch, CURLOPT_POSTFIELDS,'hl=en&ie=UTF8&text=-->this+is+a+test<--&langpair=en%7Car');
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_REFERER, !empty($_SERVER["HTTP_REFERER"]) ? $_SERVER["HTTP_REFERER"] : "");
curl_setopt($ch, CURLOPT_POST,true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$postArr);
$http_response = curl_exec($ch);
var_dump($http_response);
$json = json_decode($http_response, true);
if ($json['responseStatus'] != '200') {
return $json['responseStatus'];
} else {
return $json['responseData']['translatedText'];
}
curl_close($ch);
}
// V2 - Google way
function googleTranslateV2Method1($text, $destLang = 'nl', $srcLang = 'en') {
require_once 'google/src/Google_Client.php';
require_once 'google/src/contrib/Google_TranslateService.php';
$client = new Google_Client();
$client->setApplicationName('Google Translate PHP Starter Application');
$client->setDeveloperKey('dsfdsfdsf');
$service = new Google_TranslateService($client);
//$langs = $service->languages->listLanguages();
//print "<h1>Languages</h1><pre>" . print_r($langs, true) . "</pre>";
$translations = $service->translations->listTranslations($text, 'hi');
return $translations;
}
echo googleTranslatePostV1("V1: " . "How are you?") . "\n";
echo googleTranslatePostV2("V2: " . "How are you?") . "\n";
echo googleTranslateV2Method1("V2: " . "How are you?") . "\n";
?>
$ curl http://ajax.googleapis.com/ajax/services/language/translate -d "v=1.0&q=dog&langpair=en|ru" -H "Referer: http://google.com"
{"responseData": null, "responseDetails": "Please use Translate v2. See http://code.google.com/apis/language/translate/overview.html", "responseStatus": 403}
http://code.google.com/apis/language/translate/overview.html : Google
Translate API is available as a paid service. See the Pricing and FAQ
pages for details.
I'm trying to save a users profile image on facebook using CURL. When I use the code below, I save a jpeg image but it has zero bytes in it. But if I exchange the url value to https://fbcdn-profile-a.akamaihd.net/hprofile-ak-snc4/211398_812269356_2295463_n.jpg, which is where http://graph.facebook.com/' . $user_id . '/picture?type=large redirects the browser, the image is saved without a problem. What am I doing wrong here?
<?php
$url = 'http://graph.facebook.com/' . $user_id . '/picture?type=large';
$file_handler = fopen('pic_facebook.jpg', 'w');
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_FILE, $file_handler);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_exec($curl);
curl_close($curl);
fclose($file_handler);
?>
There is a redirect, so you have to add this option for curl
// safemode if off:
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
but if you have safemode if on, then:
// safemode if on:
<?php
function curl_redir_exec($ch)
{
static $curl_loops = 0;
static $curl_max_loops = 20;
if ($curl_loops++ >= $curl_max_loops)
{
$curl_loops = 0;
return FALSE;
}
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
#list($header, $data) = #explode("\n\n", $data, 2);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($http_code == 301 || $http_code == 302)
{
$matches = array();
preg_match('/Location:(.*?)\n/', $header, $matches);
$url = #parse_url(trim(array_pop($matches)));
if (!$url)
{
//couldn't process the url to redirect to
$curl_loops = 0;
return $data;
}
$last_url = parse_url(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL));
if (!$url['scheme'])
$url['scheme'] = $last_url['scheme'];
if (!$url['host'])
$url['host'] = $last_url['host'];
if (!$url['path'])
$url['path'] = $last_url['path'];
$new_url = $url['scheme'] . '://' . $url['host'] . $url['path'] . (#$url['query']?'?'.$url['query']:'');
return $new_url;
} else {
$curl_loops=0;
return $data;
}
}
function get_right_url($url) {
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
return curl_redir_exec($curl);
}
$url = 'http://graph.facebook.com/' . $user_id . '/picture?type=large';
$file_handler = fopen('pic_facebook.jpg', 'w');
$curl = curl_init(get_right_url($url));
curl_setopt($curl, CURLOPT_FILE, $file_handler);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_exec($curl);
curl_close($curl);
fclose($file_handler);
If you can't process the redirect, try this instead:
Make the request to https://graph.facebook.com/<USER ID>?fields=picture and parse the response, which will be in JSON format and look like this - e.g. for Zuck you get this response:
{
"picture": "http://profile.ak.fbcdn.net/hprofile-ak-snc4/157340_4_3955636_q.jpg"
}
Then make your curl request directly to retrieve the image from that cloud storage URL
set
CURLOPT_FOLLOWLOCATION to true
so that it follows the 301/302 redirect the reads the image file from final location.
i.e.
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
I managed to do it this way, works perfectly fine:
$data = file_get_contents('https://graph.facebook.com/[App-Scoped-ID]/picture?width=378&height=378&access_token=[Access-Token]');
$file = fopen('fbphoto.jpg', 'w+');
fputs($file, $data);
fclose($file);
You just need an App Access Token (APPID . '|' . APPSECRET), and you can specify width and height.
You can also add "redirect=false" to the URL, to get a JSON object with the URL (For example: https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xpa1...)
CURLOPT_FOLLOWLOCATION has been removed in PHP5.4, so it´s not really an option anymore.