I am trying to set CURLOPT_PROXY but it doesn't work. Curl is enabled. If I do this by "raw" curl request - everything works.. So? What could be the solution?
$client = new GuzzleHttp\Client();
$res = $client->get('http://www.ipmango.com/api/myip', [
'config' => [
'curl' => [
'CURLOPT_PROXY' => '194.135.220.18:8081',
],
]
]);
echo $res->getBody(); // displays my ip addess, not that what I set.
I spent numerous hours finding out myself that you will also need to set the option CURLOPT_HTTPPROXYTUNNEL to 1. So something like:
<?php
$res = $client->get('http://www.ipmango.com/api/myip', [
'config' => [
'curl' => [
'CURLOPT_PROXY' => '194.135.220.18:8081',
'CURLOPT_HTTPPROXYTUNNEL' => 1,
]
]
]);
GuzzleHttp Client automatically detects if environment variables HTTP_PROXY and HTTPS_PROXY are set.
(see lines 165-175 of \path\to\project\vendor\guzzlehttp\guzzle\src\Client.php)
So set both HTTP_PROXY=http://ip:port and HTTPS_PROXY=https://ip:port as system environment variables. Now restart your command line, and rerun php artisan serve
You may be able to configure authentication for your proxy in the environment variable as well, if it's required
Guzzle docs give info about setting proxy for a single request
$client->request('GET', '/', ['proxy' => 'tcp://localhost:8125']);
http://docs.guzzlephp.org/en/latest/request-options.html#proxy
But you can set it to all requests when initializing client
$client = new Client([
'base_uri' => 'http://doma.in/',
'timeout' => 10.0,
'cookie' => true,
'proxy' => 'tcp://12.34.56.78:3128',
]);
Related
I have a script that uses guzzle to make an API call. The api server checks for headers and it is case sensitive.
Below is an example code of mine
<?php
$headers = [
'set_headers' => [
'Connection' => 'Keep-Alive',
'Accept-Encoding' => ‘gzip’,
'Accept-Language' => ‘en_US’,
'US-Token' => '1f23a-d234s-3s45d-452g',
'AToken' => 'XXXX'
],
];
// Build HTTP request object.
$request = \GuzzleHttp\Psr7\Request( // Throws (they didn't document that properly).
'POST',
'htps://api.website.com/',
$headers,
bodystream() //StreamInterface
);
// Default request options (immutable after client creation).
$_guzzleClient = new \GuzzleHttp\Client([
'handler' => $stack, // Our middleware is now injected.
'allow_redirects' => [
'max' => 8, // Allow up to eight redirects (that's plenty).
],
'connect_timeout' => 30.0, // Give up trying to connect after 30s.
'decode_content' => true, // Decode gzip/deflate/etc HTTP responses.
'timeout' => 240.0, // Maximum per-request time (seconds).
// Tells Guzzle to stop throwing exceptions on non-"2xx" HTTP codes,
// thus ensuring that it only triggers exceptions on socket errors!
// We'll instead MANUALLY be throwing on certain other HTTP codes.
'http_errors' => false,
]);
// Add critically important options for authenticating the request.
$guzzleOptions = [
'cookies' => ($_cookieJar instanceof CookieJar ? $_cookieJar : false),
'verify' => file_exists('/etc/ssl/certs/cacert.pem') ? '/etc/ssl/certs/cacert.pem' : $_verifySSL,
'proxy' => ($_proxy !== null ? $_proxy : null),
'curl' => [
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_2, // Make http client work with HTTP 2/0
CURLOPT_SSLVERSION => 1,
CURLOPT_SSL_VERIFYPEER => false
]
];
// Attempt the request. Will throw in case of socket errors!
$response = $_guzzleClient->send($request, $guzzleOptions); ?>
I tested the same request with cURL and it works perfectly. Is there a way I can rectify this in the guzzle php library, thanks in advance.
I'm setting up Google Cloud Storage bucket CORS configuration using PHP API, but it doesn't seem to work
I read the document given in : https://googleapis.github.io/google-cloud-php/#/docs/google-cloud/v0.96.0/storage/bucket
Here's my Laravel source code:
use Google\Cloud\Core\ServiceBuilder;
...
$projectId = 'myProjectId';
$bucketName = 'myBucketName';
$gcloud = new ServiceBuilder([
'keyFilePath' => 'resources/google-credentials.json',
'projectId' => $projectId
]);
$storage = $gcloud->storage();
$bucket = $storage->bucket($bucketName);
//change bucket configuration
$result = $bucket->update([
'cors' => [
'maxAgeSeconds' => 3600,
'method' => [
"GET","HEAD"
],
"origin" => [
"*"
],
"responseHeader" => [
"Content-Type"
]
]
]);
//print nothing and bucket doesn't changed
dd($bucket->info()['cors']);
After execute this code, the bucket CORS configuration doesn't changed
(My boss don't want me to use gsutil shell command to deal with this)
You're very close! CORS accepts a list, so you'll just need to make a slight modification:
$result = $bucket->update([
'cors' => [
[
'maxAgeSeconds' => 3600,
'method' => [
"GET","HEAD"
],
"origin" => [
"*"
],
"responseHeader" => [
"Content-Type"
]
]
]
]);
Let me know if it helps :).
The only thing I needed to change was when I config disks in laravel, using this code in config/filesystems.php when adding a disk for google:
'google' => [
'driver' => 's3',
'key' => 'xxx',
'secret' => 'xxx',
'bucket' => 'qrnotesfiles',
'base_url'=>'https://storage.googleapis.com'
]
Here is the code example fist get file contents from request:
$file = $request->file('avatar')
second save it into storage:
Storage::disk('google')->put('avatars/' , $file);
Laravel 5.8
I am new to this whole pusher functionality and I've been following this tutorial and trying it out,
Create Web Notifications Using Laravel and Pusher Channels.
I've followed it step-by-step and when I get to the step to manually test the event by visiting the test url, I receive the following exception:
Illuminate \ Broadcasting \ BroadcastException
No message
C:\wamp\www\ares\vendor\laravel\framework\src\Illuminate\Broadcasting\Broadcasters\PusherBroadcaster.php
Here is the code:
$response = $this->pusher->trigger(
$this->formatChannels($channels), $event, $payload, $socket, true
);
if ((is_array($response) && $response['status'] >= 200 && $response['status'] <= 299)
|| $response === true) {
return;
}
throw new BroadcastException( // <-- Exception at this line
is_bool($response) ? 'Failed to connect to Pusher.' : $response['body']
);
}
/**
* Get the Pusher SDK instance.
*
* #return \Pusher\Pusher
*/
public function getPusher()
{
return $this->pusher;
}
}
I've looked at a few other stack overflow articles which talk about changing encrypted: true to encrypted: false but that does not seem to affect anything.
I started working on Laravel 4 days ago and I came across this same problem when I was implementing a real-time chat application. After searching for many days, I discovered that this may vary depending on the version of Laravel you are running. If it is 5.8, you can fix this by adding the following code in the pusher.options array of the file config/broadcasting.php:
'curl_options' => [
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0,
],
After adding this , your pusher array in the config/broadcasting.php should look like this.
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'cluster' => env('PUSHER_APP_CLUSTER'),
'encrypted' => true,
'curl_options' => [
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0,
],
],
],
You can then run php artisan config:cache(which may not be necessary in some cases) and finally run php artisan serve.You can consult your app in the pusher website and see the events you receive after sending your messages.
Hope it helps!!
If you're working on localhost try setting your .env file.
Set:
APP_URL=http://localhost
DB_HOST=localhost
And run
php artisan config:cache
Like i mentioned in a comment before this happens when the whole post goes wrong and wont deliver a response. Thats why the exception in line 116 is raised. I changed it to the domain before!
In my case i followed the code an found the method "createPusherDriver" in "vendor/laravel/framework/src/Illuminate/Broadcasting/BroadcastManager.php". At this place i inserted this
var_dump($config['key']);
var_dump($config['secret']);
var_dump( $config['app_id']);
var_dump($config['options']);
exit;
an noticed that my options still listed "host" => "localhost".
I removed those lines an cleared the config cache by executing php artisan config:cache
On next reload my event was fired an logged in the console.
Worked perfectly up to my Laravel 5.8 version. But encrypted' => true or encrypted' => false did not matter in this case for such Laravel version. But, following PUSHER suggestions, I put to broadcasting: 'useTLS' => true,.
This is the final result to me:
'options' => [
'cluster' => env('PUSHER_APP_CLUSTER'),
'encrypted' => true,
'useTLS' => true,
'curl_options' => [
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0,
],
]
Thanks to dear #Bitart
'useTLS' => true
option solved my issue.
'options' => [
'cluster' => env('PUSHER_APP_CLUSTER'),
'useTLS' => true,
]
I'm trying to delete files from my CloudFlare cache using PHP. Using Guzzle I've done this:
$client = new \GuzzleHttp\Client;
$response = $client->delete('https://api.cloudflare.com/client/v4/zones/myzoneid/purge_cache', [
'query' => [
'files' => 'https://example.com/styles.css,
],
'headers' => [
'X-Auth-Email' => 'myemail',
'X-Auth-Key' => 'myapikey',
],
]);
But when I run this I get an error:
Client error: DELETE https://api.cloudflare.com/client/v4/zones/myzoneid/purge_cache?files=https%3A%2F%2Fexample.com/etc resulted in a 400 Bad Request response: {"success":false,"errors":[{"code":1012,"message":"Request must contain one of \"purge_everything\", \"files\", \"tags\" (truncated...)
I can't get it to work using Postman either. I put in the required headers and try to set a key of files or files[] with the URL but it doesn't work. I've also tried data with raw JSON as the value like {"files":["url"]} (along with a JSON content-type header) but get the same error. It thinks I'm not sending the files key.
The method for purge_cache is POST instead of DELETE (Source: https://api.cloudflare.com/#zone-purge-files-by-url).
The payload is not sent as 'query', but as 'json'.
Files should be an array, not a string.
So the correct syntax should be....
$client = new \GuzzleHttp\Client;
$response = $client->post('https://api.cloudflare.com/client/v4/zones/myzoneid/purge_cache', [
'json' => [
'files' => ['https://example.com/styles.css'],
],
'headers' => [
'X-Auth-Email' => 'myemail',
'X-Auth-Key' => 'myapikey',
],
]);
I have a problem with translating curl to guzzle request.
In docs to create a user i just need to post:
$ curl -XPOST -d '{"username":"test", "password":"super_secret_password"}' -H "Content-Type:application/json" -u "$CLOUDMQTT_USER:$CLOUDMQTT_PASSWORD" https://api.cloudmqtt.com/user
In my project I cannot use curl, so i use guzzle:
$client = new Client();
$res = $client->post('https://api.cloudmqtt.com/user', ['auth' => ['xxx', 'xxx'], 'body' => ["username"=>"user", "password"=>"super_secret_password"]]);
And user is created, I can see new user on the users list on panel, but server is responsing with 500 when creating the user. What am I doing wrong? Maybe my guzzle request is wrong format? I have no idea
https://www.cloudmqtt.com/docs-api.html link to API
This will match up your Guzzle request to the curl request, although I can't say for sure that will solve your 500 error:
$client = new Client([
'headers' => [ 'Content-Type' => 'application/json' ]
]);
$response = $client->post('https://api.cloudmqtt.com/user',
[
'auth' => ['xxx', 'xxx'],
'body' => json_encode(
[
"username"=>"user",
"password"=>"super_secret_password"
]
)
]
);
The differences here include setting the Content-Type header and also encoding the body to json instead of an array (which may not have an effect here?).
EDIT:
It looks like the json parameter will automatically set the header and json_encode the body for you:
$client = new Client();
$response = $client->post('https://api.cloudmqtt.com/user',
[
'auth' => ['xxx', 'xxx'],
'json' =>
[
"username"=>"user",
"password"=>"super_secret_password"
]
]
);
Docs