用stream_系列函数实现远程文件本地化,如何防止卡死
还是我前两天写的代码,已经用于采集内容了,今天用来改进采集到的内容中的图片等远程文件的本地化,有时候还是会卡死,高手看看如何能防止卡死。
代码如下,这个代码还是提供两种方式实现本地化进行比较,时事证明这种流方式实现效率是提高了。
- PHP code
<!--Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--><?php $dir = str_replace('\\', '/', dirname(__FILE__)) . '/';$timeStart = microtime(true);$data = '';$urls = array('http://www.jxcms.com/upload/2011/0518/0337319304.jpg', 'http://www.jxcms.com/upload/2011/0310/0951568835.jpg', 'http://www.tzksgs.com/upload/banner1.jpg', 'http://www.tzksgs.com/upload/banner2.jpg');foreach($urls as $url) { copy($url, $dir . 'a_' . basename($url));}$timeEnd = microtime(true);echo sprintf("Spend time: %s second(s)\n", $timeEnd - $timeStart), '<br>';$timeStart = microtime(true);function getMoreContent($urls) { $timeout = 30; $rs = array(); $sockets = array(); $userAgent = $_SERVER['HTTP_USER_AGENT']; foreach($urls as $id => $url) { $tmp = parse_url($url); $host = $tmp['host']; $path = isset($tmp['path'])?$tmp['path']:'/'; empty($tmp['query']) or $path .= '?' . $tmp['query']; if (empty($tmp['port'])) { $port = $tmp['scheme'] == 'https'?443:80; } else $port = $tmp['port']; $fp = stream_socket_client("$host:$port", $errno, $errstr, $timeout); if ($fp) { $rs[$id] = ''; $sockets[$id] = $fp; fwrite($fp, "GET $path HTTP/1.1\r\nHost: $host\r\nUser-Agent: $userAgent\r\nConnection: Close\r\n\r\n"); } } // Now, wait for the results to come back in while (count($sockets)) { $read = $sockets; // This is the magic function - explained below if (stream_select($read, $write = null, $e = null, $timeout)) { // readable sockets either have data for us, or are failed connection attempts foreach ($read as $r) { $id = array_search($r, $sockets); $data = fread($r, 8192); if (strlen($data) == 0) { fclose($r); $tmp = explode("\r\n\r\n", $rs[$id], 2); $rs[$id] = strpos($tmp[0], '200')?$tmp[1]:''; unset($sockets[$id]); } else $rs[$id] .= $data; } } } return $rs;}$rs = getMoreContent($urls);foreach($rs as $k => $v) { @file_put_contents($dir . 'b_' . basename($urls[$k]), $v);}$timeEnd = microtime(true);echo sprintf("Spend time: %s second(s)\n", $timeEnd - $timeStart);?>
------解决方案--------------------
由于php没有计时器,所以你不可能中断一个没有中断接口的函数的执行
所以底层函数都只适合于理想的条件下
我依然建议你使用多道的curl来完成你的工作
- PHP code
$urls = array( 'http://www.jxcms.com/upload/2011/0518/0337319304.jpg', 'http://www.jxcms.com/upload/2011/0310/0951568835.jpg', 'http://www.tzksgs.com/upload/banner1.jpg', 'http://www.tzksgs.com/upload/banner2.jpg');$mh = curl_multi_init();foreach ($urls as $i => $url) { $conn[$i] = curl_init($url); curl_setopt($conn[$i], CURLOPT_RETURNTRANSFER,1); curl_multi_add_handle($mh, $conn[$i]);}do { curl_multi_exec($mh, $active); //在这个循环中,你有机会中断程序的执行。curl_getinfo提供了连接的各种信息}while($active);foreach ($urls as $i => $url) { $fn = basename($url); file_put_contents($fn, curl_multi_getcontent($conn[$i])); curl_close($conn[$i]);}<div class="clear"> </div>

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

Tostoreauser'snameinaPHPsession,startthesessionwithsession_start(),thenassignthenameto$_SESSION['username'].1)Usesession_start()toinitializethesession.2)Assigntheuser'snameto$_SESSION['username'].Thisallowsyoutoaccessthenameacrossmultiplepages,enhanc

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.


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

WebStorm Mac version
Useful JavaScript development tools

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),

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version
Recommended: Win version, supports code prompts!
