Table of Contents
PHP异步调用实现方式" >PHP异步调用实现方式
Home Backend Development PHP Tutorial PHP异步子用实现方式

PHP异步子用实现方式

Jun 13, 2016 pm 01:24 PM
Backend curl fsockopen http php

PHP异步调用实现方式

PHP异步调用实现方式

浏览器和服务器之间只一种面向无连接的HTTP协议进行通讯的,面向无连接的程序的特点是客户端请求服务端,服务端根据请求输出相应的程序,不能保持持久连接。

这样就出现了一个问题,一个客户端的相应服务端可能执行1秒也有可能执行1分钟,这样浏览器就会一直处于等待状态,如果程序执行缓慢,用户可能就没耐心关掉了浏览器。

而有的时候我们不需要关心程序执行的结果,没有必要这样浪费时间和耐心等待,那我们就要想出办法让程序不收等待在后台静默执行。

比如现在有一个场景,给1000个用户发送一封推荐邮件,用户输入或者导入邮件账号了提交服务器执行发送。

复制代码
<?php <span style="color: #800080;">$count=<span style="color: #008080;">count</span>(<span style="color: #800080;">$emailarr</span>);<span style="color: #008000;">
</span><span style="color: #0000ff;">for</span>(<span style="color: #800080;">$i</span>=0;<span style="color: #800080;">$i</span>$count;<span style="color: #800080;">$i</span>++)  
{  
  sendmail(.....);<span style="color: #008000;">//</span><span style="color: #008000;">发送邮件  </span><span style="color: #008000;">
</span>}  <span style="color: #0000ff;">
</span>?>  
Copy after login
复制代码

这段代码用户体验极差,也无法实际运用,首先发送这么多邮件会产生服务器运行超时,其实漫长的用户等待时间会让用户对系统产品怀疑和失去信心。但是用户不需要等待到1000封邮件都发送完毕了才提交发送成功,我们完全可以提交后台后直接给用户提示发送成功,然后让后台程序静默依次发送。

这个时候我们就需要“异步执行”技术来执行代码,异步执行的特点是后台静默执行,用户无需等待代码的执行结果,使用异步执行的好处:

1.摆脱了应用程序对单个任务的依赖性

2.提高了程序的执行效率

3.提高了程序的扩展性

4.在一定场景提高了用户体验

5.因为PHP不支持多线程,使用异步调用的请求多个HTTP的方式达到了程序并行执行效果,但是注意的是请求的HTTP过多的话,会大大加大了系统的开销

?

PHP异步执行的常用方式:

1.客户端页面采用AJAX技术请求服务器

1. 最简单的办法,就是在返回给客户端的HTML代码中,嵌入AJAX调用,或者,嵌入一个img标签,src指向要执行的耗时脚本。
这种方法最简单,也最快。服务器端不用做任何的调用。
但是缺点是,一般来说Ajax都应该在onLoad以后触发,也就是说,用户点开页面后,就关闭,那就不会触发我们的后台脚本了。
而使用img标签的话,这种方式不能称为严格意义上的异步执行。用户浏览器会长时间等待php脚本的执行完成,也就是用户浏览器的状态栏一直显示还在load。
当然,还可以使用其他的类似原理的方法,比如script标签等等


2.popen()函数

resource popen ( string command, string mode );
//打开一个指向进程的管道,该进程由派生给定的 command 命令执行而产生。打开一个指向进程的管道,该进程由派生给定的 command 命令执行而产生。

所以可以通过调用它,但忽略它的输出。

?
pclose(popen(<span style="color: #0000ff;">"/home/xinchen/backend.php &"</span>, <span style="color: #0000ff;">'r'</span>));

  这个方法避免了第一个方法的缺点,并且也很快。但是问题是,这种方法不能通过HTTP协议请求另外的一个WebService,只能执行本地的脚本文件。并且只能单向打开,无法穿大量参数给被调用脚本。

并且如果,访问量很高的时候,会产生大量的进程。如果使用到了外部资源,还要自己考虑竞争。


3.CURL扩展

CURL是一个强大的HTTP命令行工具,可以模拟POST/GET等HTTP请求,然后得到和提取数据,显示在"标准输出"(stdout)上面

复制代码
<span style="color: #800080;">$ch</span> = curl_init();
 
<span style="color: #800080;">$curl_opt</span> = <span style="color: #0000ff;">array</span>(CURLOPT_URL, 'http://www.example.com/backend.php',
                            CURLOPT_RETURNTRANSFER, 1,
                            CURLOPT_TIMEOUT, 1,);
 
curl_setopt_array(<span style="color: #800080;">$ch</span>, <span style="color: #800080;">$curl_opt</span>);
 
curl_exec(<span style="color: #800080;">$ch</span>);
 
curl_close(<span style="color: #800080;">$ch</span>);
Copy after login
复制代码

使用CURL需要设置CUROPT_TIMEOUT为1(最小为1,郁闷)。也就是说,客户端至少必须等待1秒钟。

4.fscokopen()函数

fsockopen是一个非常强大的函数,支持socket编程,可以使用fsockopen实现邮件发送等socket程序等等,使用fcockopen需要自己手动拼接出header部分

官方文档:?http://cn.php.net/fsockopen/

?
<span style="color: #aa7700;">$fp</span> = <span style="color: #ff1493;">fsockopen</span>(<span style="color: #0000ff;">"www.example.com"</span>, 80, <span style="color: #aa7700;">$errno</span>, <span style="color: #aa7700;">$errstr</span>, 30);
<span style="color: #0000ff;">if</span> (!<span style="color: #aa7700;">$fp</span>) {
????<span style="color: #ff1493;">echo</span> <span style="color: #0000ff;">"$errstr ($errno)<br>\n"</span>;
} <span style="color: #0000ff;">else</span> {
????<span style="color: #aa7700;">$out</span> = <span style="color: #0000ff;">"GET /backend.php? / HTTP/1.1\r\n"</span>;
????<span style="color: #aa7700;">$out</span> .= <span style="color: #0000ff;">"Host: www.example.com\r\n"</span>;
????<span style="color: #aa7700;">$out</span> .= <span style="color: #0000ff;">"Connection: Close\r\n\r\n"</span>;
???
????fwrite(<span style="color: #aa7700;">$fp</span>, <span style="color: #aa7700;">$out</span>);
????<span style="color: #008200;">/*忽略执行结果 </span>
????<span style="color: #008200;">while (!feof($fp)) { </span>
????????<span style="color: #008200;">echo fgets($fp, 128); </span>
????<span style="color: #008200;">}*/</span>
????fclose(<span style="color: #aa7700;">$fp</span>);
}
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP: Handling Databases and Server-Side Logic PHP: Handling Databases and Server-Side Logic Apr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

See all articles