i am totaly new to CURL thing . i have a problem .
i have the below script which supposed to get remote files using a proxy , i am trying this code on my local host machine and it is working great "done successfully part: .
when i run it from server , it just keep going to the "invalid proxy" although it is same proxy as used in the local host ..
<?php
$dots = '';
include($dots.'classes/config.php');
$wordsLimitPerCall = 1;
$maxAttemptsTrials = 3;
$timeout = 10; // Seconds
$proxy = sqlSelectRow('proxy', array(
'condition'=>'not_valid=0',
'order'=>'rand()'
));
echo '<ul>';
if($proxy)
echo '<li>Using proxy: '.$proxy['proxy'].':'.$proxy['port'].'</li>';
$wordsRes = sqlSelectRows('words', array(
'condition'=>'is_done=0 and trials<'.$maxAttemptsTrials,
'limit'=>$wordsLimitPerCall,
'order'=>'created asc'
));
while($arr = $wordsRes->fetch_assoc()) {
$word = urlencode($arr['word']);
$url = 'http://example.com'.$word;
$callSettings = array(
'method'=>'curl',
'timeout'=>$timeout
);
if($proxy)
$callSettings['proxy'] = $proxy['proxy'].':'.$proxy['port'];
$result = callRemoteURL($url, $callSettings);
$filename = urldecode($word);
$filename = 'file/'.$arr['id'].' - '.$filename.'.mp3';
echo '<li>Getting the word: '.$word.'</li>';
if($result && strpos($result, '<html')===false) {
if(file_exists($dots.$filename))
unlink($dots.$filename);
fileWrite($filename, $result);
$is_done = 1;
echo '<li>done successfully</li>';
}
else {
$is_done = 0;
if($proxy) {
sqlUpdate('proxy', array(
'not_valid'=>0
), array(
'condition'=>'id='.$proxy['id']
));
echo '<li>Proxy is not valid</li>';
}
}
sqlUpdate('words', array(
'trials'=>$arr['trials']+1,
'path'=>$url,
'last_call_date'=>date('Y-m-d H:i:s'),
'is_done'=>$is_done
), array(
'condition'=>'id='.$arr['id']
));
}
echo '</ul>'; ?>
below the function called from utils
<? php
if($set['method']=='curl' && extension_loaded('curl'))
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0);
curl_setopt($ch, CURLOPT_TIMEOUT, $set['timeout']); // Seconds
if($set['proxy'])
curl_setopt($ch, CURLOPT_PROXY, $set['proxy']);
ob_start();
if(curl_exec($ch) === false)
{
$errorNo = curl_errno($ch);
if($errorNo==28)
print_r('The connection took time more than '. $set['timeout'].' seconds, so we disconnected the process');
else
if($errorNo!=7)
print_r(curl_error($ch));
$result=false;
}
else
{
$result = ob_get_contents();
}
ob_end_clean();
return $result;
}
?>
sorry if its too long ... but i've spent the last couple days tryng to find out . any idea or what shall i do ?
Related
I am using Face API with curl in PHP. But I am having issue when matching images.
I am able to generate faceId's but when matching I get different results than expected. I have two images belonges to same person but API indicates that these images are different. But when using Microsoft demo to compare images I get right result.
Here is microsoft demo link:
https://azure.microsoft.com/en-in/services/cognitive-services/face/#demo
Here are My images url
$img1 = "http://nexever.in/LibTravelSuperAdmin/images/temporary/1645715403_1.jpg";
$img2 = "http://nexever.in/LibTravelSuperAdmin/images/temporary/3.png";
Here is my code
<?php
function compare($image1, $image2)
{
$faceid = array();
$images = array($image1 , $image2);
$headers = ["Ocp-Apim-Subscription-Key: ********* ","Content-Type:application/json" ];
/* Getting faceId */
foreach($images as $data)
{
/* First step is to detect face */
$request_url='https://nexever.cognitiveservices.azure.com/face/v1.0/detect?detectionModel=detection_03&returnFaceId=true&returnFaceLandmarks=false';
/* Image to get faceid */
$detect = array('url' => $data);
$curl = curl_init(); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_URL, $request_url); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($detect)); curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$strResponse = curl_exec($curl);
$curlErrno = curl_errno($curl);
if ($curlErrno) { $curlError = curl_error($curl);throw new Exception($curlError); }
$http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl);
$strResponse = json_decode($strResponse , true);
print_r($strResponse);
array_push($faceid , $strResponse[0]['faceId']);
}
// comparing by face ID
/* Match face url */
$request_url = 'https://nexever.cognitiveservices.azure.com/face/v1.0/verify';
/* Face ID to compare */
print_r($faceid);
$match = array("faceId1"=>$faceid[0], "faceId2"=>$faceid[1],"maxNumOfCandidatesReturned" =>10,"mode"=> "matchFace");
$curl = curl_init(); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_URL, $request_url); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($match)); curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$strResponse = curl_exec($curl); $curlErrno = curl_errno($curl);
if ($curlErrno) {$curlError = curl_error($curl); throw new Exception($curlError); }
$http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
return json_decode($strResponse, true);
}
$img1 = "http://nexever.in/LibTravelSuperAdmin/images/temporary/1645715403_1.jpg";
$img2 = "http://nexever.in/LibTravelSuperAdmin/images/temporary/3.png";
$ret = compare($img1, $img2);
//print_r($ret);
if(isset($ret['isIdentical']))
{
if($ret['isIdentical'] == 1)
{
echo "Same Person ";
}
else if($ret['isIdentical'] == 0)
{
echo "Different Person ";
}
}
?>
I have successfully got face id but unable to match. If I try some other images of same person it matches sometimes. The problem is result is not accurate.
but on microsoft demo it is working fine.
Pls try to use specify request param: recognitionModel=recognition_04 when you detect faces as official doc recommanded:
I modified your code as below, it works for me perfectly:
<?php
function compare($image1, $image2)
{
$faceid = array();
$images = array($image1 , $image2);
$faceAPIName = "nexever";
$apikey = "<your api key>";
$faceidAPIHost = "https://$faceAPIName.cognitiveservices.azure.com";
foreach($images as $data)
{
$detect = array('url' => $data);
$result = do_post("$faceidAPIHost/face/v1.0/detect?recognitionModel=recognition_04&detectionModel=detection_03",json_encode($detect),$apikey);
array_push($faceid , $result[0]['faceId']);
}
$request_url = "$faceidAPIHost/face/v1.0/verify";
/* Face ID to compare */
print_r($faceid);
$match = array("faceId1"=>$faceid[0], "faceId2"=>$faceid[1],"maxNumOfCandidatesReturned" =>10,"mode"=> "matchFace");
return do_post($request_url,json_encode($match),$apikey);
}
function do_post($url, $params,$key) {
$options = array(
'http' => array(
'header' => "Content-type: application/json\r\nOcp-Apim-Subscription-Key: $key",
'method' => 'POST',
'content' => $params
)
);
$result = file_get_contents($url, false, stream_context_create($options));
return json_decode($result, true);
}
$img1 = "http://nexever.in/LibTravelSuperAdmin/images/temporary/1645715403_1.jpg";
$img2 = "http://nexever.in/LibTravelSuperAdmin/images/temporary/3.png";
$ret = compare($img1, $img2);
//print_r($ret);
if(isset($ret['isIdentical']))
{
if($ret['isIdentical'] == 1)
{
echo "Same Person ";
}
else if($ret['isIdentical'] == 0)
{
echo "Different Person ";
}
}
?>
Result of your code:
I have a few lines of code in a script, and if part A executes, then part B executes TWICE (that is: the cron.php file is added to the crontab TWICE). This is odd, because if I comment out part A, part B only executes ONCE.
Why is this happening? What am I missing?
// Part A
$url = "https://api.sendgrid.com/apiv2/customer.add.json";
$input = "api_user=$sendgrid_user_account&api_key=$sendgrid_master_password&username=$custname.domain.com&website=$sendgridsubuserdomain&password=$sendgridsubusersmtppass&con firm_password=$sendgridsubusersmtppass&first_name=$first&last_name=$last&address=$sendgridsubuseraddress&city=$sendgridsubusercity&state=$sendgridsubuserstate&zip=$ sendgridsubuserzip&email=$email&country=$sendgridsubusercountry&company=$custname&phone=$sendgridsubuserphone";
$sendgrid_output = postCurl($url, $input, false, false);
// Part B
chdir("/etc/nginx/");
exec("2>&1 ./addcron.sh $custname");
Supporting functions:
function postUrl($url, $data, $headers = null, $json_format = true) { // json format is only used if $data is also formatted as a string
$curl_result = postCurl($url, $data);
if($curl_result != false) return $curl_result;
$data_query = http_build_query($data);
$opts = array('http' => array('method' => 'POST', 'content' => $data_query));
if($headers) {
$opts['http']['header'] = $headers;
}
else {
$opts['http']['header'] = "Content-type: application/x-www-form-urlencoded";
}
$st = stream_context_create($opts);
$fp = fopen($url, 'rb', false, $st);
if(!$fp) {
//$result = http_post_fields($url, $data); TODO: add back in once AWS's PHP updated to include http_post_fields function
//if(!empty($result)) return $result;
}
$result = stream_get_contents($fp);
if(empty($result)) {
//$result = http_post_fields($url, $data);
//if(!empty($result)) return $result;
}
return false; // if all else fails, false
}
function postCurl($url, $values, $boolean_return = false, $json_format = true) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
if(is_array($values)) {
$values_string = "";
foreach($values as $key => $value) $values_string .= "$key=$value&";
$values_string = substr($values_string, 0, -1); // remove last "&"
}
else { // if it's not an array, assume JSON
$values_string = $values;
if($json_format == true) {
$input_array = array(
'Content-Type: application/json',
'Content-Length: ' . strlen($values_string));
}
else {
$input_array = array('Content-Length: ' . strlen($values_string));
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $input_array);
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $values_string);
// in real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS,
// http_build_query(array('postvar1' => 'value1')));
// receive server response ...
if($boolean_return == false) curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
return $server_output;
}
The addcron.sh script:
#!/bin/bash
custname="$1"
(crontab -l; echo "* * * * * /usr/bin/php -f /var/www/html/$custname/cron/cron.php" ) | crontab -
I'm a beginner in PHP, so maybe someone could help to fix this ?
My web application is showing Google PageInsights API error..
Here's the code, I tried to change version to /v2/, but it still didn't work..
public function getPageSpeed($domain, $api = "")
{
try
{
$callback_url = "https://www.googleapis.com/pagespeedonline/v1/runPagespeed?";
$data = array(
'url' => 'http://' . $domain,
'key' => (empty($api) ? $_SESSION['GOOGLEAPI_SERVERKEY'] : $api),
'fields' => 'score,pageStats(htmlResponseBytes,textResponseBytes,cssResponseBytes,imageResponseBytes,javascriptResponseBytes,flashResponseBytes,otherResponseBytes)'
);
$curl_response = $this->curl->get($callback_url . http_build_query($data, '', '&'));
if ($curl_response->headers['Status-Code'] == "200") {
$content = json_decode($curl_response, true);
$response = array(
'status' => 'success',
'data' => array(
'pagespeed_score' => (int)$content['score'],
'pagespeed_stats' => $content['pageStats']
)
);
} else {
$response = array(
'status' => 'error',
'msg' => 'Google API Error. HTTP Code: ' . $curl_response->headers['Status-Code']
);
}
}
catch (Exception $e)
{
$response = array(
'status' => 'error',
'msg' => $e->getMessage()
);
}
return $response;
}
<?php
function checkPageSpeed($url){
if (function_exists('file_get_contents')) {
$result = #file_get_contents($url);
}
if ($result == '') {
$ch = curl_init();
$timeout = 60;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$result = curl_exec($ch);
curl_close($ch);
}
return $result;
}
$myKEY = "your_key";
$url = "http://kingsquote.com";
$url_req = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url='.$url.'&screenshot=true&key='.$myKEY;
$results = checkPageSpeed($url_req);
echo '<pre>';
print_r(json_decode($results,true));
echo '</pre>';
?>
The code shared by Siren Brown is absolutely correct, except that
while getting the scores we need to send the query parameter &strategy=mobile or &strategy=desktop to get the respective results from Page speed API
$url_mobile = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url='.$url.'&screenshot=true&key='.$myKEY.'&strategy=mobile';
$url_desktop = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url='.$url.'&screenshot=true&key='.$myKEY.'&strategy=desktop';
I am having troble on curl functions in my codes. My CURLINFO_HTTP_CODE always return 0 and when I use
curl_error($ch) it returns 'could not reach host'. My host is ispeech and it shouldn't have problems. Can anyone here help me out? Thanks a lot!
iSpeech.php
class iSpeechBase{
var $server;
var $parameters = array("device-type"=>"php-SDK-0.3");
function setParameter($parameter, $value){
if ($parameter == "server")
$this->server = $value;
else
$this->parameters["$parameter"] = $value;
}
function makeRequest(){
$ch = curl_init();
$url=$this->server . "/?" . http_build_query($this->parameters);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
ob_start();
echocurl_exec($ch);
$http_body = ob_get_contents();
ob_end_clean();
echo curl_getinfo($ch, CURLINFO_HTTP_CODE); //return 0
echo curl_error($ch); //return Could not reach host.
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) != 200)
if ($this->parameters["action"] == "convert")
return array("error" => $http_body);
return $http_body;
}
}
synthesis-demo.php
require_once('ispeech.php');
$SpeechSynthesizer = new SpeechSynthesizer();
$SpeechSynthesizer->setParameter("server", "http://api.ispeech.org/api/rest");
$SpeechSynthesizer->setParameter("apikey", "myapikey");
$SpeechSynthesizer->setParameter("text", "yes");
$SpeechSynthesizer->setParameter("format", "wav");
$SpeechSynthesizer->setParameter("voice", "usenglishfemale");
$SpeechSynthesizer->setParameter("output", "rest");
$result = $SpeechSynthesizer->makeRequest();
So save faffing around with the ob buffer, you could replace
ob_start();
echocurl_exec($ch);
$http_body = ob_get_contents();
ob_end_clean();
with
$http_body = curl_exec($ch);
Also adds the space between echo and curl_exec missing from your example (although that should throw a fatal and stop execution - do you have your own error handler?)
I am using PHP. I want to fetch all gmail contacts of a user, i am using a PHP code that is calling google API through CURL. But, when i am doing this on localhost, it is doing well and giving me all contacts.
But when i am doing this on online server that server in US, it is giving me response "Account Disabled" and also receiving a security mail by same user from google.
i am using below code :
function getGmailContacts($user, $password) {
//========================================== step 1: login ===========================================================
$login_url = "https://www.google.com/accounts/ClientLogin";
$fields = array(
'Email' => $user,
'Passwd' => $password,
'service' => 'cp', // <== contact list service code
'source' => 'test-google-contact-grabber',
'accountType' => 'GOOGLE',
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,$login_url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS,$fields);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
$returns = array();
foreach (explode("\n",$result) as $line)
{
$line = trim($line);
if (!$line) continue;
list($k,$v) = explode("=",$line,2);
$returns[$k] = $v;
}
curl_close($curl);
//echo "<pre>";
//print_r($returns);exit;
if(!isset($returns['Error'])) {
//========================== step 2: grab the contact list ===========================================================
$feed_url = "http://www.google.com/m8/feeds/contacts/$user/full?alt=json&max-results=250";
$header = array(
'Authorization: GoogleLogin auth=' . $returns['Auth'],
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $feed_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
$data = json_decode($result, true);
//echo "<pre>";
//print_r($data);exit;
$contacts = array();
$i=0;
foreach ($data['feed']['entry'] as $entry)
{
//echo $i." ";
$entryElement = $entry;
if(isset($entryElement['gd$email'])) {
$gdEmailData = $entryElement['gd$email'][0];
//$contact->title = $entryElement['title']['$t'];
//$contact->email = $gdEmailData['address'];
$contacts[$gdEmailData['address']] = $entryElement['title']['$t'];
}
}
//var_dump($contacts);
//print_r($contacts);
return $contacts;
}
else {
if($returns['Error']=='BadAuthentication') {
//echo '<strong>User Name and Password is incorrect.</strong>';
$errorArr = array("Error"=>"User Name and Password is incorrect.");
//print_r($errorArr);
return $errorArr;
}
}
}
That mail contains that
"Someone recently tried to use an application to sign in to your
Google Account....Location: New York NY, New York, United States....."
.
I thing this error is occurring from location change.
can any one help me please? Thanks in advance.