Как сделать progress bar php ajax через file_get_contents()?

Пользователь

от jerrold_langworth , в категории: PHP , 9 месяцев назад

Как сделать progress bar php ajax через file_get_contents()?

Facebook Vk Ok Twitter LinkedIn Telegram Whatsapp

2 ответа

Пользователь

от alisa.bahringer , 9 месяцев назад

@jerrold_langworth 

To create a progress bar in PHP using Ajax and file_get_contents() function, you can follow the steps below:

  1. Set up the HTML structure with a progress bar container and a button to initiate the process:
1
2
3
4
<div id="progress-bar-container">
    <div id="progress-bar"></div>
</div>
<button id="start-process">Start Process</button>


  1. Add CSS styles to the progress bar container and button:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<style>
#progress-bar-container {
    width: 200px;
    border: 1px solid #ccc;
    padding: 5px;
}

#progress-bar {
    background: #4CAF50;
    height: 20px;
    width: 0;
}

#start-process {
    margin-top: 10px;
}
</style>


  1. Create a JavaScript function to initiate the Ajax request and update the progress bar:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<script>
document.getElementById('start-process').onclick = function() {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'process.php', true);
    
    // Update progress bar
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 3 && xhr.status === 200) {
            var totalSize = xhr.getResponseHeader('Content-Length');
            var loadedSize = xhr.responseText.length;
            var progress = Math.round((loadedSize / totalSize) * 100);
            document.getElementById('progress-bar').style.width = progress + '%';
        }
    }

    xhr.send();
}
</script>


  1. Create a PHP file process.php to perform the desired process and output the response:
1
2
3
4
5
6
7
8
<?php
// Start your process here
// Make sure to update the relevant logic according to your requirements

$file = file_get_contents('https://example.com/large_file.txt');

echo $file;
?>


Note: This example assumes that you want to track the progress based on the content length of the response. However, file_get_contents() might not provide real-time progress information. In this case, you may need to use more advanced techniques like curl or server-side scripts to provide actual progress updates.

Пользователь

от richie_mayert , 18 дней назад

@jerrold_langworth 

The provided solution outlines the steps to create a progress bar in PHP using Ajax and file_get_contents(). However, it's essential to note that file_get_contents() is a blocking function, meaning it fetches the entire content of a file before returning any data. So, tracking real-time progress with file_get_contents() might not be optimal.


If you still want to use file_get_contents() and desire real-time progress tracking, you may consider breaking down the file fetching process into chunks and then updating the progress bar based on the downloaded chunk size.


Here's an updated version of the process.php file with chunked data fetching:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?php
// Start your file fetching process here

// URL to the file to download
$fileUrl = 'https://example.com/large_file.txt';

// Open the file for reading
$fp = fopen($fileUrl, 'r');
if (!$fp) {
    die("Error opening file.");
}

// Get the total file size
$totalSize = intval($http_response_header[8]);

// Chunk size for each iteration
$chunkSize = 1024; // 1KB

$loadedSize = 0;

while (!feof($fp)) {
    $buffer = fread($fp, $chunkSize);
    $loadedSize += strlen($buffer);

    // Send the buffer to output
    echo $buffer;

    // Flush the output buffer
    ob_flush();
    flush();

    // Calculate progress
    $progress = round(($loadedSize / $totalSize) * 100);
    header('X-Progress: ' . $progress);
}

// Close the file
fclose($fp);
?>


In the JavaScript part, you can use the progress event of XMLHttpRequest to fetch the progress header set in the PHP script and update the progress bar:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
var xhr = new XMLHttpRequest();
xhr.open('GET', 'process.php', true);

xhr.onprogress = function (event) {
    if (event.lengthComputable) {
        var progress = Math.round((event.loaded / event.total) * 100);
        document.getElementById('progress-bar').style.width = progress + '%';
    }
};

xhr.send();


By using this approach, you can achieve a more dynamic progress bar based on the chunks being fetched, providing real-time progress updates during the file fetching process.