Can't send the request to the server - php

I've some problem with the PHP script. So, I'm trying to connect to the FMI Server, but when I'm enter a valid credentials the server always return HTTP code 330, instead of 200 OK. Also when I'm trying with invalid credentials it's return 401 and it's okay, but why I've this problem only with VALID credentials?
What I'm tried?
curl_setopt($ch,CURLOPT_ENCODING , "gzip");
But no luck :(
Here's my code:
<?php
$username = "callibra#yandex.ru"; //Valid login
$password = "callibra4App"; //Valid Password
class FMIWebApplication {
private $client = array(
"user-agent" => "FindMyiPhone/472.1 CFNetwork/711.1.12 Darwin/14.0.0",
"headers" => array(
"X-Apple-Realm-Support" => "1.0",
"X-Apple-Find-API-Ver" => "3.0",
"X-Apple-AuthScheme" => "UserIdGuest",
"X-Apple-I-MD-RINFO" => "17106176",
"Accept" => "*/*",
"Connection" => "keep-alive",
"Accept-Encoding" => "br, gzip, deflate",
"Accept-Language" => "en-us",
"X-Apple-I-TimeZone" => "GMT+2",
"X-Apple-I-Locale" => "en_US"
)
);
public $username;
public $password;
public $devices = array();
public function __construct($username, $password) {
$this->username = $username;
$this->password = $password;
$this->authenticate();
}
public function authenticate() {
$url = "https://fmipmobile.icloud.com/fmipservice/device/".$this->username."/initClient";
list($headers, $body) = $this->curlPOST($url, "", $this->username.":".$this->password);
/*
if ($headers["http_code"] == 200) {
return 200;
};
if ($headers["http_code"] == 401) {
return 401;
};
if ($headers["http_code"] == 403) {
return 403;
};*/
echo $headers["http_code"];
}
private function curlPOST($url, $body, $authentication = "") {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, $this->client["user-agent"]);
curl_setopt($ch, CURLOPT_SSLVERSION, 6);
if (strlen($authentication) > 0) {
curl_setopt($ch, CURLOPT_USERPWD, $authentication);
}
$arrHeaders = array();
$arrHeaders["Content-Length"] = strlen($request);
foreach ($this->client["headers"] as $key=>$value) {
array_push($arrHeaders, $key.": ".$value);
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $arrHeaders);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$responseBody = substr($response, $header_size);
$headers = array();
foreach (explode("\r\n", substr($response, 0, $header_size)) as $i => $line) {
if ($i === 0)
$headers['http_code'] = $info["http_code"];
else {
list ($key, $value) = explode(': ', $line);
if (strlen($key) > 0)
$headers[$key] = $value;
}
}
return array($headers, json_decode($responseBody, true));
}
}
$API = new FMIWebApplication($username, $password);
$API->authenticate();
?>
That's what I'm getting from the server:
HTTP/1.1 330 Server: AppleHttpServer/70a91026 Date: Thu, 07 Mar 2019 13:23:40 GMT Content-Length: 0 Connection: keep-alive X-Responding-Instance: fmipservice:34000504:mr23p40ic-ztdg08174101:7004:1903B41:738abffa X-Responding-Server: mr23p40ic-ztdg08174101_004 X-Responding-Partition: p40 X-Apple-MMe-Host: p40-fmipmobile.icloud.com X-Apple-MMe-Scope: 639524741 Strict-Transport-Security: max-age=31536000; includeSubDomains Set-Cookie: NSC_q40-gnjqtfswjdf=6ad0a3dee1e78d9bd168cb5a7ceafc289128c7a38269b4bddde70dac09e4e273e5f12331;path=/;secure;httponly via: icloudedge:mc10p01ic-zteu01141501:7401:18RC846:Manchester X-Apple-Request-UUID: 8d5dc207-f1f8-453f-8863-9e0d5ab3b58b access-control-expose-headers: X-Apple-Request-UUID access-control-expose-headers: Via 330

Related

FB messenger Bot not getting postback payloads

