백엔드 개발 PHP 튜토리얼 php写守护进程(Daemon)_PHP教程

php写守护进程(Daemon)_PHP教程

Jul 15, 2016 pm 01:21 PM
php 쓰다 무대 뒤에서 제어 ~의 프로세스

 守护进程(Daemon)是运行在后台的一种特殊进程。它独立于控制终端并且周期性地执行某种任务或等待处理某些发生的事件。守护进程是一种很有用的进程。php也可以实现守护进程的功能。

 

1、基本概念

    进程

            每个进程都有一个父进程,子进程退出,父进程能得到子进程退出的状态。

    进程组

            每个进程都属于一个进程组,每个进程组都有一个进程组号,该号等于该进程组组长的PID

2、守护编程要点

 守护进程(Daemon)是运行在后台的一种特殊进程。它独立于控制终端并且周期性地执行某种任务或等待处理某些发生的事件。守护进程是一种很有用的进程。php也可以实现守护进程的功能。

 

1、基本概念

    进程

            每个进程都有一个父进程,子进程退出,父进程能得到子进程退出的状态。

    进程组

            每个进程都属于一个进程组,每个进程组都有一个进程组号,该号等于该进程组组长的PID

2、守护编程要点

    1. 在后台运行。    
         为避免挂起控制终端将Daemon放入后台执行。方法是在进程中调用fork使父进程终止,让Daemon在子进程中后台执行。 if($pid=pcntl_fork()) exit(0);//是父进程,结束父进程,子进程继续
    2. 脱离控制终端,登录会话和进程组
       有必要先介绍一下Linux中的进程与控制终端,登录会话和进程组之间的关系:进程属于一个进程组,进程组号(GID)就是进程组长的进程号(PID)。登录会话可以包含多个进程组。这些进程组共享一个控制终端。这个控制终端通常是创建进程的登录终  端。 控制终端,登录会话和进程组通常是从父进程继承下来的。我们的目的就是要摆脱它们,使之不受它们的影响。方法是在第1点的基础上,调用setsid()使进程成为会话组长: posix_setsid();
        说明:当进程是会话组长时setsid()调用失败。但第一点已经保证进程不是会话组长。setsid()调用成功后,进程成为新的会话组长和新的进程组长,并与原来的登录会话和进程组脱离。由于会话过程对控制终端的独占性,进程同时与控制终端脱离。
    3. 禁止进程重新打开控制终端
        现在,进程已经成为无终端的会话组长。但它可以重新申请打开一个控制终端。可以通过使进程不再成为会话组长来禁止进程重新打开控制终端: if($pid=pcntl_fork()) exit(0);//结束第一子进程,第二子进程继续(第二子进程不再是会话组长)
    4. 关闭打开的文件描述符
        进程从创建它的父进程那里继承了打开的文件描述符。如不关闭,将会浪费系统资源,造成进程所在的文件系统无法卸下以及引起无法预料的错误。按如下方法关闭它们:
        fclose(STDIN),fclose(STDOUT),fclose(STDERR)关闭标准输入输出与错误显示。
    5. 改变当前工作目录
        进程活动时,其工作目录所在的文件系统不能卸下。一般需要将工作目录改变到根目录。对于需要转储核心,写运行日志的进程将工作目录改变到特定目录如chdir("/")
    6. 重设文件创建掩模
        进程从创建它的父进程那里继承了文件创建掩模。它可能修改守护进程所创建的文件的存取位。为防止这一点,将文件创建掩模清除:umask(0);
    7. 处理SIGCHLD信号
        处理SIGCHLD信号并不是必须的。但对于某些进程,特别是服务器进程往往在请求到来时生成子进程处理请求。如果父进程不等待子进程结束,子进程将成为僵尸进程(zombie)从而占用系统资源。如果父进程等待子进程结束,将增加父进程的负担,影  响服务器进程的并发性能。在Linux下可以简单地将SIGCHLD信号的操作设为SIG_IGN。 signal(SIGCHLD,SIG_IGN);
        这样,内核在子进程结束时不会产生僵尸进程。这一点与BSD4不同,BSD4下必须显式等待子进程结束才能释放僵尸进程。关于信号的问题请参考Linux 信号说明列表


 

3、实例

 
<?php  
/** 
*@author tengzhaorong@gmail.com 
*@date 2013-07-25 
* 后台脚本控制类 
*/  
class DaemonCommand{  
   
    private $info_dir="/tmp";  
    private $pid_file="";  
    private $terminate=false; //是否中断   
    private $workers_count=0;  
    private $gc_enabled=null;  
    private $workers_max=8; //最多运行8个进程   
   
    public function __construct($is_sington=false,$user=&#39;nobody&#39;,$output="/dev/null"){  
   
            $this->is_sington=$is_sington; //是否单例运行,单例运行会在tmp目录下建立一个唯一的PID   
            $this->user=$user;//设置运行的用户 默认情况下nobody   
            $this->output=$output; //设置输出的地方   
            $this->checkPcntl();  
    }  
    //检查环境是否支持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);  
        }  
        //信号处理   
        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下面运行   
        if (php_sapi_name() != "cli"){  
            die("only run in command line mode\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){ //是父进程,父进程退出   
            exit();  
        }  
   
        posix_setsid();//设置新会话组长,脱离终端   
   
        if (pcntl_fork() != 0){ //是第一子进程,结束第一子进程      
            exit();  
        }  
   
        chdir("/"); //改变工作目录   
   
        $this->setUser($this->user) or die("cannot change owner");  
   
        //关闭打开的文件描述符   
        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();  
        }  
   
    }  
    //--检测pid是否已经存在   
    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);  
   
    }  
    //----创建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);  
    }  
   
    //设置运行的用户   
    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;  
   
    }  
    //信号处理函数   
    public function signalHandler($signo){  
   
        switch($signo){  
   
            //用户自定义信号   
            case SIGUSR1: //busy   
            if ($this->workers_count < $this->workers_max){  
                $pid = pcntl_fork();  
                if ($pid > 0){  
                    $this->workers_count ++;  
                }  
            }  
            break;  
            //子进程结束信号   
            case SIGCHLD:  
                while(($pid=pcntl_waitpid(-1, $status, WNOHANG)) > 0){  
                    $this->workers_count --;  
                }  
            break;  
            //中断进程   
            case SIGTERM:  
            case SIGHUP:  
            case SIGQUIT:  
   
                $this->terminate = true;  
            break;  
            default:  
            return false;  
        }  
   
    }  
    /** 
    *开始开启进程 
    *$count 准备开启的进程数 
    */  
    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){  
   
                // 这个符号表示恢复系统对信号的默认处理   
                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);  
   
    }  
   
    //整个进程退出   
    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);  
    }  
   
    // 添加工作实例,目前只支持单个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("你必须添加运行的函数!");  
        }  
   
        $this->jobs=$jobs;  
   
    }  
    //日志处理   
    private  function _log($message){  
        printf("%s\t%d\t%d\t%s\n", date("c"), posix_getpid(), posix_getppid(), $message);  
    }  
   
}  
   
//调用方法1   
$daemon=new DaemonCommand(true);  
$daemon->daemonize();  
$daemon->start(2);//开启2个子进程工作   
work();  
   
   
   
   
//调用方法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 要运行的函数,argv运行函数的参数,runtime运行的次数   
$daemon->start(2);//开启2个子进程工作   
   
//具体功能的实现   
function work(){  
      echo "测试1";  
}  
?>  

<?php
/**
*@author tengzhaorong@gmail.com
*@date 2013-07-25
* 后台脚本控制类
*/
class DaemonCommand{
 
    private $info_dir="/tmp";
    private $pid_file="";
    private $terminate=false; //是否中断
    private $workers_count=0;
    private $gc_enabled=null;
    private $workers_max=8; //最多运行8个进程
 
    public function __construct($is_sington=false,$user=&#39;nobody&#39;,$output="/dev/null"){
 
            $this->is_sington=$is_sington; //是否单例运行,单例运行会在tmp目录下建立一个唯一的PID
            $this->user=$user;//设置运行的用户 默认情况下nobody
            $this->output=$output; //设置输出的地方
            $this->checkPcntl();
    }
    //检查环境是否支持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);
        }
        //信号处理
        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下面运行
        if (php_sapi_name() != "cli"){
            die("only run in command line mode\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){ //是父进程,父进程退出
            exit();
        }
 
        posix_setsid();//设置新会话组长,脱离终端
 
        if (pcntl_fork() != 0){ //是第一子进程,结束第一子进程   
            exit();
        }
 
        chdir("/"); //改变工作目录
 
        $this->setUser($this->user) or die("cannot change owner");
 
        //关闭打开的文件描述符
        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();
        }
 
    }
    //--检测pid是否已经存在
    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);
 
    }
    //----创建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);
    }
 
    //设置运行的用户
    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;
 
    }
    //信号处理函数
    public function signalHandler($signo){
 
        switch($signo){
 
            //用户自定义信号
            case SIGUSR1: //busy
            if ($this->workers_count < $this->workers_max){
                $pid = pcntl_fork();
                if ($pid > 0){
                    $this->workers_count ++;
                }
            }
            break;
            //子进程结束信号
            case SIGCHLD:
                while(($pid=pcntl_waitpid(-1, $status, WNOHANG)) > 0){
                    $this->workers_count --;
                }
            break;
            //中断进程
            case SIGTERM:
            case SIGHUP:
            case SIGQUIT:
 
                $this->terminate = true;
            break;
            default:
            return false;
        }
 
    }
    /**
    *开始开启进程
    *$count 准备开启的进程数
    */
    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){
 
                // 这个符号表示恢复系统对信号的默认处理
                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);
 
    }
 
    //整个进程退出
    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);
    }
 
    // 添加工作实例,目前只支持单个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("你必须添加运行的函数!");
        }
 
        $this->jobs=$jobs;
 
    }
    //日志处理
    private  function _log($message){
        printf("%s\t%d\t%d\t%s\n", date("c"), posix_getpid(), posix_getppid(), $message);
    }
 
}
 
//调用方法1
$daemon=new DaemonCommand(true);
$daemon->daemonize();
$daemon->start(2);//开启2个子进程工作
work();
 
 
 
 
//调用方法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 要运行的函数,argv运行函数的参数,runtime运行的次数
$daemon->start(2);//开启2个子进程工作
 
//具体功能的实现
function work(){
      echo "测试1";
}
?>

로그인 후 복사


 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/477175.htmlTechArticle守护进程(Daemon)是运行在后台的一种特殊进程。它独立于控制终端并且周期性地执行某种任务或等待处理某些发生的事件。守护进程是一...
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Ubuntu 및 Debian용 PHP 8.4 설치 및 업그레이드 가이드 Ubuntu 및 Debian용 PHP 8.4 설치 및 업그레이드 가이드 Dec 24, 2024 pm 04:42 PM

PHP 8.4는 상당한 양의 기능 중단 및 제거를 통해 몇 가지 새로운 기능, 보안 개선 및 성능 개선을 제공합니다. 이 가이드에서는 Ubuntu, Debian 또는 해당 파생 제품에서 PHP 8.4를 설치하거나 PHP 8.4로 업그레이드하는 방법을 설명합니다.

이전에 몰랐던 후회되는 PHP 함수 7가지 이전에 몰랐던 후회되는 PHP 함수 7가지 Nov 13, 2024 am 09:42 AM

숙련된 PHP 개발자라면 이미 그런 일을 해왔다는 느낌을 받을 것입니다. 귀하는 상당한 수의 애플리케이션을 개발하고, 수백만 줄의 코드를 디버깅하고, 여러 스크립트를 수정하여 작업을 수행했습니다.

PHP 개발을 위해 Visual Studio Code(VS Code)를 설정하는 방법 PHP 개발을 위해 Visual Studio Code(VS Code)를 설정하는 방법 Dec 20, 2024 am 11:31 AM

VS Code라고도 알려진 Visual Studio Code는 모든 주요 운영 체제에서 사용할 수 있는 무료 소스 코드 편집기 또는 통합 개발 환경(IDE)입니다. 다양한 프로그래밍 언어에 대한 대규모 확장 모음을 통해 VS Code는

JWT (JSON Web Tokens) 및 PHP API의 사용 사례를 설명하십시오. JWT (JSON Web Tokens) 및 PHP API의 사용 사례를 설명하십시오. Apr 05, 2025 am 12:04 AM

