如何在页面加载 10 秒后调用 PHP 中的函数(不使用 HTML)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1333434/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:03:52  来源:igfitidea点击:

how to call a function in PHP after 10 seconds of the page load (Not using HTML)

php

提问by Fero

Is there any way to call a function 10 seconds after the page load in PHP. (Not using HTML.)

有什么方法可以在 PHP 页面加载后 10 秒调用函数。(不使用 HTML。)

采纳答案by Fero

This code works. Edited from randell's answer.

此代码有效。从兰德尔的回答中编辑。

<script type="text/javascript" src="jquery.js"></script>          
<script type="text/javascript">

$(document).ready(function()
  {
    setTimeout(function()    {   $('#some_id').load('index.php');    }, 10000);
  });
</script>  

Thanks to randell

感谢兰德尔

回答by Randell

PHP is a server side scripting language.If you need to check if something has loaded already in the client side, you will need a client-side scripting language like JavaScript.

PHP 是一种服务器端脚本语言。如果您需要检查客户端是否已经加载了某些内容,您将需要一种客户端脚本语言,例如 JavaScript

You might need to use jQuery for your purposeto simplify things.

您可能需要使用 jQuery来简化事情。

jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript.

jQuery 是一个快速而简洁的 JavaScript 库,它简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互,以实现快速的 Web 开发。jQuery 旨在改变您编写 JavaScript 的方式。

First, download jQuery. In the head tag of your HTML, add this:

首先,下载jQuery。在 HTML 的 head 标记中,添加以下内容:

<script type="text/javascript" src="jquery.js"></script>          
<script type="text/javascript">

// Check if the page has loaded completely                                         
$(document).ready( function() { 
    setTimeout( function() { 
        $('#some_id').load('index.php'); 
    }, 10000); 
}); 
</script> 

In the body of your HTML, add this:

在 HTML 正文中,添加以下内容:

<div id="some_id"></div>

回答by Konrad Rudolph

Not really, no. 10 seconds after your page loaded is (at least) 10 seconds after your PHP script finished, i.e. it is no longer running(apart from tricks that try keeping the connection open, which I don't think will work for a time as long as 10 seconds)!

不是真的,不是。页面加载后 10 秒(至少)是 PHP 脚本完成后的 10 秒,即它不再运行(除了尝试保持连接打开的技巧,我认为这在一段时间内不会起作用) 10 秒)!

Therefore, you either need to schedule a cronjob on the server side to fire in 10 seconds, or you need a callback from the website, using AJAX.

因此,您要么需要cron在服务器端安排作业在 10 秒内触发,要么需要使用 AJAX 从网站回调。

回答by Paul Dixon

If I interpret your question as "My page takes a long time to generate, now can I call a PHP function every 10 seconds while it generates" then there are several ways you can approach this...

如果我将您的问题解释为“我的页面需要很长时间才能生成,现在我可以在生成时每 10 秒调用一次 PHP 函数吗”,那么您可以通过多种方法来解决这个问题...

Time your loop, do something after 10 seconds of work...

为你的循环计时,在工作 10 秒后做一些事情......

$nexttick=time()+10;
$active=true;

while ($active)
{
    if (time()>=$nexttick)
    {
        my_tick_function();
        $nexttick=time()+10;
    }

    //now do some useful processing
    $active=do_some_work();
}

It's possible to use a technique like this to implement a progress meter for long running operations, by having your "tick" function output some javascript to update the HTML representing a progress meter.

通过让“tick”函数输出一些 javascript 来更新表示进度表的 HTML,可以使用这样的技术来为长时间运行的操作实现进度表。

Using pcntl_alarm...

使用 pcntl_alarm...

Alternatively, if you have the Process Controlsupport enabled in your build of PHP, you might be able to use pcntl_alarmto call a signal handler after a certain amount of time has elapsed.

或者,如果您在 PHP 版本中启用了Process Control支持,您可能能够在经过一定时间后使用pcntl_alarm调用信号处理程序。

Using ticks...

使用刻度...

You can use the declareconstruct along with register_tick_functionto have the PHP engine call your function every x 'ticks'. From the manual:

您可以将声明构造与register_tick_function一起使用,让 PHP 引擎每 x 'tick' 调用一次您的函数。从手册:

A tick is an event that occurs for every N low-level tickable statements executed by the parser within the declare block. The value for N is specified using ticks=N within the declare blocks's directive section.

滴答是在声明块中解析器每执行 N 个低级可滴答语句时发生的事件。N 的值是在声明块的指令部分中使用 ticks=N 指定的。

回答by warpech

This seems weird idea but maybe it's what you are looking for if you want to do it in PHP without touching HTML/JS:

这看起来很奇怪,但如果您想在不接触 HTML/JS 的情况下在 PHP 中执行此操作,这可能就是您正在寻找的:

<?php
your_website_here();

flush(); //this sends the output to the client. You may also need ob_flush();
sleep(10); //wait 10 seconds

your_func_here();
?>

The above is preety OK in theory, but in practice it will result in VERY memory consuming app. So be warned.

以上在理论上是可以的,但在实践中它会导致非常消耗内存的应用程序。所以要小心。

And please don't downvote me, this is only a theoretical dispute.

请不要贬低我,这只是理论上的争议。

回答by Brian

if you mean after the page has loaded you will need to use javascript/ajax/jquery to do so.

