I am trying to save an mp4 file from audio live stream by PHP script initiated by cron job.
It’s expected to work for 75 minutes, but the problem is it runs for only 45 minutes. I found that the server may disconnect the process and not allow the script to run for such a long time.
I checked my PHP ini settings from CPanel and I found this:
allow_url_fopen
Enabled
display_errors
Disabled
enable_dl
Disabled
file_uploads
Enabled
max_execution_time
30
max_input_time
60
max_input_vars
1000
memory_limit
256M
post_max_size
512M
session.gc_maxlifetime
1440
session.save_path
/var/cpanel/php/sessions/ea-php74
upload_max_filesize
512M
zlib.output_compression
Disabled
This is my PHP script:
<?php
function flush_buffers(){
ob_end_flush();
ob_flush();
flush();
ob_start();
}
$path = __DIR__ . '/save.mp4';
$stream = fopen( 'request url', "rb" );
$save = fopen($path, "w");
$startTime = time();
$finishTime = $startTime + (60*75);
while ( $finishTime >= time() ){
$response = fread( $stream, 8192 );
fwrite($save,$response);
flush_buffers();
}
fclose( $stream );
fclose($save);
exit();
?>
2
Answers
The problem is because of shared server hosting limitations. The shared server does not allow any script to run for more than 45 minutes (VPS & dedicated run normally).
I get around this issue by run 2 separate cron jobs (40 minutes between every job) instead of one big one.
Every script works for 40 minutes only in order to avoid the server killing the script.
Here is my final code:
You may try
ignore_user_abort()
function withset_time_limit()
function. Theignore_user_abort(true)
function with the argumenttrue
lets the script run even if the client is disconnected. And set zero as the argument to theset_time_limit(0)
function to run the script forever.So add the following code snippet to the top of your script. This could help you.