I am developing a facebook chatbot. I am facing a issue which I cannot solve. I am developing this in laravel. Here I cannot get the postback payload. here is my code
public function index(Request $request) {
if ($request->hub_verify_token === $this->verifyToken) {
echo $request->hub_challenge;
exit;
}
$input = json_decode(file_get_contents("php://input"), true);
$senderId = $input['entry'][0]['messaging'][0]['sender']['id'];
$messageText = $input['entry'][0]['messaging'][0]['message']['text'];
$pageId = $input['entry'][0]['id'];
$accessToken = "access_token_that_got_from_fb";
//set Message
if($messageText != "") {
$answer = "Howdy! User";
}
if($messageText == "hello") {
$answer = 'Testing hello from bot';
}
foreach ($input['entry'][0]['messaging'] as $message) {
// When bot receive message from user
if (!empty($message['postback'])) {
$answer = 'got it tada';
}
}
//send message to facebook bot
$response = [
'recipient' => [ 'id' => $senderId ],
'message' => [ 'text' => $answer ] //json_encode($request->getContent())
];
$ch = curl_init('https://graph.facebook.com/v2.11/me/messages?access_token='.$accessToken);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($response));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
$result = curl_exec($ch);
curl_close($ch);
}
and my route is
Route::any('chatbot', 'ChatbotController#index');
here the message is working . but the postback payload request is not going to server. on the other hand using the same code in normal php file I am able to get postback paylod.
$hubVerifyToken = 'chatbot';
$accessToken = "access_token";
// check token at setup
if ($_REQUEST['hub_verify_token'] === $hubVerifyToken) {
echo $_REQUEST['hub_challenge'];
exit;
}
// handle bot's anwser
$input = json_decode(file_get_contents('php://input'), true);
$senderId = $input['entry'][0]['messaging'][0]['sender']['id'];
$messageText = $input['entry'][0]['messaging'][0]['message']['text'];
$postback = isset($input['entry'][0]['messaging'][0]['postback']['payload']) ? $input['entry'][0]['messaging'][0]['postback']['payload'] : '' ;
//set Message
if($messageText == "hi") {
$answer = "Hello";
}
if($messageText == "hello") {
$answer = "Hello there, welcome to Chatleads";
}
if($postback) {
$answer = "postback TADA";
}
//send message to facebook bot
$response = [
'recipient' => [ 'id' => $senderId ],
'message' => [ 'text' => $answer ]
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://graph.facebook.com/v2.11/me/messages?access_token=$accessToken");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($response));
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = "Content-Type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
How to solve this issue? can anyone show me a path?
Solved it by checking at laravel.log file.
$this->messageText = isset($this->input['entry'][0]['messaging'][0]['message']['text']) ? $this->input['entry'][0]['messaging'][0]['message']['text'] : '' ;
messageText should be like this. that's why its causing an error.

500 Error uploading An Audio File Using AcrCloud RESTful api php

I am trying to upload audio file using php I got this
i tried the same credentials in Postman and it works.
I can't find out what is wrong
I am following ACRCloud documentation here
HTTP/1.1 100 Continue
< HTTP/1.1 500 Internal Server Error
< Server: openresty/1.9.7.4
< Date: Mon, 23 Jan 2017 16:51:29 GMT
< Content-Type: application/json; charset=UTF-8
< Transfer-Encoding: chunked
< Connection: keep-alive
< X-Powered-By: PHP/5.6.21
< X-Rate-Limit-Limit: 600
< X-Rate-Limit-Remaining: 599
< X-Rate-Limit-Reset: 0
HTTP error before end of send, stop sending
<
Closing connection 0`
mycode
$request_url = 'https://api.acrcloud.com/v1/audios';
$http_method = 'POST';
$http_uri = '/v1/audios';
$timestamp = time();
$signature_version = '1';
$account_access_key = '';
$account_access_secret = '';
$string_to_sign =
$http_method . "\n" .
$http_uri . "\n" .
$account_access_key . "\n" .
$signature_version . "\n" .
$timestamp;
$signature = base64_encode(hash_hmac("sha1", $string_to_sign, $account_access_secret, true));
$realpath = realpath('uploads/*****.mp3');
if(class_exists('\CURLFile'))
$cfile = new \CURLFile($realpath, "audio/mp3", basename($realpath));
else
$cfile = '#' . $realpath;
$fields = array(
'audio_id' => '30007',
'title' => 'aya number 19',
'audio_file' => $cfile,
'bucket_name' => 'whatever',
'data_type' => 'audio', // if you upload fingerprint file please set 'data_type'=>'fingerprint'
'custom_key[0]' => 'track_id',
);
$headerArray = array();
$headers = array(
'access-key' => $account_access_key,
'signature' => $signature,
'signature-version' => '1',
'timestamp' => $timestamp,
);
foreach( $headers as $n => $v ) {
$headerArr[] = $n .':' . $v;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $request_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
$verbose = fopen('php://temp', 'w+');
curl_setopt($ch, CURLOPT_STDERR, $verbose);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArr);
$result = curl_exec($ch);
if ($result === FALSE) {
printf("cUrl error (#%d): %s<br>\n", curl_errno($ch),
htmlspecialchars(curl_error($ch)));
}
rewind($verbose);
$verboseLog = stream_get_contents($verbose);
echo "Verbose information:\n<pre>", htmlspecialchars($verboseLog), "</pre>\n";
dd($result);
curl_close($ch);
I found out :
1- You have to use local file
2- Curl take absolute file path
3- You have to add custom_value[0] after custom_key[0] if You use it
now it works thanks to support
hope that help someone

VestaCP api with CURL Giving 500 error

this is my Vesta.php i made this to send the API requests and use it internally
<?php
require 'includes/Config.php';
class VestaAPI {
private $_instance = null;
public static function getInstance() {
if ($_instance == null) {
$_instance = new VestaAPI();
}
return $_instance;
}
public static function runCMD($cmd,$arg1 = "",$arg2 = "",$arg3 = "",$arg4 = "",$arg5 = "",$arg6 = "",$arg7 = "",$arg8 = "",$arg9 = "",$arg10 = ""){
ini_set('max_execution_time', 30);
set_time_limit(30);
// Server credentials
$settings = Config::getInstance()->getSettings();
$vst_hostname = $settings["vestaLogin"]["Host"];
$vst_username = $settings["vestaLogin"]["Username"];
$vst_password = $settings["vestaLogin"]["Password"];
$vst_command = $cmd;
// Prepare POST query
$postvars = array(
'user' => $vst_username,
'password' => $vst_password,
'cmd' => $vst_command,
'arg1' => $arg1,
'arg2' => $arg2
);
$postdata = http_build_query($postvars);
// Send POST query via cURL
$postdata = http_build_query($postvars);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://' . $vst_hostname . ':81/api/');
curl_setopt($curl, CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_LOW_SPEED_LIMIT, 1); // cancel if below 1 byte/second
curl_setopt($ch, CURLOPT_LOW_SPEED_TIME, 30); // for a period of 30 seconds
curl_setopt($post, CURLOPT_AUTOREFERER, true);
curl_setopt($post, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($post, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($post, CURLOPT_TIMEOUT, 30 );
curl_setopt(CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)');
return curl_exec($curl);
}
public static function arrayToXml($array, &$xml){
foreach ($array as $key => $value) {
if(is_array($value)){
if(is_int($key)){
$key = "e";
}
$label = $xml->addChild($key);
arrayToXml($value, $label);
}
else {
$xml->addChild($key, $value);
}
}
}
}
// to get your instance use
?>
but when i try to run this code here (to suspend a website or to unsuspend) i get error 500
<?php
require 'includes/Vesta.php';
if(isset($_POST["username"])){}else{die("ERROR 403");}
$output = VestaAPI::runCMD("v-suspend-user",$_POST["username"]);
if(strstr($output, "Error:")) {die($output);}else{
die("Done!");
}
?>
but if i am getting the data of the account it works i think it must be a time out issue but here is the php error log
2016/02/15 00:53:55 [error] 14102#0: *6 upstream prematurely closed
connection while reading response header from upstream, client:
86.6.39.173, server: testing.DOMAIN.co.uk, request: "POST /suspendUser.php HTTP/1.1", upstream:
"http://45.58.48.103:8080/suspendUser.php", host:
"testing.DOMAIN.co.uk", referrer: "http://testing.DOMAIN.co.uk/"
i have replaced my domain with DOMAIN
Perhaps you run the API request from the same server as the vestacp installation.
This is happening because after suspend/unsuspend user, the vestacp web service is restarted.
You must set $arg2='no', to prevent web service restart, and restart it at a later time.

PHP CURL fetch header from URL and set it to variable

I have a piece of code that trying to call Cloudstack REST API :
function file_get_header($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
$datas = curl_exec($ch);
curl_close($ch);
return $datas;
}
$url = "http://10.151.32.51:8080/client/api?" . $command . "&" . $signature . "&" . $response;
echo $test = file_get_header($url);
And the output is like this :
HTTP/1.1 200 OK Server: Apache-Coyote/1.1 Set-Cookie: JSESSIONID=74A5104C625549EB4F1E8690C9FC8FC1; Path=/client Content-Type: text/javascript;charset=UTF-8 Content-Length: 323 Date: Sun, 01 Jun 2014 20:08:36 GMT
What I am trying to do is how to print JSESSIONID=74A5104C625549EB4F1E8690C9FC8FC1 only and assign it into variable? Thankss,
Here's a method that will parse all your headers into a nice associative array, so you can get any header value by requesting $dictionary['header-name']
$url = 'http://www.google.com';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$datas = curl_exec($ch);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($datas, 0, $header_size);
curl_close($ch);
echo ($header);
$arr = explode("\r\n", $header);
$dictionary = array();
foreach ($arr as $a) {
echo "$a\n\n";
$key_value = explode(":", $a, 2);
if (count($key_value) == 2) {
list($key, $value) = $key_value;
$dictionary[$key] = $value;
}
}
//uncomment the following line to see $dictionary is an associative-array of Header keys to Header values
//var_dump($dictionary);
Simple, just match the part of the string you want with preg_match:
<?php
$text = "HTTP/1.1 200 OK Server: Apache-Coyote/1.1 Set-Cookie: JSESSIONID=74A5104C625549EB4F1E8690C9FC8FC1; Path=/client Content-Type: text/javascript;charset=UTF-8 Content-Length: 323 Date: Sun, 01 Jun 2014 20:08:36 GMT";
preg_match("/JSESSIONID=\\w{32}/u", $text, $match);
echo $result = implode($match);
?>

Using cURL to findout where website redirects?

I'm trying to get server redirect url. I have tried
function http_head_curl($url,$timeout=10)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); // in seconds
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$res = curl_exec($ch);
if ($res === false) {
throw new RuntimeException("cURL exception: ".curl_errno($ch).": ".curl_error($ch));
}
return trim($res);
}
echo http_head_curl("http://www.site.com",$timeout=10);
Result is;
HTTP/1.1 301 Moved Permanently Date: Sun, 12 May 2013 23:34:22 GMT
Server: LiteSpeed Connection: close X-Powered-By: PHP/5.3.23
Set-Cookie: PHPSESSID=0d4b28dd02bd3d8413c92f71253e8b31; path=/;
HttpOnly X-Pingback: http://site.com/xmlrpc.php Content-Type:
text/html; charset=UTF-8 Location: http://site.com/ HTTP/1.1 200 OK
Date: Sun, 12 May 2013 23:34:23 GMT Server: LiteSpeed Connection:
close X-Powered-By: PHP/5.3.23 Set-Cookie:
PHPSESSID=630ed27f107c07d25ee6dbfcb02e8dec; path=/; HttpOnly
X-Pingback: http://site.com/xmlrpc.php Content-Type: text/html;
charset=UTF-8
It shows almost all header information, but not showing where it redirects. How do I get the redirected page url ?
It's the Location header.
$headers = array();
$lines = explode("\n", http_head_curl('http://www.site.com', $timeout = 10));
list($protocol, $statusCode, $statusMsg) = explode(' ', array_shift($lines), 3);
foreach($lines as $line){
$line = explode(':', $line, 2);
$headers[trim($line[0])] = isset($line[1]) ? trim($line[1]) : '';
}
// 3xx = redirect
if(floor($statusCode / 100) === 3)
print $headers['Location'];
$response = curl_exec($ch);
$info = curl_getinfo($ch);
$response_header = substr($response, 0, $info['header_size']);
$response_header = parseHeaders($response_header, 'Status');
$content = substr(response, $info['header_size']);
$url_redirect = (isset($response_header['Location'])) ? $response_header['Location'] : null;
var_dump($url_redirect);
/*
* or you can use http://php.net/http-parse-headers,
* but then need to install http://php.net/manual/en/book.http.php
*/
function parseHeaders($headers, $request_line)
{
$results = array();
$lines = array_filter(explode("\r\n", $headers));
foreach ($lines as $line) {
$name_value = explode(':', $line, 2);
if (isset($name_value[1])) {
$name = $name_value[0];
$value = $name_value[1];
} else {
$name = $request_line;
$value = $name_value[0];
}
$results[$name] = trim($value);
}
return $results;
}
After your CURL request is done, use curl_getinfo with the CURLINFO_EFFECTIVE_URL option. Done.
Compared to the other (complicated) answers, this will provide you the full URL that your request "ended up on".

Categories