如果您的意思是在页面加载后,您将需要使用 javascript/ajax/jquery 来执行此操作。

回答by Brian

If you really must do it within the same PHP script, the cleanest way would be a fork.

如果您真的必须在同一个 PHP 脚本中执行此操作,最简洁的方法是使用fork

Or if that's not possible, here's a really bad hackish way of doing it:

或者,如果这是不可能的,这里有一个非常糟糕的黑客方法:

<?php
ignore_user_abort(1);

page_output_stuff();
// ...

flush();
sleep(10);
do_something_after_script();
?>

If you're doing this to output stuff to the user after a delay, the above canbe made to work but it's a really ugly way of doing it. Just use AJAX instead.

如果您这样做是为了在延迟后向用户输出内容,则可以使上述内容起作用,但这是一种非常丑陋的做法。只需使用 AJAX。

回答by Julien Marodon

I wanted to do the same thing, to be notified at each hit my resume got. With flush() after all data sent then the DB and mail operations: the page on the client is fully rendered but the downloading progress bar is still present until the script is fully terminated.

我想做同样的事情,在我的简历每次点击时收到通知。在发送完所有数据后使用flush(),然后进行数据库和邮件操作:客户端上的页面已完全呈现,但下载进度条仍然存在,直到脚本完全终止。

I wanted to keep the whole stuff server-side (to allow the generated HTML file to be cleanly usable offline without giving errors) so JS wasn't an option.

我想将整个内容保留在服务器端(以允许生成的 HTML 文件在离线时完全可用而不会出错),因此 JS 不是一个选项。

I eventually ended simply appending a line with parameters to a text file, add a cron job every minute that compares this file size with the latest sent version and this bash script handles all the lenghty functions while the 9k page still loads and renders in a fraction of a second.

我最终只是简单地在文本文件中添加了一行参数,每分钟添加一个 cron 作业,将这个文件大小与最新发送的版本进行比较,这个 bash 脚本处理所有的长函数,而 9k 页面仍然加载和呈现一小部分一秒钟。

Unfortunately this method still has a up to 1 minute delay but still simple:

不幸的是,这种方法仍然有长达 1 分钟的延迟,但仍然很简单:

#!/bin/sh
FLOG=/home/web/traceur/cvaccess.txt

if [ -e $FLOG ]; then
    if [ ! -e $FLOG.sent ]; then touch $FLOG.sent; fi;
    SENT_LINES=$(wc -l $FLOG.sent | cut -d " " -f 1)

    # No disk write if no new-data
    if [ $(wc -l $FLOG | cut -d " " -f 1) -gt $SENT_LINES ]; then
        cp -f $FLOG $FLOG.intr
        NEW_LINES=$(wc -l $FLOG.intr | cut -d " " -f 1)
        TO_SEND=$(( $NEW_LINES - $SENT_LINES ))
        tail -n $TO_SEND $FLOG.intr > $FLOG.diff

        mailx -s "Nouvelle consultation du CV" -r "HAL <[email protected]>" [email protected] < $FLOG.diff
        rm $FLOG.diff
        mv -f $FLOG.intr $FLOG.sent
    fi
fi

And the page is at: http://www.jmd-tech.com/cv-julien-marodon.html, the PHP code is nothing more than those 3 lines at the end of the previously plain HTML file:

该页面位于:http: //www.jmd-tech.com/cv-julien-marodon.html,PHP 代码只不过是之前纯 HTML 文件末尾的那 3 行:

<?php
// Enregistrement log
$ligne=$_SERVER["REMOTE_ADDR"]."\t".$_SERVER["HTTP_USER_AGENT"]."\t".$_SERVER["HTTP_REFERER"]."\t".date("Y-m-d H:i:s");
$fic=fopen("/home/web/traceur/cvaccess.txt","a");
if ($fic) { fwrite($fic,$ligne."\n"); fclose($fic); }
?>

If i wanted to make a near-instant (<1s) or a 10 second delay version, i think the way to go would be using a daemon instead of a cron job and some kind of inter-process communication, probably a listening socket which the PHP script would fsockopen() for sending data and closing (fast), then the daemon proceeds by himself with lenghty operations.

如果我想制作一个近乎即时(<1s)或 10 秒延迟的版本,我认为要走的路是使用守护进程而不是 cron 作业和某种进程间通信,可能是一个侦听套接字PHP 脚本将 fsockopen() 用于发送数据和关闭(快速),然后守护进程自己进行长时间的操作。

回答by Kablam

You can create a Javascript timer that calls the function every ten seconds.

您可以创建一个 Javascript 计时器,每十秒调用一次该函数。

Tutorial here

教程在这里

(10 seconds is 10000 milliseconds)

(10 秒是 10000 毫秒)

回答by Deniss Kozlovs

There's no way you can do it with PHP, except maybe using some crontab / loop with sleep() and file_get_contents(). Or use javascript/ajax as previously mentioned.

你无法用 PHP 做到这一点,除非可能使用一些带有 sleep() 和 file_get_contents() 的 crontab / 循环。或者使用前面提到的 javascript/ajax。

回答by Mohamed

Php is a servide scripting language, and can't detect if the page is loaded or not. so you have to use client side script javascript.

Php 是一种服务脚本语言,无法检测页面是否已加载。所以你必须使用客户端脚本javascript。