


To deal with harsh network environments, set a timeout limit for php-curl to prevent the server from freezing.
The project of digging for foreign goods cannot be filed because there is no company name, so the front-end machine is placed on Alibaba Cloud Hong Kong ECS, and an additional Alibaba Cloud Hangzhou ECS is used to run itcrontab——execute the crawler, save the picture Go to Alibaba Cloud OSS and so on. Recently, I felt that Hangzhou ECS was a bit redundant (there was originally a Hangzhou RDS, but it was moved to Hong Kong RDS), and I planned to remove it, so I moved all the crontabs on Hangzhou ECS back to Hong Kong ECS. This caused a lot of trouble. Fewer problems. What problem did it cause? The core problem is that Hong Kong ECS is in an international network environment, and network jitters often occur when accessing mainland servers, which is very unsolvable. To be more specific, for example, when Hong Kong ECS queries Alibaba Cloud Hangzhou open search
(open search
does not have a Hong Kong node, dear╥﹏╥...), it often reports an error; another example is that Hong Kong ECS captures the image and uploads it to Hangzhou OSS (OSS has a Hong Kong node, but the problem is that there is no image processing service. Don’t you think this is a rip-off?), secondly, it is slow. It often gets stuck for a while before reporting an error, which makes the upload efficiency extremely low (I will tell you Is it because of this reason that you have a backlog of thousands of crawled products waiting to upload pictures before they can be put on the shelves?)
The problem is still easy to solve. The SDK provides timeout configuration. I set the timeout limit a little larger (5 seconds), and basically no errors will be reported. The OSS SDK does not provide this configuration at all. In order to solve this problem, I decided to go deep into the SDK to modify the source code.
OSS’s SDK requests the API through
php-curl
. After investigation, I found that this SDK has a file named requestcore.class.php
that defines a RequestCore
class. Obviously, this The class is responsible for sending the request. Among them, prep_request()
is responsible for configuring curl, and send_request($parse = false)
is responsible for executing curl (that is, actually sending the request). First, let’s take a look at
prep_request()
, which contains two timeout configurations for php-curl
: CURLOPT_TIMEOUT
and CURLOPT_CONNECTTIMEOUT
curl_setopt($ curl_handle, CURLOPT_CONNECTTIMEOUT, 120);CURLOPT_TIMEOUT
is easy to understand, it is the timeout limit of the entire curl request process (http request & response), in seconds, if set to 0, there is no limit. CURLOPT_CONNECTTIMEOUT
is difficult to understand. It is currently confirmed that this is a small part of the curl request process, so it must be set smaller than CURLOPT_TIMEOUT
, otherwise CURLOPT_TIMEOUT
is meaningless. The information on the Internet says this:
Thiswaiting time before initiating a connection
is rather vague. I tend to refer to the time it takes to complete the TCP three-way handshake
process, or in other words, the entire process of TCP three-way handshake
must Complete within CURLOPT_CONNECTTIMEOUT
, otherwise it will time out. TCP three-way handshake
If it cannot be completed within the specified time, it means that the server is in a busy/crash state or the network is abnormal, which is consistent with the scenario mentioned in this article. Based on this conjecture, I set
CURLOPT_CONNECTTIMEOUT
to 3 seconds:
In this way, there is no need to wait 2 minutes when the network jitters (SDK setting TheCURLOPT_CONNECTTIMEOUT
is 120 seconds) before reporting an error. PS: If you want to set the timeout to less than 1 second, you need to use
, but according to Brother Niao, this configuration has bugs and has not been tested. Keep an eye out: "A "Bug" in Curl's millisecond timeout"
The above has introduced how to deal with harsh network environments, set timeout limits for php-curl to prevent the server from freezing, including crontab and image saving. I hope it will be helpful to friends who are interested in PHP tutorials.

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

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.

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

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

TooptimizePHPapplicationsforperformance,usecaching,databaseoptimization,opcodecaching,andserverconfiguration.1)ImplementcachingwithAPCutoreducedatafetchtimes.2)Optimizedatabasesbyindexing,balancingreadandwriteoperations.3)EnableOPcachetoavoidrecompil

DependencyinjectioninPHPisadesignpatternthatenhancesflexibility,testability,andmaintainabilitybyprovidingexternaldependenciestoclasses.Itallowsforloosecoupling,easiertestingthroughmocking,andmodulardesign,butrequirescarefulstructuringtoavoidover-inje

PHP performance optimization can be achieved through the following steps: 1) use require_once or include_once on the top of the script to reduce the number of file loads; 2) use preprocessing statements and batch processing to reduce the number of database queries; 3) configure OPcache for opcode cache; 4) enable and configure PHP-FPM optimization process management; 5) use CDN to distribute static resources; 6) use Xdebug or Blackfire for code performance analysis; 7) select efficient data structures such as arrays; 8) write modular code for optimization execution.

OpcodecachingsignificantlyimprovesPHPperformancebycachingcompiledcode,reducingserverloadandresponsetimes.1)ItstorescompiledPHPcodeinmemory,bypassingparsingandcompiling.2)UseOPcachebysettingparametersinphp.ini,likememoryconsumptionandscriptlimits.3)Ad


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1
Easy-to-use and free code editor

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.
