You might not consider this a pure PHP solution because there is anonload
parameter specified for the<BODY>
tag. Then again, purity is not all it's cracked up to be. But I throw this out as a technique you could use to give the user a running pseudo "progress bar" and your script would only get interrupted when you wanted it to and you would be able to pass back to the script any restart parameters. In this demo, the only "restart parameters" being passed back are successive integers that drive the progress bar, but you can get the idea:
<?php
if (!isset($_REQUEST['progress'])) {
// initially no parameters specified, so use starting value of 0:
$progress = 0;
}
else {
$progress = (int)$_REQUEST['progress'];
}
// increment progress:
$progress++;
// draw progress bar:
$progress_bar = str_repeat ('+' , $progress);
// simulate doing some work:
sleep(5);
// simulate being done or not:
$done = $progress == 5;
?>
<html>
<head>
<title>Test</title>
</head>
<?php if (!$done) { ?>
<body onload="document.f.submit();">
<?php } else { ?>
<body>
<?php } ?>
Progress: <?= $progress_bar ?><br>
<?php if (!$done) { ?>
<form name="f" method="post">
<input type="hidden" name="progress" value="<?= $progress ?>">
<!-- add any other hidden variables you need to resume where you left off -->
</form>
<?php } else { ?>
Done!
<?php } ?>
</body>
</html>
For this, I would use import.lock file. Here is my suggested workflow:
For progress to implemented you count all created junks (chunk1.json, chunk2.json ...), and let's say you we 100 chunks and we processed 15 already, import.lock have a value of 15 so it means 15% done. After refresh we taking 16 chunks (chunk16.json).
After every junk is done we delete it from file system.
Implementation example
Here is my implementation example, tested and working: Link to the repository: https://github.com/RomkaLTU/php-progress-case You still need to implement JSON files generation. I have used session in this example to track progress as user Mawg says reinstate Monica suggested.
And you may need to adjust header("refresh: 2") and chunk size.
session_start();
$dataDir = __DIR__ . DIRECTORY_SEPARATOR . 'data';
$chunkFiles = array_values(array_diff(scandir($dataDir), ['..', '.']));
$chunksCount = count($chunkFiles);
$currentChunk = $_SESSION['currentChunk'] ?? 1;
// need to identify current index of proccessing file
// need to follow naming convention here or make something smarter
$currentChunkIndex = array_search('chunk_' . $currentChunk . '.json', $chunkFiles);
if (isset($chunkFiles[$currentChunkIndex])) {
$chunkFilePath = $dataDir . DIRECTORY_SEPARATOR . $chunkFiles[$currentChunkIndex];
$dataJson = file_get_contents($chunkFilePath);
$data = json_decode($dataJson, true);
foreach ($data as $item) {
// @TODO do something with a $item
}
unlink($chunkFilePath);
$_SESSION['currentChunk'] = $currentChunk + 1;
if (!empty($chunksCount)) {
header("refresh: 2");
} else {
$_SESSION['currentChunk'] = 1;
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<?php echo $chunksCount * 3 . ' records left...'; ?>
</body>
</html>
Ideally a script that "could potentially take quite some time" must not be executed on the fly via HTTP. The best practice is to queue the job, the http request only add the job into the queue and does not run it directly, so it is a fast and predictable operation that will not timeout, then the job is run independantly of the HTTP server, the job is executed by a queue manager with larger or no timeout on resources. You can periodically poll via HTTP from client side (with HTTP refresh or Javascript) to display some progress status to the user.
A minimalist but perfectly viable queue manager could be a cronjob launching a simple PHP Cli script that read and write some persistent locked data about jobs (file, database, ...). For more complex use cases (prioritizing or distributing load), it may be useful to use a dedicated queue manager software.
If cron is not an option, you may also run a PHP CLI script daemonized as a 100% pure PHP queue manager.
To main concept here is to decouple running unpredictable or long jobs from serving HTML pages through stateless HTTP in a predictable and fast way.
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Find the answer in similar questions on our website.
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.
PHP (from the English Hypertext Preprocessor - hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites.
The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/
JavaScript is a multi-paradigm language that supports event-driven, functional, and mandatory (including object-oriented and prototype-based) programming types. Originally JavaScript was only used on the client side. JavaScript is now still used as a server-side programming language. To summarize, we can say that JavaScript is the language of the Internet.
https://www.javascript.com/
DBMS is a database management system. It is designed to change, search, add and delete information in the database. There are many DBMSs designed for similar purposes with different features. One of the most popular is MySQL.
It is a software tool designed to work with relational SQL databases. It is easy to learn even for site owners who are not professional programmers or administrators. MySQL DBMS also allows you to export and import data, which is convenient when moving large amounts of information.
https://www.mysql.com/
HTML (English "hyper text markup language" - hypertext markup language) is a special markup language that is used to create sites on the Internet.
Browsers understand html perfectly and can interpret it in an understandable way. In general, any page on the site is html-code, which the browser translates into a user-friendly form. By the way, the code of any page is available to everyone.
https://www.w3.org/html/
Welcome to the Q&A site for web developers. Here you can ask a question about the problem you are facing and get answers from other experts. We have created a user-friendly interface so that you can quickly and free of charge ask a question about a web programming problem. We also invite other experts to join our community and help other members who ask questions. In addition, you can use our search for questions with a solution.
Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.
Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.