Simple static page generation process_PHP tutorial
I have always used smart cache, but I feel like I still need to make one myself to feel comfortable. There are many awesome people on the Internet who have relatively complete functions. I plan to make a simple one myself first and then gradually expand it. I made a relatively simple one in the past two days and recorded it at hi.baidu.net/alex_wang58.
1. Related technical keywords used: PHP, Apache,
mod_rewrite (RewriteCond, RewriteRule) address rewriting,
Ob series function buffer
file_put_contents generates html
2. Process: The user sends a request url?id=x to determine whether the article exists
(1) If it exists, go directly to the corresponding Html page.
(2) There is no need to read database data through php, then generate html files and store them in the specified directory.
3. Implementation method:
(1) Address rewriting uses the RewriteRule instruction in Apahce's mod_rewrite module to implement rewriting (for the opening and simple rules of mod_rewrite, see another article on this blog http://hi.baidu.com/alex%5Fwang5... 0346ffb3fb952e.html ).
(2) To determine whether an article exists, use the RewriteCond instruction in Apahce’s mod_rewrite module
(3) Generate html file:
ob_star() opens the buffer, includes the php that reads the article, and then uses file_put_contents to write the obtained buffer content to the specified HTMl file.
4. Code
Contents of the .htaccess file in the /Test directory:
RewriteEngine On
RewriteRule ^index.html$ /news.php [L]
RewriteCond %{REQUEST_FILENAME} !-s
RewriteRule ^html/news_([0-9]+).html$ getnews.php?id=$1 [L]
Access to news.php will be implemented through localhost/Test/index.html and implemented by the second sentence RewriteRule ^index.html$ Test/news.php [L]
news.php =============================> news.php will list the article title links.
header("Content-Type:text/html; charset=gbk"); //To prevent garbled characters
mysql_connect("localhost","root","");
mysql_query('SET NAMES gbk'); //The gbk encoding used by my database, please adjust it according to your actual situation
mysql_select_db("test");
$sql = "SELECT `id`,`title` FROM `arc` order by `id` DESC";
$rs = mysql_query($sql);
while($row = mysql_fetch_array($rs) ){
echo "$row[title]
";
}
?>
For example, php static page implementation
is generated
When a link is clicked to make a request to http://localhost/Test/html/news_3.html
Apache will determine whether news_3.html exists, based on the third sentence
in .htaccess
RewriteCond %{REQUEST_FILENAME} !-s
Implementation:
RewriteCond is the "condition for directed rewriting to occur". REQUEST_FILENAME This parameter is "the file name requested by the client"
'-s' (is a non-empty regular file [size]) tests whether the specified file exists and is a regular file with a size greater than 0. ! Represents the inversion of the matching condition.
So the sentence RewriteCond means that when the requested link does not exist, the following RewriteRule rules will be executed.
So when the requested news_3.html does not exist, the address will be rewritten for getnews.php?id=3 to process (otherwise, if news_3.html exists, the html file will be loaded directly).
getnews.php ===================>Function: Determine the integrity of parameter transmission, and call the corresponding file to generate an html file.
$id =$_GET['id'];
$root =& $_SERVER['DOCUMENT_ROOT'];
$filename = "news_".$id.".html";
$file = $root."/Test/html/".$filename;
ob_start();
include($root."/Test/newsDetail.php");
file_put_contents($file,ob_get_contents());
ob_end_flush();
?>
newsDetail.php ====================> Read data from the database and generate news content, which is captured by getnews.php
header("Content-Type:text/html; charset=gbk");
if( isset($_GET['id']) ){
$id = & $_GET['id'];
}else{
header("Location: [url]http://127.0.0.1/lean/Test/html/news_failed.html[/url]");
exit();
}
mysql_connect("localhost","root","");
mysql_query('SET NAMES gbk');
mysql_select_db("test");
$id =$_GET['id'];
$sql = "SELECT `news` FROM `arc` WHERE `id`=$id";
$rs = mysql_query($sql);
while($row = mysql_fetch_array($rs) ){
echo $row['news'];
}
?>
This will generate an html file named news_article ID.html in the /Test/html directory.
PS: Initially, PHP's built-in file_exists() judgment was used to determine whether the corresponding html page existed, instead of Apache's RewriteCond, that is, there was no RewriteCond %{REQUEST_FILENAME} !-s. It seems feasible, but the result will be a "cyclic redirection" problem.
When news_3.html does not exist, we need to use getnews.php to generate news_3.html. After the generation is completed, we need to redirect to news_3.html, so another request mod_rewrite is initiated to rewrite news_3.html to getnews.php?id= 3 This creates an endless loop. Therefore, the judgment of file existence is handed over to RewriteCond, and the rewrite rule is enabled only when the specified html file does not exist. This way the problem of circular redirection disappears.
out of fopen is not used to open newsDetail.php, and then fwrite the generated content into an html file, and then include to output the static page. Later, under the reminder of fhjr999, it was changed to: include newDetail.php into getnews.php, put the generated content into the buffer through the ob series function, and then generate the html file. The efficiency of ob is about 20 times that of the former.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The hard disk serial number is an important identifier of the hard disk and is usually used to uniquely identify the hard disk and identify the hardware. In some cases, we may need to query the hard drive serial number, such as when installing an operating system, finding the correct device driver, or performing hard drive repairs. This article will introduce some simple methods to help you check the hard drive serial number. Method 1: Use Windows Command Prompt to open the command prompt. In Windows system, press Win+R keys, enter "cmd" and press Enter key to open the command

