search
HomeBackend DevelopmentPHP TutorialPHP network request plug-in Guzzle use

When writing background code, it is inevitable to interact with other third-party interfaces, such as sending template messages to the service account. Sometimes more than 100,000 messages may need to be sent. At this time, you have to consider using asynchronous and "multi-threaded" network requests.

Today I recommend a Guzzle plug-in to PHP engineers.

Guzzle

Guzzle is an HTTP client for PHP, used to easily send requests and integrate into our WEB services.

The interface is simple: construct query statements, POST requests, split upload and download large files, use HTTP cookies, upload JSON data, etc.

The same interface is used to send synchronous or asynchronous requests.

Use the PSR-7 interface to request, respond, and offload, allowing you to use other compatible PSR-7 class libraries to develop together with Guzzle.

Abstracts the underlying HTTP transport, allowing you to change the environment and other code, such as: not heavily dependent on cURL and PHP streams or sockets, non-blocking event loops.

Middleware systems allow you to create client-side behaviors.

Installing Guzzle

This article combines the Laravel project to introduce the basic use of Guzzle, so it is perfect to use composer to install Guzzle, and the Guzzle official website also recommends using composer to install.

composer require guzzlehttp/guzzle:~6.0
// 或者
php composer.phar require guzzlehttp/guzzle:~6.0

Send a simple POST request

Access third-party interfaces, basically POST requests are the main ones. If you want to make a simple intelligent chat tool, you can use the Turing Robot API to send a POST request to get the automatic answer content. Go directly to the code:

