search
HomeBackend DevelopmentPHP Tutorialhttp://www.56.com/m2v/?magic=1 Detailed explanation of generating static pages with PHP

Let's review some basic concepts first.
 1. PHP scripts and dynamic pages.
  PHP script is a server-side script program that can be mixed with HTML files through methods such as embedding, or it can process user requests in the form of templates in the form of classes, function encapsulation, etc. One way or another, the basics of it are this. The client makes a request for a certain page -----> The WEB server introduces the designated corresponding script for processing -----> The script is loaded into the server -----> Parsed by PHP specified by the server The script is parsed by the browser to form an HTML language form----> The parsed HTML statement is sent back to the browser in the form of a package. It is not difficult to see from this that after the page is sent to the browser, PHP no longer exists and has been converted and parsed into HTML statements. The client request is a dynamic file. In fact, there is no real file there. PHP parses it into the corresponding page and then sends it back to the browser. This way of handling pages is called "dynamic pages".
 Second, static page.
 Static pages refer to pages that actually exist on the server side and only contain HTML and JS, CSS and other client-side scripts. The way it is handled is. The client makes a request for a certain page----> The WEB server confirms and loads a certain page----> The WEB server passes the page back to the browser in the form of a package. From this process, we can compare the dynamic pages and we can see. Dynamic pages need to be parsed by the PHP parser of the WEB server, and usually need to connect to the database and perform database access operations before they can form an HTML language information package; while static pages do not need to be parsed or connected to the database, and can be sent directly, which can greatly Reduce server pressure, improve server load capacity, and greatly improve page opening speed and overall website opening speed. But its disadvantage is that the request cannot be processed dynamically, and the file must actually exist on the server.
 Three, templates and template analysis.
 The template means that the content html file has not yet been filled in. For example:
temp.html

{ title }

this is a { file } file's templates


PHP processing:
templetest.php
$title = "TwoMax International test template";
$file = "TwoMax Inter test template,
author: Matrix@Two_Max";
$fp = fopen ("temp.html","r");
$content = fread ($fp,filesize ("temp.html"));
$content .= str_replace ("{ file }",$file,$content ; content) into the template processing process. Usually with the help of template classes. Currently, the more popular template parsing classes include phplib, smarty, fastsmarty and so on. The principle of template parsing processing is usually replacement. There are also some programmers who are accustomed to putting judgment, looping and other processing into template files and processing them with parsing classes. The typical application is the block concept, which is simply a loop processing. The PHP script specifies the number of loops, how to loop through, etc., and then the template parsing class implements these operations.
 Okay, after comparing the advantages and disadvantages of static pages and dynamic pages, now let’s talk about how to use PHP to generate static files.
  PHP generating static pages does not refer to PHP’s dynamic parsing and outputting HTML pages, but refers to using PHP to create HTML pages. At the same time, because of the non-writable nature of HTML, if the HTML we create is modified, it needs to be deleted and regenerated. (Of course, you can also choose to use regular rules to modify it, but I personally think that it is faster than deleting and regenerating, which is not worth the gain.)
 Getting back to the subject. PHP fans who have used PHP file operation functions know that there is a file operation function fopen in PHP, which opens a file. If the file does not exist, try to create it. This is the theoretical basis on which PHP can be used to create HTML files. As long as the folder used to store HTML files has write permission (ie permission definition 0777), the file can be created. (For UNIX systems, Win systems do not need to be considered.) Still taking the above example as an example, if we modify the last sentence and specify to generate a static file named test.html in the test directory:
$title = "Tomax International Test Template";
$file = "TwoMax Inter test template,
author:Matrix@Two_Max";
$fp = fopen ("temp.html","r");
$content = fread ($fp,filesize ("temp.html "));
$content .= str_replace ("{ file }",$file,$content);
$content .= str_replace ("{ title }",$title,$content);
// echo $content ;
$filename = "test/test.html";
$handle = fopen ($filename,"w"); //Open the file pointer and create the file
/*
Check whether the file is created and writable
*/
if (!is_writable ($filename)){
die ("File: ".$filename." is not writable, please check its properties and try again!");
}
if (!fwrite ($handle,$content )){ //Write information to the file
die ("Generate file".$filename."Failed!");
}
fclose ($handle); //Close the pointer
die ("Create file".$filename ."Success!");
?>
Solutions to common problems in practical applications are referenced:
1. Article list issues:
Create a field in the database and record the file name. Each time a file is generated, the file name will be automatically generated. Store it in the database. For recommended articles, just point to the page in the specified folder where the static files are stored. Use PHP operations to process the article list, save it as a string, and replace this string when generating the page. For example, add the mark { articletable } to the table where the article list is placed on the page, and in the PHP processing file:
$title = "TwoMax International test template";
$file = "TwoMax Inter test template,
author:Matrix@Two_Max";
$fp = fopen ("temp.html","r");
$content = fread ($fp,filesize ("temp.html"));
$content .= str_replace ("{ file }",$file,$content);
$content .= str_replace ("{ title }",$title,$content);
// Start generating list
$list = '';
$sql = "select id,title,filename from article";
$query = mysql_query ($sql);
while ($result = mysql_fetch_array ($query)){
$list .= ''.$result['title'].'
';
}
$content .= str_replace ("{ articletable }",$list,$content);
//End of generating list
//echo $content;
$filename = "test/test.html";
$handle = fopen ($filename,"w"); //Open the file pointer and create the file
/*
Check whether the file is created and writable
*/
if (!is_writable ($filename)){
die ("File: ".$filename." is not writable, please Check its properties and try again! ");
}
if (!fwrite ($handle,$content)){ //Write information to the file
die ("Generate file".$filename."Failed!
, 20 articles per page. The number of articles in a certain sub-channel list is 45 through database query. First, we obtain the following parameters through query: 1, total number of pages; 2, number of articles per page. Second step, for ($i. = 0; $i   $fp          = fopen ("temp.html","r");
  $content  = fread ($fp,filesize ("temp.html"));
  $onepage  = '20';
  $sql          = "select id from article where channel='$channelid'";
  $query      = mysql_query ($sql);
  $num        = mysql_num_rows ($query);
  $allpages   = ceil ($num / $onepage);
  for ($i = 0;$i     if ($i == 0){ 
        $indexpath = "index.html";
      } else { 
        $indexpath = "index_".$i."html";
      }
     $start = $i * $onepage;
     $list    = '';
     $sql_for_page = "select name,filename,title from article where channel='$channelid' limit $start,$onepage";
     $query_for_page = mysql_query ($sql_for_page);
     while ($result = $query_for_page){ 
        $list .= ''.$title.'
';
      }
     $content = str_replace ("{ articletable }",$list,$content);
     if (is_file ($indexpath)){ 
        @unlink ($indexpath); //若文件已存在,则删除
      }
     $handle    = fopen ($indexpath,"w"); //打开文件指针,创建文件
     /*
    检查文件是否被创建且可写
     */
     if (!is_writable ($indexpath)){ 
        echo "文件:".$indexpath."不可写,请检查其属性后重试!"; //修改为echo
      }
     if (!fwrite ($handle,$content)){  //将信息写入文件
        echo "生成文件".$indexpath."失败!"; //修改为echo
      } 
     fclose ($handle); //关闭指针
  }
  fclose ($fp);
  die ("生成分页文件完成,如生成不完全,请检查文件权限系统后重新生成!");
?>   
  大致思路如此,其中如其它数据生成,数据输入输出检查,分页内容指向等可酌情在页面中加入。
  在实际文章系统处理过程当中,还有许多问题有待考虑,与动态页面不同之处,需注意的地方还有很多。但大致思路即是如此,其它方面可举一反三而得。 

以上就介绍了http://www.56.com/m2v/?magic=1 PHP生成静态页面详解,包括了http://www.56.com/m2v/?magic=1方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do you modify data stored in a PHP session?How do you modify data stored in a PHP session?Apr 27, 2025 am 12:23 AM

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Give an example of storing an array in a PHP session.Give an example of storing an array in a PHP session.Apr 27, 2025 am 12:20 AM

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

How does garbage collection work for PHP sessions?How does garbage collection work for PHP sessions?Apr 27, 2025 am 12:19 AM

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

How can you trace session activity in PHP?How can you trace session activity in PHP?Apr 27, 2025 am 12:10 AM

Tracking user session activities in PHP is implemented through session management. 1) Use session_start() to start the session. 2) Store and access data through the $_SESSION array. 3) Call session_destroy() to end the session. Session tracking is used for user behavior analysis, security monitoring, and performance optimization.

How can you use a database to store PHP session data?How can you use a database to store PHP session data?Apr 27, 2025 am 12:02 AM

Using databases to store PHP session data can improve performance and scalability. 1) Configure MySQL to store session data: Set up the session processor in php.ini or PHP code. 2) Implement custom session processor: define open, close, read, write and other functions to interact with the database. 3) Optimization and best practices: Use indexing, caching, data compression and distributed storage to improve performance.

Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function