How to set up keyboard startup on Gigabyte's motherboard. First, if it needs to support keyboard startup, it must be a PS2 keyboard! ! The setting steps are as follows: Step 1: Press Del or F2 to enter the BIOS after booting, and go to the Advanced (Advanced) mode of the BIOS. Ordinary motherboards enter the EZ (Easy) mode of the motherboard by default. You need to press F7 to switch to the Advanced mode. ROG series motherboards enter the BIOS by default. Advanced mode (we use Simplified Chinese to demonstrate) Step 2: Select to - [Advanced] - [Advanced Power Management (APM)] Step 3: Find the option [Wake up by PS2 keyboard] Step 4: This option The default is Disabled. After pulling down, you can see three different setting options, namely press [space bar] to turn on the computer, press group

1. Processor When choosing a computer configuration, the processor is one of the most important components. For playing games like CS, the performance of the processor directly affects the smoothness and response speed of the game. It is recommended to choose Intel Core i5 or i7 series processors because they have powerful multi-core processing capabilities and high frequencies, and can easily cope with the high requirements of CS. 2. Graphics card Graphics card is one of the important factors in game performance. For shooting games such as CS, the performance of the graphics card directly affects the clarity and smoothness of the game screen. It is recommended to choose NVIDIA GeForce GTX series or AMD Radeon RX series graphics cards. They have excellent graphics processing capabilities and high frame rate output, and can provide a better gaming experience. 3. Memory power

SPDIFOUT connection line sequence on the motherboard. Recently, I encountered a problem regarding the wiring sequence of the wires. I checked online. Some information says that 1, 2, and 4 correspond to out, +5V, and ground; while other information says that 1, 2, and 4 correspond to out, ground, and +5V. The best way is to check your motherboard manual. If you can't find the manual, you can use a multimeter to measure it. Find the ground first, then you can determine the order of the rest of the wiring. How to connect motherboard VDG wiring When connecting the VDG wiring of the motherboard, you need to plug one end of the VGA cable into the VGA interface of the monitor and the other end into the VGA interface of the computer's graphics card. Please be careful not to plug it into the motherboard's VGA port. Once connected, you can

How to write a simple student performance report generator using Java? Student Performance Report Generator is a tool that helps teachers or educators quickly generate student performance reports. This article will introduce how to use Java to write a simple student performance report generator. First, we need to define the student object and student grade object. The student object contains basic information such as the student's name and student number, while the student score object contains information such as the student's subject scores and average grade. The following is the definition of a simple student object: public

How to write a simple online reservation system through PHP. With the popularity of the Internet and users' pursuit of convenience, online reservation systems are becoming more and more popular. Whether it is a restaurant, hospital, beauty salon or other service industry, a simple online reservation system can improve efficiency and provide users with a better service experience. This article will introduce how to use PHP to write a simple online reservation system and provide specific code examples. Create database and tables First, we need to create a database to store reservation information. In MyS

Glodon Software is a software company focusing on the field of building informatization. Its products are widely used in all aspects of architectural design, construction, and operation. Due to the complex functions and large data volume of Glodon software, it requires high computer configuration. This article will elaborate on the computer configuration recommendations of Glodon Software from many aspects to help readers choose a suitable computer configuration processor. Glodon Software requires a large amount of data calculation and processing when performing architectural design, simulation and other operations. Therefore, the requirements for the processor are higher. It is recommended to choose a multi-core, high-frequency processor, such as Intel i7 series or AMD Ryzen series. These processors have strong computing power and multi-thread processing capabilities, and can better meet the needs of Glodon software. Memory Memory is affecting computing

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make
