Page 1 of 1

Stop and skip to next function

Posted: Fri Apr 10, 2009 11:51 am
by aurorawx
Hello. I'm writing a code to print text on an image. I'm defining the images in the code, however there is a change they may not exist. If the script runs and one of the images don't exist, the entire script will fail.

I'm looking for a way at the beginning of the function to check if the file exists, and if it does not, then stop, but allow the file to continue. I don't want the entire script to cease if certain files are missing. For example (see bottom of script), if 'thr.png' does not exist, stop function, and start the next function ('bv1.png').

Code: Select all

<?php
 
function radar_status($radar)
{
    $now = time();
    $now -= 720; // 12 minutes
 
    $filetime = filemtime("/".$radar);     
    if ($now = $filetime) 
        $active = ''; 
    else 
        $active = 'This image is not current';
 
 
 
    header("Content-Type: image/png");
 
    $im = imagecreatefrompng($radar); 
 
    $red = ImageColorAllocate($im, 255, 0, 0);
 
    $start_x = 250;
    $start_y = 375;
 
    imagettftext($im, 24, 0, $start_x, $start_y, $red, 'ArialBold.ttf', $active);
 
    imagepng($im,$radar);
 
    imagedestroy($im);
}
 
 
radar_status('br1.png');
radar_status('br2.png');
radar_status('br3.png');
radar_status('br4.png');
radar_status('br248.png');
radar_status('srv1.png');
radar_status('srv2.png');
radar_status('thr.png');
radar_status('bv1.png');
radar_status('bv2.png');
 
?>

Thank you!

Re: Stop and skip to next function

Posted: Fri Apr 10, 2009 12:46 pm
by Drachlen
Hi there,

Here's a simple solution for your problem:

Code: Select all

function radar_status($radar)
{
 
    if( !file_exists($radar) )
    {
      //the file does NOT exist, exit the function
      return 0;    
    }
    $now = time();
    $now -= 720; // 12 minutes
 
    $filetime = filemtime("/".$radar);    
    if ($now = $filetime)
        $active = '';
    else
         $active = 'This image is not current';
 
  
  
     header("Content-Type: image/png");
  
     $im = imagecreatefrompng($radar);
  
     $red = ImageColorAllocate($im, 255, 0, 0);
  
     $start_x = 250;
     $start_y = 375;
  
     imagettftext($im, 24, 0, $start_x, $start_y, $red, 'ArialBold.ttf', $active);
  
     imagepng($im,$radar);
  
     imagedestroy($im);
 }
All I have done is added one if-statement at the beginning of your function call:

Code: Select all

 
    if( !file_exists($radar) )
    {
      //the file does NOT exist, exit the function
      return 0;    
    }
the function file_exists literally is checking whether the file exists or not--if it doesn't, the return 0; call simply ends the function at that point and the next function call begins.

I hope this is helpful.

Good luck.

Re: Stop and skip to next function

Posted: Fri Apr 10, 2009 12:50 pm
by aurorawx
Thanks for that! Much appreciated.