在php中,每秒回显当前日期和时间以及磁盘上的空闲空间


Echo current date and time and free space on disk every second in php

我是php的新手,我正试图获得当前日期和时间以及磁盘上的可用空间,并在网页上每秒更新一次。

对于日期和时间我使用:date("d-m-Y H:i:s") .

对于获得空闲空间,我知道我可以使用以路径作为参数的diskfreespace()函数。在我的情况下,我正在尝试diskfreespace("C:")

它返回字节数,因为我有gb的空间,所以我除以字节数以得到gb的数量。

diskfreespace("C:") / pow(1024, 3)

虽然它只执行一次,但它可以工作,我希望函数每秒执行一次,并通过echo函数显示值。

然后我尝试使用1秒的sleep()无限循环,但似乎有一个问题,因为值不是每秒更新,似乎如果页面不能正常加载。

<?php
while(1)
{
    echo "Current date and time: " . date("d-m-Y H:i:s");
    echo "</br></br>Free space on C: disk " . (diskfreespace("C:") / pow(1024, 3)) . " Gb";
    sleep(1);
}
?>

如果您使用Server Sent Events,您可以连接到PHP脚本,该脚本在无限循环中运行,将数据推送到javascript侦听器

<?php
    /*
        diskspace_sse.php
    */
    set_time_limit( 0 );
    ini_set('auto_detect_line_endings', 1);
    ini_set('max_execution_time', '0');
    /* -- Edit to suit your location -- */
    date_default_timezone_set( 'Europe/London' );
    ob_end_clean();

    /* -- set headers -- */
    header('Content-Type: text/event-stream'); /* !important! */
    header('Cache-Control: no-cache');
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Allow-Methods: GET');
    header('Access-Control-Expose-Headers: X-Events');  

    /* -- utility function to send formatted sse message -- */
    if( !function_exists('sse_message') ){
        function sse_message( $evtname='gas', $data=null, $retry=1000 ){
            if( !is_null( $data ) ){
                echo "event:".$evtname."'r'n";
                echo "retry:".$retry."'r'n";
                echo "data:" . json_encode( $data, JSON_FORCE_OBJECT|JSON_HEX_QUOT|JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS );
                echo "'r'n'r'n";
            }
        }
    }

    /* -- How often to send messages -- */
    $sleep=1;
    $disk='c:';
    while( true ){
        if( connection_status() != CONNECTION_NORMAL or connection_aborted() ) {
            break;
        }
        /* Infinite loop is running - perform actions you need */
        $payload=array(
            'date'      =>  date(DATE_COOKIE),
            'diskspace' =>  disk_free_space($disk),
            'totalspace'=>  disk_total_space($disk),
            'formatted_diskspace'   =>  round( disk_free_space($disk) / pow( 1024,3 ), 2 ).'Gb',
            'formatted_total'       =>  round( disk_total_space($disk) / pow( 1024,3 ), 2 ).'Gb'
        );
        /* -- prepare sse message -- */
        sse_message( 'diskspace', $payload );
        /* -- Send output -- */
        if( @ob_get_level() > 0 ) for( $i=0; $i < @ob_get_level(); $i++ ) @ob_flush();
        @flush();
        /* wait */
        sleep( $sleep );
    }
    if( @ob_get_level() > 0 ) {
        for( $i=0; $i < @ob_get_level(); $i++ ) @ob_flush();
        @ob_end_clean();
    }
?>

在你的html页面

<div id='diskspace'></div>
<script type='text/javascript'>
    function bindEvtSource(){
        var url='http://localhost/diskspace_sse.php';
        if ( !!window.EventSource ) {
            var evtSource = new EventSource( url );
            evtSource.addEventListener( 'open', function(e){
                console.log(e.type);
            },false);
            evtSource.addEventListener( 'error', function(e){
                console.error('%o %s',e,e.type);
            },false);
            evtSource.addEventListener( 'diskspace', function(e){
                var json=JSON.parse(e.data);
                /* you could work with the json data here */
                getobject('diskspace').innerHTML=e.data;
            },false);
        } else {
            alert('Server Sent Events are not supported in this browser');
        }
    }
    document.addEventListener( 'DOMContentLoaded', bindEvtSource, false );
</script>

您应该每秒获得关于磁盘空间使用情况的反馈,并且页面加载时间没有(很少)减慢。

Echo显示代码完成作业后的结果。在你的情况下,它可能在控制台应用程序中工作,而不是在web中。为了实现您的目标,您必须了解ajax。在前端,您需要调用php代码,并呈现结果。过一秒钟再做一次

核对答案

另外,您可能希望用AJAX请求实现一种简单的轮询机制,而不是PHP中的无限循环。否则,根据您的服务器设置,无限循环可能会在一段时间后停止。看到max_execution_time。