Jump to content

Recommended Posts

Hi, I understand that you can use cron jobs to achieve this, but I can't use cron in my case.

I have a script that will copy weather details off of the Government of Canada site and put it on my site. If the site gets popular, I don't want the script to fetch the info every time the page refreshes. So far, I have this script put together, however all I can say is that it "doesn't work" I only get a blank page with no errors from my host.

 

The index will see if the script has been ran before 2000 seconds, if not it will execute weather.php, if it has, it will show the buffered results from buffer.log. When weather.php executes, it echos the result to the page and also writes the html to buffer.log

 

This is in index.php

<?php
                   $lastRunLog = '/lastrun.log';
			$lastRunBuf = '/buffer.log';

			if (file_exists($lastRunLog) && file_exists($lastRunBuf)) {
			    $lastRun = file_get_contents($lastRunLog);
			    if (time() - $lastRun >= 2000) {
         				$cron = file_get_contents('weather.php');
			        file_put_contents($lastRunLog, time());
					eval($cron);
				}
				elseif {
					$buffer = file_get_contents($lastRunBuf);
					echo "$buffer"; 
				}
			}
            ?>

 

weather.php

<?php
                $url = "http://www.weatheroffice.gc.ca/city/pages/on-69_metric_e.html";
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 100);
                $text = curl_exec($ch);  
                
			$buffer = "buffer.log";
			$fh = fopen($buffer, 'w') or die("Can not open buffer");

                $exploded = explode('<p class="temperature">',$text); 
                $result = explode('<sup>',$exploded[1]);
                
                $exploded2 = explode('<img id="currentimg" src="/weathericons/',$text);
                $idnum = explode('.gif"',$exploded2[1]); 
            
                if ($idnum[0] == ''){
                    $idnum[0] = '50';
                }
            
                $exploded3 = explode('<dt>Condition:</dt>',$text);
                $iden = explode('</dd>',$exploded3[1]); 
                
                curl_close($ch); 
                
                $iden2 = ereg_replace("<dd>", "", $iden[0]);
                $iden3 = ereg_replace("  ", "", $iden2);
                $num = intval($idnum[0]);
                
                if($num < 10){
				$stringdata1 = "<img src=\"images/weather/0$num.png\" style=\"border-style: none\">";
                    echo "$stringdata1";
				fwrite($fh, $stringdata1);
                }
                if($num > 9 && $num < 50){
				$stringdata2 = "<img src=\"images/weather/$num.png\" style=\"border-style: none\">";
                    echo "$stringdata2";
				fwrite($fh, $stringdata2);
                }
                if($num == 50){
				$stringdata3 = "<img src=\"images/weather/31.png\" style=\"border-style: none\">";
                    echo "$stringdata3";
				fwrite($fh, $stringdata3);
                }
                else{
				$stringdata4 = " ";
                    echo "$stringdata4";
				fwrite($fh, $stringdata4);
                }
			$stringdata5 = "  <span id=\"number\">$result[0]</span> $iden3";
                echo "$stringdata5";
			fwrite($fh, $stringdata5);
                
			fclose($fh);

?>

 

buffer.log and lastrun.log exist and is blank.

 

Thanks for reading. Hopefully its a stupid mistake, I'm still pretty new to PHP. My apologies for the bad spacing, some formatting issues with Dreamweaver.

Link to comment
https://forums.phpfreaks.com/topic/183436-only-running-php-every-2000-seconds/
Share on other sites

Blank pages are usually due to fatal parse or fatal runtime errors. In your case -

 

Parse error: syntax error, unexpected '{', expecting '(' in your_file.php on line 12

 

You should be learning php, developing php code, and debugging php code on a system with error_reporting set to E_ALL and display_errors set to ON in your master php.ini so that php will help you. (Confirm the actual settings using a phpinfo() statement in case the php.ini that you are changing is not the one that php is using.) You will save a ton of time.

The logic seems a little odd. I would create a function to return the content and have that function do the logic of pulling from a cache file or getting new content. Also, no need to have a log file with the time when the buffer (should be called cache) file was last updated. Just check the last modified time of the cache file.

 

However, your current code should be producing an error because of this line

elseif {
   $buffer = file_get_contents($lastRunBuf);

 

There is an elseif with no condition.

Oh wow... sorry for wasting your guys' time. I'm sure you all had a little chuckle at the ifelse without a condition.

Yes, thats what fixed it. Along with just putting the code from weather.php right in the index. mjdamato, thanks for the enlightening perspective, but I'll keep the log file... It works now and thats all I need.

 

PFMaBiSmAd, I tried that line of code in your signature while I still had the error but nothing changed. I don't have access to the php.ini file. I'm not hosting this myself. I guess my host disabled it?  It's free so I can't complain.

 

Thanks again both of you.

I was bored and found this an interesting activity. Here is a rewrite of what you have above in what I believe is a more efficient manner - especially for the logic of parsing the external page.

 

<?php

//This function is called when the cached data is nonexistent or is stale
//Will screen scrape the URL and parse the data
function getWeatherData()
{
    $url = "http://www.weatheroffice.gc.ca/city/pages/on-69_metric_e.html";
    $urlContents = file_get_contents($url);
    preg_match('/weathericons\/(\d*)\.gif/', $urlContents, $idNumMatch);
    $idNumber = $idNumMatch[1];
    preg_match('/<dt>Condition:<\/dt>.*?<dd>(.*?)<\/dd>/s', $urlContents, $conditionMatch);
    $condition = $conditionMatch[1];

    if ($idNumber=='50')
    {
        $idNumber = '31';
    }

    if (is_numeric($idNumber) && $idNumber>0 && $idNumber<50)
    {
        $output = "<img src=\"images/weather/{$idNumber}.png\" style=\"border-style:none;\">";;
    }
    else
    {
        $output = ' ';
    }

    $output .= "  <span id=\"number\">$condition</span> $iden3";
    return $output;
}

//This function is "generic" in that you can use it in any situation
//where you would like to store cached data for a period of time
function getCurrentData($cacheFile, $getDataFunction, $secondsToCache)
{
    //Check if cache file exists & is current
    if (file_exists($cacheFile) && (time()-filemtime($cacheFile))<$secondsToCache)
    {
        //Read data from cache
        $cacheFileHandle = fopen($cacheFile, 'r');
        $currentData = fread($cacheFileHandle, filesize($cacheFile));
        fclose($cacheFileHandle);
    }
    else
    {
        //Get current data and write to cache
        $currentData = call_user_func($getDataFunction);
	$cacheFileHandle = fopen($cacheFile, 'w');
        fwrite($cacheFileHandle, $currentData);
	fclose($cacheFileHandle);
    }

    return $currentData;
}

//Get the "current" data by calling the function passing the following:
// - cache file name
// - function to refresh the cache data
// - seconds for the cache file to persist

$weatherData = getCurrentData('cache\weather.txt', getWeatherData, 2000);
echo $weatherData;

?>

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.