Script Caching with PHP
ore file operations etc.) You might also tailor it to your needs – instead of assuming the creating script end with ".php", for example, you could configure it to be ".php3", ".pl" or some other variation. Yet this script does the job and can be used as it is. <?php // example caching script // get the static HTML file’s location $cache_file = $REQUEST_URI; // find out the URL of the dynamic script // which creates the static file. $maker_URL = str_replace ( "/cache/" , "/" , $cache_file ); $maker_URL = str_replace ( ".html" , "" , $maker_URL ); $last_slash = strrpos ( $maker_URL , "/" ); // find out the creating script’s name // and make sure it exists. $script = substr ( $maker_URL , 0 , $last_slash ) . ".php"; $find = $DOCUMENT_ROOT . $script; if ( !file_exists ( $find )) { // if the file does not exist, show a // File Not Found error - // echo ("Couldn’t find $REQUEST_URI"); // you can put a nice page here... exit; // but don’t forget to exit ! } // now parse the query string // here, "_" means "=" and "__" means "&" // These rules are just personal preferences $query_str = "?" . substr ( $maker_URL , $last_slash+1 ); $query_str = str_replace ( "__" , "&" , $query_str ); $query_str = str_replace ( "_" , "=" , $query_str ); // and now create the full maker_URL $maker_URL = "http://" . $HTTP_HOST . $script . $query_str; // open the maker script and read its output $read = fopen ( $maker_URL , "r" ); if ( !$read ) { echo ( "Could not open $maker_URL" ); exit; } $HTML_output = ""; // read the HTML output while displaying it while ($line = fgets ( $read , 256 )) { $HTML_output.= $line; echo $line; } fclose ( $read ); // finally, save the HTML output // in a cache file. $write = fopen ( $DOCUMENT_ROOT . $cache_file , "w" ); |
查看所有评论
