Catch ConnectException from Guzzle - php

I am trying to retrieve the error message that comes with a GuzzleHttp\Exception\ConnectException in Guzzle 6.
I read that in older version this could be achieved with getResponse().
However, the method now returns null by default.
This is my code:
$responses = Pool::batch($client, $requests($this->list), array(
'concurrency' => 15,
));
foreach ($responses as $event) {
$classname = get_class($event);
$raw = print_r($event,1);
if ($classname == "GuzzleHttp\Exception\ConnectException") {
$response = json_encode((string)$event->getResponse());
}
echo $response;
}
$response is empty.
However, $raw contains these lines:
[0] => GuzzleHttp\Exception\ConnectException Object
(
[request:GuzzleHttp\Exception\RequestException:private] => GuzzleHttp\Psr7\Request Object
(
[method:GuzzleHttp\Psr7\Request:private] => GET
....
)
[response:GuzzleHttp\Exception\RequestException:private] =>
[handlerContext:GuzzleHttp\Exception\RequestException:private] => Array
(
[errno] => 6
[error] => Could not resolve host: mydomain.it
[url] => http://mydomain.it/
[content_type] =>
[http_code] => 0
....
How do I retrieve the "Could not resolve host: mydomain.it" message?
All I found was "you need to catch the error". But how when I am using Pool::batch and everything already is in my responses array?

Use $event->getMessage() (Exception Message) instead of $event->getResponse() because there is no connection, so no response

Related

Can't get basic remote API value shown in PHP

This is my code, where I am trying to show the values from the remote API which I am trying to fetch via a .php file in Wordpress.
<?php
try {
$response = wp_remote_get( 'MYURLHERE', array(
'headers' => array(
'Accept' => 'application/json',
)
) );
if ( ( !is_wp_error($response)) && (200 === wp_remote_retrieve_response_code( $response ) ) ) {
$result = json_decode( wp_remote_retrieve_body( $response, true) );
echo $result['data']['0']['id'];
}
} catch( Exception $ex ) {
//Handle Exception.
}
?>
Getting the following error:
Fatal error: Uncaught Error: Cannot use object of type stdClass as array
What am I doing wrong?
This should be the array:
Array
(
[data] => Array
(
[0] => Array
(
[id] => 124
[name] => MyName
[supertype] => Mso
In PHP manual, you can see the parameters of JSON Function: https://www.php.net/manual/en/function.json-decode.php
This json_decode line of code is wrong, here's the fix:
$result = json_decode( wp_remote_retrieve_body( $response), true );
You must be outputting a different variable than the one you are getting a error for.
This is because you use json_decode() without any parameters.
This means it will be outputted as an object, not an array.
So the example output you show must originate from some other place than the $result you are trying to echo.

Async Upload Using Curl in PHP - curl_multi_exec()

I'm trying to figure out for days how would it be possible if at all, to upload multiple files parallel using PHP.
given I have a class called Request with 2 methods register() and executeAll():
class Request
{
protected $curlHandlers = [];
protected $curlMultiHandle = null;
public function register($url , $file = [])
{
if (empty($file)) {
return;
}
// Register the curl multihandle only once.
if (is_null($this->curlMultiHandle)) {
$this->curlMultiHandle = curl_multi_init();
}
$curlHandler = curl_init($url);
$options = [
CURLOPT_ENCODING => 'gzip',
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $file,
CURLOPT_USERAGENT => 'Curl',
CURLOPT_HTTPHEADER => [
'Content-Type' => 'multipart/form-data; boundry=-------------'.uniqid()
]
];
curl_setopt_array($curlHandler, $options);
$this->curlHandlers[] = $curlHandler;
curl_multi_add_handle($this->curlMultiHandle, $curlHandler);
}
public function executeAll()
{
$responses = [];
$running = null;
do {
curl_multi_exec($this->curlMultiHandle, $running);
} while ($running > 0);
foreach ($this->curlHandlers as $id => $handle) {
$responses[$id] = curl_multi_getcontent($handle);
curl_multi_remove_handle($this->curlMultiHandle, $handle);
}
curl_multi_close($this->curlMultiHandle);
return $responses;
}
}
$request = new Request;
// For this example I will keep it simple uploading only one file.
// that was posted using a regular HTML form multipart
$resource = $_FILES['file'];
$request->register('http://localhost/upload.php', $resource);
$responses = $request->executeAll(); // outputs an empty subset of array(1) { 0 => array(0) { } }
Problem:
Can't figure out why on upload.php (the script which is my endpoint url on the register method) $_FILES is always an empty array:
upload.php:
<?php
var_dump($_FILES); // outputs an empty array(0) { }
Things I've already tried:
prefixing the data with #, like so:
$options = [
CURLOPT_ENCODING => 'gzip',
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => ['file' => '#'.$file['tmp_name']],
CURLOPT_USERAGENT => 'Curl',
CURLOPT_HTTPHEADER => [
'Content-Type' => 'multipart/form-data; boundry=-------------'.uniqid()
]
];
That unfortunately did not work.
What am I doing wrong ?
how could I get the file resource stored in $_FILES global on the posted script (upload.php) ?
Further Debug Information:
on upload.php print_r the headers I get as response the following:
array(1) {
[0]=>
string(260) "Array
(
[Host] => localhost
[User-Agent] => Curl
[Accept] => */*
[Accept-Encoding] => gzip
[Content-Length] => 1106
[Content-Type] => multipart/form-data; boundary=------------------------966fdfac935d2bba
[Expect] => 100-continue
)
"
}
print_r($_POST) on upload.php gives the following response back:
array(1) {
[0]=>
string(290) "Array
(
[name] => example-1.jpg
[encrypted_name] => Nk9pN21IWExiT2VlNnpHU3JRRkZKZz09.jpg
[type] => image/jpeg
[extension] => jpg
[tmp_name] => C:\xampp\tmp\php77D7.tmp
[error] => 0
[size] => 62473
[encryption] => 1
[success] =>
[errorMessage] =>
)
"
}
I appreciate any answer.
Thanks,
Eden
Can't figure out why on upload.php (the script which is my endpoint url on the register method) $_FILES is always an empty array - your first problem is that you override libcurl's boundary string with your own, but you have curl generate the multipart/form-data body automatically, meaning curl generates another random boundary string, different from your own, in the actual request body, meaning the server won't be able to parse the files. remove the custom boundary string from the headers (curl will insert its own if you don't overwrite it). your second problem is that you're using $_FILES wrong, you need to extract the upload name if you wish to give it to curl, and you need to convert the filenames to CURLFile objects to have curl upload them for you. another problem is that your script will for no good reason use 100% cpu while executing the multi handle, you should add a curl_multi_select to prevent choking an entire cpu core. for how to handle $_FILES, see http://php.net/manual/en/features.file-upload.post-method.php
, for how to use CURLFile, see http://php.net/manual/en/curlfile.construct.php and for how to use curl_multi_select, see http://php.net/manual/en/function.curl-multi-select.php

PHP SOAP Request via SOAPClient to SAP - params missing error

I am doing a PHP SOAP Request as follows (my code, location removed as I'm not allow to publish)
try {
$location = "http://myUrltoWSDLhere";
$client = new SoapClient($location,
array(
'soap_version' => SOAP_1_1,
'login' => 'myuser',
'password' => 'mypass'
));
$params = array(array('BUKRS'=> 1));
$x = $client->ZIbFtiWsCredPosToWeb( $params );
print_r($x);
} catch (Exception $e) {
echo $e->getMessage();
}
I've been trying countless combinations how to pass the params to my method and I am doing a print_r($x) and gives me the below output.
stdClass Object ( [EBkpf] => stdClass Object ( ) [EMsgnr] => 6 [EMsgtxt] => BUKRS is missing [EMsgtyp] => E [ESstMon] => 00000000000000000000 )
Important: SoapClient getTypes returns the following for this method and the IBukrs is the field I am trying to pass data to. In SAP the Company Code is "BUKRS" so I had tried BUKRS and IBukrs and also Bukrs.
Any help would be greatly appreciated!!
[43] => struct ZIbFtiWsCredPosToWeb {
int IAnz;
char1 IAp;
char4 IBukrs;
ZibSstGjahr IGjahr;
ZibSstCredTt IKreditor;
char1 IOp;
numeric20 ISstMon;
}
WSDL Content: http://pastebin.com/fU5PhD9B

PayPal API: Exception: 401 when accessing https://api.sandbox.paypal.com/v1/oauth2/token

The specific 401 error message I get is:
"error":"invalid_client","error_description":"The client credentials are invalid"}"
This error isn't listed anywhere in the PayPal documentation. I am certain I am using the test credentials and using the correct sandbox endpoint. The error occurs when I attempt to get an access token.
This is the class where the access token is retrieved:
private function _generateAccessToken($config) {
$base64ClientID = base64_encode($this->clientId . ":" . $this->clientSecret);
$headers = array(
"User-Agent" => PPUserAgent::getValue(RestHandler::$sdkName, RestHandler::$sdkVersion),
"Authorization" => "Basic " . $base64ClientID,
"Accept" => "*/*"
);
$httpConfiguration = $this->getOAuthHttpConfiguration($config);
$httpConfiguration->setHeaders($headers);
$connection = PPConnectionManager::getInstance()->getConnection($httpConfiguration, $config);
//print_r($connection); die;
$res = $connection->execute("grant_type=client_credentials");
$jsonResponse = json_decode($res, true);
if($jsonResponse == NULL ||
!isset($jsonResponse["access_token"]) || !isset($jsonResponse["expires_in"]) ) {
$this->accessToken = NULL;
$this->tokenExpiresIn = NULL;
$this->logger->warning("Could not generate new Access token. Invalid response from server: " . $jsonResponse);
} else {
$this->accessToken = $jsonResponse["access_token"];
$this->tokenExpiresIn = $jsonResponse["expires_in"];
}
$this->tokenCreateTime = time();
return $this->accessToken;
}
This is the $connection variable I have when I print_r (I removed the authorization string):
PayPal\Core\PPHttpConnection Object( [httpConfig:PayPal\Core\PPHttpConnection:private] => PayPal\Core\PPHttpConfig Object ( [headers:PayPal\Core\PPHttpConfig:private] => Array ( [User- Agent] => PayPalSDK/rest-sdk-php 0.6.0 (lang=PHP;v=5.4.21;bit=64;os=Linux_2.6.18- 308.16.1.el5;machine=x86_64;openssl=0.9.8e-fips-rhel5;curl=7.24.0) [Authorization] => Basic REMOVED AUTHORIZATION STRING == [Accept] => */* ) [curlOptions:PayPal\Core\PPHttpConfig:private] => Array ( [32] => 3 [78] => 30 [19913] => 1 [13] => 60 [10018] => PayPal-PHP-SDK [10023] => Array ( ) [81] => 2 [64] => 1 ) [url:PayPal\Core\PPHttpConfig:private] => https://api.sandbox.paypal.com/v1/oauth2/token [method:PayPal\Core\PPHttpConfig:private] => POST [retryCount:PayPal\Core\PPHttpConfig:private] => 1 ) [logger:PayPal\Core\PPHttpConnection:private] => PayPal\Core\PPLoggingManager Object ( [loggerName:PayPal\Core\PPLoggingManager:private] => PayPal\Core\PPHttpConnection [isLoggingEnabled:PayPal\Core\PPLoggingManager:private] => 1 [loggingLevel:PayPal\Core\PPLoggingManager:private] => 3 [loggerFile:PayPal\Core\PPLoggingManager:private] => PayPal.log ))
As far I can tell, I have correct credentials, correct endpoint, not sure what else it could be?
A HTTP401 on /token is returned if the client_id/secret aren’t recognized (either the wrong credentials for the environment, or the credentials aren’t active).
Can you run a test via cURL to rule out any environment / code-specific issues?
curl -v -u "client_id:secret" "https://api.sandbox.paypal.com/v1/oauth2/token" -X POST -d "response_type=token&grant_type=client_credentials"
(Replace client_id and secret above with your own)
Make sure payment $config mode is Sandbox and clientId and clientSecret keys are Sandbox same time.

Posting photo via Facebook graph no longer working

I'm trying to post a photo using the php-sdk - all was working for months successfully but all of the sudden no dice.
Other functions are still working with the same code base (ie: posting messages to wall) - its just the posting of photos that broke on my side.
try {
$data = $facebook->api('/me/photos', 'post', $args);
} catch (FacebookApiException $e) {
print_r($e);}
Is dumping:
FacebookApiException Object ( [result:protected] => Array ( [error_code] => 3 [error] => Array ( [message] => No URL set! [type] => CurlException ) ) [message:protected] => No URL set! [string:private] => [code:protected] => 3 [file:protected] => /locationofmy/base_facebook.php [line:protected] => 818 [trace:private] => Array ( [0] => Array [..............]
From the FB php-sdk lines 818:
if ($result === false) {
$e = new FacebookApiException(array(
'error_code' => curl_errno($ch),
'error' => array(
'message' => curl_error($ch),
'type' => 'CurlException',
),
));
curl_close($ch);
throw $e;
}
curl_close($ch);
return $result;
}
This was working for a long time - has something changed on Facebooks side?
EDIT: php-sdk version: 3.1.1
EDIT 2:
$tag = array(
'tag_uid' => 'acct_num',
'x' => 0,
'y' => 0
);
$tags[] = $tag;
$args = array(
'message' => $item_description,
'image' => '#' . realpath($temp_path . $tempFile),
'tags' => $tags,
);
Probably that the file doesnt exist, or the file system can't serve it anymore. Can you confirm "$temp_path . $tempFile" - the error is no URL, usually that means no real path to image. I suspect, that the images are missing and/or your servers filled up and no local images are saving. (Yes, this has happened to me before!)
Try changing the image to source. I believe this should fix your issue.
The Facebook API requires a source field but I did not see anything about an image field.
You may also have to pass the actual file contents instead of the real_path (based on the example). Or, alternatively, pass an external URL (based on my understanding of the documentation).
Source: https://developers.facebook.com/docs/reference/api/photo/
Example: https://developers.facebook.com/blog/post/498/

Categories