skip to Main Content

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


  1. Chosen as BEST 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();
    
    ?>
    

  2. You may try ignore_user_abort() function with set_time_limit() function. The ignore_user_abort(true) function with the argument true lets the script run even if the client is disconnected. And set zero as the argument to the set_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.

    <?php
    
    // Ignore user aborts and allow the script to run forever
    ignore_user_abort(true);
    set_time_limit(0);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search