国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Backend Development PHP Tutorial PHP writing daemon (Daemon)_PHP tutorial

PHP writing daemon (Daemon)_PHP tutorial

Jul 15, 2016 pm 01:21 PM
php 。 Write Backstage control yes of process

Daemon is a special process running in the background. It is independent of the control terminal and periodically performs some task or waits for some event to occur. Daemon is a very useful process. PHP can also implement the function of daemon process.

1. Basic concepts

Process

Each process has a parent process. When the child process exits, the parent process can get the exit status of the child process.

Process Group

Each process belongs to a process group, and each process group has a process group number, which is equal to the PID of the process group leader

2. Key points of daemon programming

Daemon is a special process running in the background. It is independent of the control terminal and periodically performs some task or waits for some event to occur. Daemon is a very useful process. PHP can also implement the function of daemon process.

1. Basic concepts

Process

Each process has a parent process. When the child process exits, the parent process can get the exit status of the child process.

Process Group

Each process belongs to a process group, and each process group has a process group number, which is equal to the PID of the process group leader

2. Key points of daemon programming

1. Run in the background.?
To avoid hanging the control terminal, put Daemon into the background for execution. The method is to call fork in the process to terminate the parent process and let Daemon execute in the background in the child process. if($pid=pcntl_fork()) exit(0);//It is the parent process, end the parent process, and the child process continues
2. Get rid of the controlling terminal and log in to the session and process group
It is necessary to first introduce the relationship between processes and control terminals, login sessions and process groups in Linux: a process belongs to a process group, and the process group number (GID) is the process number (PID) of the process group leader. A login session can contain multiple process groups. These process groups share a controlling terminal. This control terminal is usually the login terminal where the process was created. Controlling terminals, login sessions, and process groups are usually inherited from the parent process. Our purpose is to get rid of them and not be affected by them. The method is to call setsid() based on point 1 to make the process the session leader: posix_setsid();
? ? ? Description: The setsid() call fails when the process is the session leader. But the first point already ensures that the process is not the session leader. After the setsid() call is successful, the process becomes the new session group leader and new process group leader, and is separated from the original login session and process group. Due to the exclusivity of the session process to the control terminal, the process is detached from the control terminal at the same time.
3. Disable the process from reopening the control terminal
Now, the process has become the terminalless session leader. But it can be re-applied to open a control terminal. You can prevent the process from reopening the control terminal by making the process no longer the session leader: if($pid=pcntl_fork()) exit(0);//End the first child process and the second child process continues (the second child process No longer the conversation leader)
4. Close the open file descriptor
A process inherits open file descriptors from the parent process that created it. If it is not closed, system resources will be wasted, the file system where the process is located will not be able to be unmounted, and unpredictable errors will occur. Close them as follows:
??????????????? fclose(STDIN), fclose(STDOUT), fclose(STDERR) closes standard input, output and error display.
5. Change the current working directory
When a process is active, the file system where its working directory is located cannot be unmounted. Generally you need to change the working directory to the root directory. For core dumps that need to be dumped, the process writing the running log changes the working directory to a specific directory such as chdir("/")
6. Reset file creation mask
A process inherits the file creation mask from the parent process that created it. It may modify the access bits of files created by the daemon. To prevent this, clear the file creation mask: umask(0);
7. Processing SIGCHLD signal
It is not necessary to handle the SIGCHLD signal. But for some processes, especially server processes, child processes are often generated to handle requests when requests arrive. If the parent process does not wait for the child process to end, the child process will become a zombie process (zombie) and occupy system resources. If the parent process waits for the child process to end, it will increase the burden on the parent process and affect the concurrency performance of the server process. Under Linux, you can simply set the operation of the SIGCHLD signal to SIG_IGN. signal(SIGCHLD,SIG_IGN);
This way, the kernel will not create a zombie process when the child process ends. This is different from BSD4. Under BSD4, you must explicitly wait for the child process to end before releasing the zombie process. For questions about signals, please refer to the Linux signal description list


3. Example

 
<?php  
/** 
*@author tengzhaorong@gmail.com 
*@date 2013-07-25 
* 后臺(tái)腳本控制類(lèi) 
*/  
class DaemonCommand{  
   
    private $info_dir="/tmp";  
    private $pid_file="";  
    private $terminate=false; //是否中斷   
    private $workers_count=0;  
    private $gc_enabled=null;  
    private $workers_max=8; //最多運(yùn)行8個(gè)進(jìn)程   
   
    public function __construct($is_sington=false,$user=&#39;nobody&#39;,$output="/dev/null"){  
   
            $this->is_sington=$is_sington; //是否單例運(yùn)行,單例運(yùn)行會(huì)在tmp目錄下建立一個(gè)唯一的PID   
            $this->user=$user;//設(shè)置運(yùn)行的用戶 默認(rèn)情況下nobody   
            $this->output=$output; //設(shè)置輸出的地方   
            $this->checkPcntl();  
    }  
    //檢查環(huán)境是否支持pcntl支持   
    public function checkPcntl(){  
        if ( ! function_exists(&#39;pcntl_signal_dispatch&#39;)) {  
            // PHP < 5.3 uses ticks to handle signals instead of pcntl_signal_dispatch   
            // call sighandler only every 10 ticks   
            declare(ticks = 10);  
        }  
   
        // Make sure PHP has support for pcntl   
        if ( ! function_exists(&#39;pcntl_signal&#39;)) {  
            $message = &#39;PHP does not appear to be compiled with the PCNTL extension.  This is neccesary for daemonization&#39;;  
            $this->_log($message);  
            throw new Exception($message);  
        }  
        //信號(hào)處理   
        pcntl_signal(SIGTERM, array(__CLASS__, "signalHandler"),false);  
        pcntl_signal(SIGINT, array(__CLASS__, "signalHandler"),false);  
        pcntl_signal(SIGQUIT, array(__CLASS__, "signalHandler"),false);  
   
        // Enable PHP 5.3 garbage collection   
        if (function_exists(&#39;gc_enable&#39;))  
        {  
            gc_enable();  
            $this->gc_enabled = gc_enabled();  
        }  
    }  
   
    // daemon化程序   
    public function daemonize(){  
   
        global $stdin, $stdout, $stderr;  
        global $argv;  
   
        set_time_limit(0);  
   
        // 只允許在cli下面運(yùn)行   
        if (php_sapi_name() != "cli"){  
            die("only run in command line mode\n");  
        }  
   
        // 只能單例運(yùn)行   
        if ($this->is_sington==true){  
   
            $this->pid_file = $this->info_dir . "/" .__CLASS__ . "_" . substr(basename($argv[0]), 0, -4) . ".pid";  
            $this->checkPidfile();  
        }  
   
        umask(0); //把文件掩碼清0   
   
        if (pcntl_fork() != 0){ //是父進(jìn)程,父進(jìn)程退出   
            exit();  
        }  
   
        posix_setsid();//設(shè)置新會(huì)話組長(zhǎng),脫離終端   
   
        if (pcntl_fork() != 0){ //是第一子進(jìn)程,結(jié)束第一子進(jìn)程      
            exit();  
        }  
   
        chdir("/"); //改變工作目錄   
   
        $this->setUser($this->user) or die("cannot change owner");  
   
        //關(guān)閉打開(kāi)的文件描述符   
        fclose(STDIN);  
        fclose(STDOUT);  
        fclose(STDERR);  
   
        $stdin  = fopen($this->output, &#39;r&#39;);  
        $stdout = fopen($this->output, &#39;a&#39;);  
        $stderr = fopen($this->output, &#39;a&#39;);  
   
        if ($this->is_sington==true){  
            $this->createPidfile();  
        }  
   
    }  
    //--檢測(cè)pid是否已經(jīng)存在   
    public function checkPidfile(){  
   
        if (!file_exists($this->pid_file)){  
            return true;  
        }  
        $pid = file_get_contents($this->pid_file);  
        $pid = intval($pid);  
        if ($pid > 0 && posix_kill($pid, 0)){  
            $this->_log("the daemon process is already started");  
        }  
        else {  
            $this->_log("the daemon proces end abnormally, please check pidfile " . $this->pid_file);  
        }  
        exit(1);  
   
    }  
    //----創(chuàng)建pid   
    public function createPidfile(){  
   
        if (!is_dir($this->info_dir)){  
            mkdir($this->info_dir);  
        }  
        $fp = fopen($this->pid_file, &#39;w&#39;) or die("cannot create pid file");  
        fwrite($fp, posix_getpid());  
        fclose($fp);  
        $this->_log("create pid file " . $this->pid_file);  
    }  
   
    //設(shè)置運(yùn)行的用戶   
    public function setUser($name){  
   
        $result = false;  
        if (empty($name)){  
            return true;  
        }  
        $user = posix_getpwnam($name);  
        if ($user) {  
            $uid = $user[&#39;uid&#39;];  
            $gid = $user[&#39;gid&#39;];  
            $result = posix_setuid($uid);  
            posix_setgid($gid);  
        }  
        return $result;  
   
    }  
    //信號(hào)處理函數(shù)   
    public function signalHandler($signo){  
   
        switch($signo){  
   
            //用戶自定義信號(hào)   
            case SIGUSR1: //busy   
            if ($this->workers_count < $this->workers_max){  
                $pid = pcntl_fork();  
                if ($pid > 0){  
                    $this->workers_count ++;  
                }  
            }  
            break;  
            //子進(jìn)程結(jié)束信號(hào)   
            case SIGCHLD:  
                while(($pid=pcntl_waitpid(-1, $status, WNOHANG)) > 0){  
                    $this->workers_count --;  
                }  
            break;  
            //中斷進(jìn)程   
            case SIGTERM:  
            case SIGHUP:  
            case SIGQUIT:  
   
                $this->terminate = true;  
            break;  
            default:  
            return false;  
        }  
   
    }  
    /** 
    *開(kāi)始開(kāi)啟進(jìn)程 
    *$count 準(zhǔn)備開(kāi)啟的進(jìn)程數(shù) 
    */  
    public function start($count=1){  
   
        $this->_log("daemon process is running now");  
        pcntl_signal(SIGCHLD, array(__CLASS__, "signalHandler"),false); // if worker die, minus children num   
        while (true) {  
            if (function_exists(&#39;pcntl_signal_dispatch&#39;)){  
   
                pcntl_signal_dispatch();  
            }  
   
            if ($this->terminate){  
                break;  
            }  
            $pid=-1;  
            if($this->workers_count<$count){  
   
                $pid=pcntl_fork();  
            }  
   
            if($pid>0){  
   
                $this->workers_count++;  
   
            }elseif($pid==0){  
   
                // 這個(gè)符號(hào)表示恢復(fù)系統(tǒng)對(duì)信號(hào)的默認(rèn)處理   
                pcntl_signal(SIGTERM, SIG_DFL);  
                pcntl_signal(SIGCHLD, SIG_DFL);  
                if(!empty($this->jobs)){  
                    while($this->jobs[&#39;runtime&#39;]){  
                        if(empty($this->jobs[&#39;argv&#39;])){  
                            call_user_func($this->jobs[&#39;function&#39;],$this->jobs[&#39;argv&#39;]);  
                        }else{  
                            call_user_func($this->jobs[&#39;function&#39;]);  
                        }  
                        $this->jobs[&#39;runtime&#39;]--;  
                        sleep(2);  
                    }  
                    exit();  
   
                }  
                return;  
   
            }else{  
   
                sleep(2);  
            }  
   
   
        }  
   
        $this->mainQuit();  
        exit(0);  
   
    }  
   
    //整個(gè)進(jìn)程退出   
    public function mainQuit(){  
   
        if (file_exists($this->pid_file)){  
            unlink($this->pid_file);  
            $this->_log("delete pid file " . $this->pid_file);  
        }  
        $this->_log("daemon process exit now");  
        posix_kill(0, SIGKILL);  
        exit(0);  
    }  
   
    // 添加工作實(shí)例,目前只支持單個(gè)job工作   
    public function setJobs($jobs=array()){  
   
        if(!isset($jobs[&#39;argv&#39;])||empty($jobs[&#39;argv&#39;])){  
   
            $jobs[&#39;argv&#39;]="";  
   
        }  
        if(!isset($jobs[&#39;runtime&#39;])||empty($jobs[&#39;runtime&#39;])){  
   
            $jobs[&#39;runtime&#39;]=1;  
   
        }  
   
        if(!isset($jobs[&#39;function&#39;])||empty($jobs[&#39;function&#39;])){  
   
            $this->log("你必須添加運(yùn)行的函數(shù)!");  
        }  
   
        $this->jobs=$jobs;  
   
    }  
    //日志處理   
    private  function _log($message){  
        printf("%s\t%d\t%d\t%s\n", date("c"), posix_getpid(), posix_getppid(), $message);  
    }  
   
}  
   
//調(diào)用方法1   
$daemon=new DaemonCommand(true);  
$daemon->daemonize();  
$daemon->start(2);//開(kāi)啟2個(gè)子進(jìn)程工作   
work();  
   
   
   
   
//調(diào)用方法2   
$daemon=new DaemonCommand(true);  
$daemon->daemonize();  
$daemon->addJobs(array(&#39;function&#39;=>&#39;work&#39;,&#39;argv&#39;=>&#39;&#39;,&#39;runtime&#39;=>1000));//function 要運(yùn)行的函數(shù),argv運(yùn)行函數(shù)的參數(shù),runtime運(yùn)行的次數(shù)   
$daemon->start(2);//開(kāi)啟2個(gè)子進(jìn)程工作   
   
//具體功能的實(shí)現(xiàn)   
function work(){  
      echo "測(cè)試1";  
}  
?>  

<?php
/**
*@author tengzhaorong@gmail.com
*@date 2013-07-25
* 后臺(tái)腳本控制類(lèi)
*/
class DaemonCommand{
 
    private $info_dir="/tmp";
    private $pid_file="";
    private $terminate=false; //是否中斷
    private $workers_count=0;
    private $gc_enabled=null;
    private $workers_max=8; //最多運(yùn)行8個(gè)進(jìn)程
 
    public function __construct($is_sington=false,$user=&#39;nobody&#39;,$output="/dev/null"){
 
            $this->is_sington=$is_sington; //是否單例運(yùn)行,單例運(yùn)行會(huì)在tmp目錄下建立一個(gè)唯一的PID
            $this->user=$user;//設(shè)置運(yùn)行的用戶 默認(rèn)情況下nobody
            $this->output=$output; //設(shè)置輸出的地方
            $this->checkPcntl();
    }
    //檢查環(huán)境是否支持pcntl支持
    public function checkPcntl(){
        if ( ! function_exists(&#39;pcntl_signal_dispatch&#39;)) {
            // PHP < 5.3 uses ticks to handle signals instead of pcntl_signal_dispatch
            // call sighandler only every 10 ticks
            declare(ticks = 10);
        }
 
        // Make sure PHP has support for pcntl
        if ( ! function_exists(&#39;pcntl_signal&#39;)) {
            $message = &#39;PHP does not appear to be compiled with the PCNTL extension.  This is neccesary for daemonization&#39;;
            $this->_log($message);
            throw new Exception($message);
        }
        //信號(hào)處理
        pcntl_signal(SIGTERM, array(__CLASS__, "signalHandler"),false);
        pcntl_signal(SIGINT, array(__CLASS__, "signalHandler"),false);
        pcntl_signal(SIGQUIT, array(__CLASS__, "signalHandler"),false);
 
        // Enable PHP 5.3 garbage collection
        if (function_exists(&#39;gc_enable&#39;))
        {
            gc_enable();
            $this->gc_enabled = gc_enabled();
        }
    }
 
    // daemon化程序
    public function daemonize(){
 
        global $stdin, $stdout, $stderr;
        global $argv;
 
        set_time_limit(0);
 
        // 只允許在cli下面運(yùn)行
        if (php_sapi_name() != "cli"){
            die("only run in command line mode\n");
        }
 
        // 只能單例運(yùn)行
        if ($this->is_sington==true){
 
            $this->pid_file = $this->info_dir . "/" .__CLASS__ . "_" . substr(basename($argv[0]), 0, -4) . ".pid";
            $this->checkPidfile();
        }
 
        umask(0); //把文件掩碼清0
 
        if (pcntl_fork() != 0){ //是父進(jìn)程,父進(jìn)程退出
            exit();
        }
 
        posix_setsid();//設(shè)置新會(huì)話組長(zhǎng),脫離終端
 
        if (pcntl_fork() != 0){ //是第一子進(jìn)程,結(jié)束第一子進(jìn)程   
            exit();
        }
 
        chdir("/"); //改變工作目錄
 
        $this->setUser($this->user) or die("cannot change owner");
 
        //關(guān)閉打開(kāi)的文件描述符
        fclose(STDIN);
        fclose(STDOUT);
        fclose(STDERR);
 
        $stdin  = fopen($this->output, &#39;r&#39;);
        $stdout = fopen($this->output, &#39;a&#39;);
        $stderr = fopen($this->output, &#39;a&#39;);
 
        if ($this->is_sington==true){
            $this->createPidfile();
        }
 
    }
    //--檢測(cè)pid是否已經(jīng)存在
    public function checkPidfile(){
 
        if (!file_exists($this->pid_file)){
            return true;
        }
        $pid = file_get_contents($this->pid_file);
        $pid = intval($pid);
        if ($pid > 0 && posix_kill($pid, 0)){
            $this->_log("the daemon process is already started");
        }
        else {
            $this->_log("the daemon proces end abnormally, please check pidfile " . $this->pid_file);
        }
        exit(1);
 
    }
    //----創(chuàng)建pid
    public function createPidfile(){
 
        if (!is_dir($this->info_dir)){
            mkdir($this->info_dir);
        }
        $fp = fopen($this->pid_file, &#39;w&#39;) or die("cannot create pid file");
        fwrite($fp, posix_getpid());
        fclose($fp);
        $this->_log("create pid file " . $this->pid_file);
    }
 
    //設(shè)置運(yùn)行的用戶
    public function setUser($name){
 
        $result = false;
        if (empty($name)){
            return true;
        }
        $user = posix_getpwnam($name);
        if ($user) {
            $uid = $user[&#39;uid&#39;];
            $gid = $user[&#39;gid&#39;];
            $result = posix_setuid($uid);
            posix_setgid($gid);
        }
        return $result;
 
    }
    //信號(hào)處理函數(shù)
    public function signalHandler($signo){
 
        switch($signo){
 
            //用戶自定義信號(hào)
            case SIGUSR1: //busy
            if ($this->workers_count < $this->workers_max){
                $pid = pcntl_fork();
                if ($pid > 0){
                    $this->workers_count ++;
                }
            }
            break;
            //子進(jìn)程結(jié)束信號(hào)
            case SIGCHLD:
                while(($pid=pcntl_waitpid(-1, $status, WNOHANG)) > 0){
                    $this->workers_count --;
                }
            break;
            //中斷進(jìn)程
            case SIGTERM:
            case SIGHUP:
            case SIGQUIT:
 
                $this->terminate = true;
            break;
            default:
            return false;
        }
 
    }
    /**
    *開(kāi)始開(kāi)啟進(jìn)程
    *$count 準(zhǔn)備開(kāi)啟的進(jìn)程數(shù)
    */
    public function start($count=1){
 
        $this->_log("daemon process is running now");
        pcntl_signal(SIGCHLD, array(__CLASS__, "signalHandler"),false); // if worker die, minus children num
        while (true) {
            if (function_exists(&#39;pcntl_signal_dispatch&#39;)){
 
                pcntl_signal_dispatch();
            }
 
            if ($this->terminate){
                break;
            }
            $pid=-1;
            if($this->workers_count<$count){
 
                $pid=pcntl_fork();
            }
 
            if($pid>0){
 
                $this->workers_count++;
 
            }elseif($pid==0){
 
                // 這個(gè)符號(hào)表示恢復(fù)系統(tǒng)對(duì)信號(hào)的默認(rèn)處理
                pcntl_signal(SIGTERM, SIG_DFL);
                pcntl_signal(SIGCHLD, SIG_DFL);
                if(!empty($this->jobs)){
                    while($this->jobs[&#39;runtime&#39;]){
                        if(empty($this->jobs[&#39;argv&#39;])){
                            call_user_func($this->jobs[&#39;function&#39;],$this->jobs[&#39;argv&#39;]);
                        }else{
                            call_user_func($this->jobs[&#39;function&#39;]);
                        }
                        $this->jobs[&#39;runtime&#39;]--;
                        sleep(2);
                    }
                    exit();
 
                }
                return;
 
            }else{
 
                sleep(2);
            }
 
 
        }
 
        $this->mainQuit();
        exit(0);
 
    }
 
    //整個(gè)進(jìn)程退出
    public function mainQuit(){
 
        if (file_exists($this->pid_file)){
            unlink($this->pid_file);
            $this->_log("delete pid file " . $this->pid_file);
        }
        $this->_log("daemon process exit now");
        posix_kill(0, SIGKILL);
        exit(0);
    }
 
    // 添加工作實(shí)例,目前只支持單個(gè)job工作
    public function setJobs($jobs=array()){
 
        if(!isset($jobs[&#39;argv&#39;])||empty($jobs[&#39;argv&#39;])){
 
            $jobs[&#39;argv&#39;]="";
 
        }
        if(!isset($jobs[&#39;runtime&#39;])||empty($jobs[&#39;runtime&#39;])){
 
            $jobs[&#39;runtime&#39;]=1;
 
        }
 
        if(!isset($jobs[&#39;function&#39;])||empty($jobs[&#39;function&#39;])){
 
            $this->log("你必須添加運(yùn)行的函數(shù)!");
        }
 
        $this->jobs=$jobs;
 
    }
    //日志處理
    private  function _log($message){
        printf("%s\t%d\t%d\t%s\n", date("c"), posix_getpid(), posix_getppid(), $message);
    }
 
}
 
//調(diào)用方法1
$daemon=new DaemonCommand(true);
$daemon->daemonize();
$daemon->start(2);//開(kāi)啟2個(gè)子進(jìn)程工作
work();
 
 
 
 
//調(diào)用方法2
$daemon=new DaemonCommand(true);
$daemon->daemonize();
$daemon->addJobs(array(&#39;function&#39;=>&#39;work&#39;,&#39;argv&#39;=>&#39;&#39;,&#39;runtime&#39;=>1000));//function 要運(yùn)行的函數(shù),argv運(yùn)行函數(shù)的參數(shù),runtime運(yùn)行的次數(shù)
$daemon->start(2);//開(kāi)啟2個(gè)子進(jìn)程工作
 
//具體功能的實(shí)現(xiàn)
function work(){
      echo "測(cè)試1";
}
?>


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/477175.htmlTechArticleDaemon is a special process running in the background. It is independent of the control terminal and periodically performs some task or waits for some event to occur. A daemon is a...
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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

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)

Using std::chrono in C Using std::chrono in C Jul 15, 2025 am 01:30 AM

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

How does PHP handle Environment Variables? How does PHP handle Environment Variables? Jul 14, 2025 am 03:01 AM

ToaccessenvironmentvariablesinPHP,usegetenv()orthe$_ENVsuperglobal.1.getenv('VAR_NAME')retrievesaspecificvariable.2.$_ENV['VAR_NAME']accessesvariablesifvariables_orderinphp.iniincludes"E".SetvariablesviaCLIwithVAR=valuephpscript.php,inApach

Why We Comment: A PHP Guide Why We Comment: A PHP Guide Jul 15, 2025 am 02:48 AM

PHPhasthreecommentstyles://,#forsingle-lineand/.../formulti-line.Usecommentstoexplainwhycodeexists,notwhatitdoes.MarkTODO/FIXMEitemsanddisablecodetemporarilyduringdebugging.Avoidover-commentingsimplelogic.Writeconcise,grammaticallycorrectcommentsandu

PHP prepared statement get result PHP prepared statement get result Jul 14, 2025 am 02:12 AM

The method of using preprocessing statements to obtain database query results in PHP varies from extension. 1. When using mysqli, you can obtain the associative array through get_result() and fetch_assoc(), which is suitable for modern environments; 2. You can also use bind_result() to bind variables, which is suitable for situations where there are few fields and fixed structures, and it is good compatibility but there are many fields when there are many fields; 3. When using PDO, you can obtain the associative array through fetch (PDO::FETCH_ASSOC), or use fetchAll() to obtain all data at once, so the interface is unified and the error handling is clearer; in addition, you need to pay attention to parameter type matching, execution of execute(), timely release of resources and enable error reports.

PHP check if a string starts with a specific string PHP check if a string starts with a specific string Jul 14, 2025 am 02:44 AM

In PHP, you can use a variety of methods to determine whether a string starts with a specific string: 1. Use strncmp() to compare the first n characters. If 0 is returned, the beginning matches and is not case sensitive; 2. Use strpos() to check whether the substring position is 0, which is case sensitive. Stripos() can be used instead to achieve case insensitive; 3. You can encapsulate the startsWith() or str_starts_with() function to improve reusability; in addition, it is necessary to note that empty strings return true by default, encoding compatibility and performance differences, strncmp() is usually more efficient.

how to avoid undefined index error in PHP how to avoid undefined index error in PHP Jul 14, 2025 am 02:51 AM

There are three key ways to avoid the "undefinedindex" error: First, use isset() to check whether the array key exists and ensure that the value is not null, which is suitable for most common scenarios; second, use array_key_exists() to only determine whether the key exists, which is suitable for situations where the key does not exist and the value is null; finally, use the empty merge operator?? (PHP7) to concisely set the default value, which is recommended for modern PHP projects, and pay attention to the spelling of form field names, use extract() carefully, and check the array is not empty before traversing to further avoid risks.

PHP prepared statement with IN clause PHP prepared statement with IN clause Jul 14, 2025 am 02:56 AM

When using PHP preprocessing statements to execute queries with IN clauses, 1. Dynamically generate placeholders according to the length of the array; 2. When using PDO, you can directly pass in the array, and use array_values to ensure continuous indexes; 3. When using mysqli, you need to construct type strings and bind parameters, pay attention to the way of expanding the array and version compatibility; 4. Avoid splicing SQL, processing empty arrays, and ensuring data types match. The specific method is: first use implode and array_fill to generate placeholders, and then bind parameters according to the extended characteristics to safely execute IN queries.

How to Install PHP on Windows How to Install PHP on Windows Jul 15, 2025 am 02:46 AM

The key steps to install PHP on Windows include: 1. Download the appropriate PHP version and decompress it. It is recommended to use ThreadSafe version with Apache or NonThreadSafe version with Nginx; 2. Configure the php.ini file and rename php.ini-development or php.ini-production to php.ini; 3. Add the PHP path to the system environment variable Path for command line use; 4. Test whether PHP is installed successfully, execute php-v through the command line and run the built-in server to test the parsing capabilities; 5. If you use Apache, you need to configure P in httpd.conf

See all articles