<?php
namespace App\Http\Controllers;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
class GuzzleUseController extends Controller {
    public function tuling(Request $request) {
        $params = [
            &#39;key&#39; => &#39;*****&#39;,
            &#39;userid&#39; => &#39;yemeishu&#39;
        ];
        $params[&#39;info&#39;] = $request->input(&#39;info&#39;, &#39;你好吗&#39;);
        $client = new Client();
        $options = json_encode($params, JSON_UNESCAPED_UNICODE);
        $data = [
            &#39;body&#39; => $options,
            &#39;headers&#39; => [&#39;content-type&#39; => &#39;application/json&#39;]
        ];
        // 发送 post 请求
        $response = $client->post(&#39;http://www.tuling123.com/openapi/api&#39;, $data);
        $callback = json_decode($response->getBody()->getContents());
        return $this->output_json(&#39;200&#39;, &#39;测试图灵机器人返回结果&#39;, $callback);
    }
}

Guzzle client->post function is still very simple Yes, only the access interface and request parameters are required. The parameters mainly include: body, headers, query, etc. For details, please refer to

http://guzzle-cn.readthedocs.io/zh_CN /latest/quickstart.html#id8

Test:

PHP network request plug-in Guzzle use

PHP network request plug-in Guzzle use

Note: Turing robot is still It's very smart. It can identify the context based on the same userid and achieve intelligent chat.

Send an asynchronous POST request

In PHP development, it is mainly a "process-oriented" development method, but when requesting a third-party interface, sometimes There is no need to wait for the third-party interface to return results before continuing execution. For example, when the user's purchase is successful, we need to send a post request to the SMS interface, and the SMS platform will send a text message to the user to inform the user that the payment was successful, because this type of "reminder message" is an "additional additional function" and is not required. "Know" whether the reminder was sent successfully when the user pays.

At this time, you can use Guzzle's asynchronous request function and look at the code directly:

public function sms(Request $request) {
    $code = $request->input(&#39;code&#39;);
    $client = new Client();
    $sid = &#39;9815b4a2bb6d5******8bdb1828644f2&#39;;
    $time = &#39;20171029173312&#39;;
    $token = &#39;af8728c8bc*******12019c680df4b11c&#39;;

    $sig =  strtoupper(md5($sid.$token.$time));

    $auth = trim(base64_encode($sid . ":" . $time));

    $params = [&#39;templateSMS&#39; => [
            &#39;appId&#39; => &#39;12b43**********0091c73c0ab&#39;,
            &#39;param&#39; => "coding01,$code,30",
            &#39;templateId&#39; => &#39;3***3&#39;,
            &#39;to&#39; => &#39;17689974321&#39;
        ]
    ];
    $options = json_encode($params, JSON_UNESCAPED_UNICODE);
    $data = [
        &#39;query&#39; => [
            &#39;sig&#39; => $sig
        ],
        &#39;body&#39; => $options,
        &#39;headers&#39; => [
            &#39;content-type&#39; => &#39;application/json&#39;,
            &#39;Authorization&#39; => $auth
        ]
    ];

    // 发送 post 请求
    $promise = $client->requestAsync(&#39;POST&#39;, &#39;https://api.ucpaas.com/2014-06-30/Accounts/9815b4a2bb6d5******8bdb1828644f2/Messages/templateSMS&#39;, $data);

    $promise->then(
        function (ResponseInterface $res) {
            Log::info(&#39;---&#39;);
            Log::info($res->getStatusCode() . "\n");
            Log::info($res->getBody()->getContents() . "\n");
        },
        function (RequestException $e) {
            Log::info(&#39;-__-&#39;);
            Log::info($e->getMessage() . "\n");
        }
    );
    $promise->wait();

    return $this->output_json(&#39;200&#39;, &#39;测试短信 api&#39;, []);
}

Return the interface data first:

PHP network request plug-in Guzzle use

Then output Log:

[2017-10-29 09:53:14] local.INFO: ---  
[2017-10-29 09:53:14] local.INFO: 200
  
[2017-10-29 09:53:14] local.INFO: {"resp":{"respCode":"000000","templateSMS":{"createDate":"20171029175314","smsId":"24a93f323c9*****8608568"}}}

The last SMS message received:

PHP network request plug-in Guzzle use

Send multi-threaded asynchronous POST request

「Send "Multi-threaded asynchronous POST request" is used in many occasions. For example: Double Eleven is coming soon. You can do some activities to give back to old users. This requires batch push of a template message to old users to tell them which activities to participate in. of. At this time, you need to use multi-threaded asynchronous request WeChat official account interface.

Go directly to the code:

public function send($templateid, $openid, $url, $data) {
        $client = $this->bnotice->getHttp()->getClient();

        $requests = function ($open_ids) use ($templateid, $url, $data) {
            foreach($open_ids as $v){
                try {
                    yield $this->bnotice
                        ->template($templateid)
                        ->to($v)
                        ->url($url)
                        ->data($data)
                        ->request();
                } catch(Exception $e) {
                    Log::error(&#39;sendtemplate:&#39;.$e->getMessage());
                }
            }
        };

        $pool = new Pool($client, $requests($openid), [
            &#39;concurrency&#39; => 16,
            &#39;fulfilled&#39; => function ($response, $index) {
            },
            &#39;rejected&#39; => function ($reason, $index) {
            },
        ]);

        $promise = $pool->promise();

        $promise->wait();
    }

The request method:

public function request($data = [])
    {
        $params = array_merge([
            &#39;touser&#39; => &#39;&#39;,
            &#39;template_id&#39; => &#39;&#39;,
            &#39;url&#39; => &#39;&#39;,
            &#39;topcolor&#39; => &#39;&#39;,
            &#39;miniprogram&#39; => [],
            &#39;data&#39; => [],
        ], $data);
        
        $required = [&#39;touser&#39;, &#39;template_id&#39;];

        foreach ($params as $key => $value) {
            if (in_array($key, $required, true) && empty($value) && empty($this->message[$key])) {
                throw new InvalidArgumentException("Attribute &#39;$key&#39; can not be empty!");
            }

            $params[$key] = empty($value) ? $this->message[$key] : $value;
        }

        $params[&#39;data&#39;] = $this->formatData($params[&#39;data&#39;]);

        $this->message = $this->messageBackup;

        $options = json_encode ( $params,  JSON_UNESCAPED_UNICODE);
        $data = [
            &#39;query&#39; => [
                &#39;access_token&#39; => $this->getAccessToken()->getToken()
            ],
            &#39;body&#39; => $options,
            &#39;headers&#39; => [&#39;content-type&#39; => &#39;application/json&#39;]
        ];
        return function() use ($data) {
            return $this->getHttp()->getClient()->requestAsync(&#39;POST&#39;, $this::API_SEND_NOTICE, $data);
        };
    }

Guzzle multi-threaded asynchronous request prototype function, using the GuzzleHttp\Pool object

use GuzzleHttp\Pool;use GuzzleHttp\Client;use GuzzleHttp\Psr7\Request;$client = new Client();$requests = function ($total) {
    $uri = &#39;http://127.0.0.1:8126/guzzle-server/perf&#39;;
    for ($i = 0; $i < $total; $i++) {
        yield new Request(&#39;GET&#39;, $uri);
    }};$pool = new Pool($client, $requests(100), [
    &#39;concurrency&#39; => 5,
    &#39;fulfilled&#39; => function ($response, $index) {
        // this is delivered each successful response
    },
    &#39;rejected&#39; => function ($reason, $index) {
        // this is delivered each failed request
    },]);// Initiate the transfers and create a promise$promise = $pool->promise();// Force the pool of requests to complete.$promise->wait();

Summary

With Guzzle, it is greatly convenient for us to request third-party interfaces concurrently and asynchronously. If time permits, we can take a look at the Guzzle source code to see how it is implemented.

Recommended tutorial: "PHP Tutorial"

The above is the detailed content of PHP network request plug-in Guzzle use. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:jianshu. If there is any infringement, please contact admin@php.cn delete
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment