本文目錄一覽:
php中怎麼實現後台執行??
用 ajax 實現異步加載
然後
i
gnore_user_abort(true);
//即使Client斷開(如關掉瀏覽器),PHP腳本也可以繼續執行.
set_time_limit(0);
while(1) {
$fp = fopen(‘time_task.txt’,”a+”);
$str = date(“Y-m-d h:i:s”).”\n\r”;
fwrite($fp,$str);
fclose($fp);
sleep(5); //半小時執行一次
}
php如何實現腳本異步執行的方法具體分析
php語言得用fsockopen()函數,實現腳本異步運行,代碼如下
異步請求函數(用debug參數若為true則為用為調試,開啟調試可以看到異步的執行情況,但是失去異步的效果)
main.php
?php
/**
* 異步請求
* @copyright Copyright (c) Hangzhou Technology Co.,Ltd. ()
* @author $Author: juny $
* @version $Id: main.php 332 2018-09-23 09:15:08Z juny $
*/
function request_by_fsockopen($url,$post_data=array(),$debug=false){
$url_array = parse_url($url);
$hostname = $url_array[‘host’];
$port = isset($url_array[‘port’])? $url_array[‘port’] : 80;
@$requestPath = $url_array[‘path’] .”?”. $url_array[‘query’];
$fp = fsockopen($hostname, $port, $errno, $errstr, 10);
if (!$fp) {
echo “$errstr ($errno)”;
return false;
}
$method = “GET”;
if(!empty($post_data)){
$method = “POST”;
}
$header = “$method $requestPath HTTP/1.1\r\n”;
$header.=”Host: $hostname\r\n”;
if(!empty($post_data)){
$_post = strval(NULL);
foreach($post_data as $k = $v){
$_post[]= $k.”=”.urlencode($v);//必須做url轉碼以防模擬post提交的數據中有符而導致post參數鍵值對紊亂
}
$_post = implode(”, $_post);
$header .= “Content-Type: application/x-www-form-urlencoded\r\n”;//POST數據
$header .= “Content-Length: “. strlen($_post) .”\r\n”;//POST數據的長度
$header.=”Connection: Close\r\n\r\n”;//長連接關閉
$header .= $_post; //傳遞POST數據
}else{
$header.=”Connection: Close\r\n\r\n”;//長連接關閉
}
fwrite($fp, $header);
//—————–調試代碼區間—————–
//注如果開啟下面的注釋,異步將不生效可是方便調試
if($debug){
$html = ”;
while (!feof($fp)) {
$html.=fgets($fp);
}
echo $html;
}
//—————–調試代碼區間—————–
fclose($fp);
}
$data=array(‘name’=’guoyu’,’pwd’=’123456′);
$url=”;
request_by_fsockopen($url,$data,true);//
other.php
?php
header(“content-type:text/html;charset=utf-8”);
//error_reporting(0);
//ini_set(‘html_errors’,false);
//ini_set(‘display_errors’,false);
$name = isset($_POST[‘name’])?$_POST[‘name’]:”;
$pwd = isset($_POST[‘pwd’])?$_POST[‘pwd’]:”;
echo $name.$pwd;
echo ‘success ok’;
die;
?
使用實例:
[運行的main.php主腳本文件]
$data=array(‘name’=’guoyu’,’pwd’=’123456′);
$url=”;
request_by_fsockopen($url,$data,true);//把應用B的用戶表異步-同步數據
[導步執行文件other.php]
在other.php中便可以用$_POST接收main.php提交過來的參數,從而進行下一步操作
以上就是php如何實現腳本異步執行的方法具體分析的詳細內容.
PHP 怎樣異步處理
利用php的系統調用,開啟新的進程來實現。
php
提供了fsockopen函數,此函數的功能為初始化一個套接字連接到指定主機,默認情況下將以阻塞模式開啟套接字連接。當然你可以通過stream_set_blocking()將它轉換到非阻塞模式。這是關鍵。所以,思路就是:開啟一個非阻塞的套接字連接到本機,本機收到之後作一些耗時處理。
PHP後台/異步運行如何解決
具體代碼如下:
?php
$ch = curl_init();
$timeout = 5;
curl_setopt ($ch, CURLOPT_URL, ”);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);
echo $file_contents;
?
PHP 獨特的語法混合了C、Java、Perl以及PHP自創的語法。
它可以比CGI或者Perl更快速地執行動態網頁。用PHP做出的動態頁面與其他的編程語言相比,PHP是將程序嵌入到HTML(標準通用標記語言下的一個應用)文檔中去執行,
執行效率比完全生成HTML標記的CGI要高許多;
PHP還可以執行編譯後代碼,編譯可以達到加密和優化代碼運行,使代碼運行更快。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/311954.html