JWT는 주로 신분증 인증 및 정보 교환을 위해 당사자간에 정보를 안전하게 전송하는 데 사용되는 JSON을 기반으로 한 개방형 표준입니다. 1. JWT는 헤더, 페이로드 및 서명의 세 부분으로 구성됩니다. 2. JWT의 작업 원칙에는 세 가지 단계가 포함됩니다. JWT 생성, JWT 확인 및 Parsing Payload. 3. PHP에서 인증에 JWT를 사용하면 JWT를 생성하고 확인할 수 있으며 사용자 역할 및 권한 정보가 고급 사용에 포함될 수 있습니다. 4. 일반적인 오류에는 서명 검증 실패, 토큰 만료 및 대형 페이로드가 포함됩니다. 디버깅 기술에는 디버깅 도구 및 로깅 사용이 포함됩니다. 5. 성능 최적화 및 모범 사례에는 적절한 시그니처 알고리즘 사용, 타당성 기간 설정 합리적,

PHP에서 HTML/XML을 어떻게 구문 분석하고 처리합니까? PHP에서 HTML/XML을 어떻게 구문 분석하고 처리합니까? Feb 07, 2025 am 11:57 AM

이 튜토리얼은 PHP를 사용하여 XML 문서를 효율적으로 처리하는 방법을 보여줍니다. XML (Extensible Markup Language)은 인간의 가독성과 기계 구문 분석을 위해 설계된 다목적 텍스트 기반 마크 업 언어입니다. 일반적으로 데이터 저장 AN에 사용됩니다

문자열로 모음을 계산하는 PHP 프로그램 문자열로 모음을 계산하는 PHP 프로그램 Feb 07, 2025 pm 12:12 PM

문자열은 문자, 숫자 및 기호를 포함하여 일련의 문자입니다. 이 튜토리얼은 다른 방법을 사용하여 PHP의 주어진 문자열의 모음 수를 계산하는 방법을 배웁니다. 영어의 모음은 A, E, I, O, U이며 대문자 또는 소문자 일 수 있습니다. 모음이란 무엇입니까? 모음은 특정 발음을 나타내는 알파벳 문자입니다. 대문자와 소문자를 포함하여 영어에는 5 개의 모음이 있습니다. a, e, i, o, u 예 1 입력 : String = "Tutorialspoint" 출력 : 6 설명하다 문자열의 "Tutorialspoint"의 모음은 u, o, i, a, o, i입니다. 총 6 개의 위안이 있습니다

PHP에서 늦은 정적 결합을 설명하십시오 (정적 : :). PHP에서 늦은 정적 결합을 설명하십시오 (정적 : :). Apr 03, 2025 am 12:04 AM

정적 바인딩 (정적 : :)는 PHP에서 늦은 정적 바인딩 (LSB)을 구현하여 클래스를 정의하는 대신 정적 컨텍스트에서 호출 클래스를 참조 할 수 있습니다. 1) 구문 분석 프로세스는 런타임에 수행됩니다. 2) 상속 관계에서 통화 클래스를 찾아보십시오. 3) 성능 오버 헤드를 가져올 수 있습니다.

php magic 방법 (__construct, __destruct, __call, __get, __set 등)이란 무엇이며 사용 사례를 제공합니까? php magic 방법 (__construct, __destruct, __call, __get, __set 등)이란 무엇이며 사용 사례를 제공합니까? Apr 03, 2025 am 12:03 AM

PHP의 마법 방법은 무엇입니까? PHP의 마법 방법은 다음과 같습니다. 1. \ _ \ _ Construct, 객체를 초기화하는 데 사용됩니다. 2. \ _ \ _ 파괴, 자원을 정리하는 데 사용됩니다. 3. \ _ \ _ 호출, 존재하지 않는 메소드 호출을 처리하십시오. 4. \ _ \ _ get, 동적 속성 액세스를 구현하십시오. 5. \ _ \ _ Set, 동적 속성 설정을 구현하십시오. 이러한 방법은 특정 상황에서 자동으로 호출되어 코드 유연성과 효율성을 향상시킵니다.

See all articles