Skip to content
Advertisement

How can I make my server allow my PHP script process to run for 75 minutes instead of disconnecting after only 45 minutes?

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();

?>  

Advertisement

Answer

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.

  • The 1st job creates a file and saves data to it.
  • The 2nd job appends data onto the same file for the rest of stream duration.

Every script works for 40 minutes only in order to avoid the server killing the script.

Here is my final code:

<?php

// Ignore user aborts and allow the script to run forever
ignore_user_abort(true);
set_time_limit(0);

$path = __DIR__ . '/save.mp3';

$stream = fopen( 'my url', "rb" );
$save = fopen($path, "a");
$startTime = time();
$finishTime = $startTime + (60*40);
while ( $finishTime >= time() ){

    $response = fread( $stream, 8192 ); 
    fwrite($save,$response);
}

fclose( $stream );
fclose($save);
exit();

?>
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement