Home Backend Development PHP Tutorial Share a simple method to achieve static page in PHP

Share a simple method to achieve static page in PHP

Jun 01, 2018 am 11:55 AM
php method Simple

本篇文章主要介绍PHP实现页面静态化的简单方法分享,感兴趣的朋友参考下,希望对大家有所帮助。

为什么要页面静态化?

1.动态文件执行过程:语法分析-编译-运行

2.静态文件,不需要编译,减少了服务器脚本运行的时间,降低了服务器的响应时间,直接运行,响应速度快;如果页面中一些内容不经常改动,动态页面静态化是非常有效的加速方法。(纯静态,伪静态还是需要PHP解释器的)

3、生成静态URL利于SEO,利于蜘蛛抓取和收录,有利于提升排名

优化页面响应时间方法

1.动态页面静态化

2.优化数据库

3.负载均衡

4.使用缓存等等

//动态页面静态化一般用于不经常改动的地方,频繁改动的地方一般不适用静态化,可用伪静态(例如微博等)

静态化详细介绍

1、纯静态分为局部静态化(局部动态化,使用AJAX动态获取数据)和纯静态化。

伪静态:改变URL(需要服务器支持,如:apache等等)

2、从URL结构以及页面名称看,伪静态和静态页面是一样的。伪静态的页面后缀可以是html htm 或者是目录格式

伪静态只是改变了URL的表现形式,实际上还是动态页面

静态页面可以节省服务器资源,而伪静态严格说是增加服务器资源消耗的

总结,在SEO方面,伪静态和静态页面的功能是相同的,但是伪静态本质上还是动态页面,所以消耗资源是和动态页面一样的,而且因为Rewrite服务器还需要消耗额外的资源。

Buffer缓冲区认知

1、开启buffer

•在php.ini中的output_buffering开启
•在php文件中使用ob_start()函数开启

; Default Value: Off
; Development Value: 4096
; Production Value: 4096
; http://php.net/output-buffering
output_buffering = 4096
Copy after login

2、获取缓冲区的内容

output_buffering=on 需要先开起,才能调用ob_get_contents()函数。但是,如果不开启output_buffering时,当在头文件中调用函数ob_start()函数时,ob_get_contents()也能使用。

ob_get_content();//返回输出缓冲区的内容;

PHP如何实现页面纯静态化

基本方式

1、file_put_contents

2、使用PHP内置缓存机制实现页面静态化output_buffering

ob_start()//如果php.ini已经开启,那么这里会开启一个新的输出缓冲区;
ob_get_contents()//获取输出缓冲区内容;
ob_clean()//清空输出缓冲区内容,但是不会删除输出缓冲区
ob_get_clean//获取输出缓冲区内容并且删除输出缓冲区,等价于ob_get_contents和ob_end_clean)
Copy after login

下方这段代码,运行是不会有输出的

原因就是输出缓冲区被清空了,看上图理解

ob_start();
echo 777;
echo 000;
ob_clean();
echo ob_get_contents();
Copy after login

纯静态实现,代码和实现逻辑参考:

<?php
/**
 * 触发系统生成纯静态化页面业务逻辑
 * 有3种方案: 
 * 第一:定时扫描程序(利用crontab来处理) 
 * 第二:手动触发方式,人为触发
 * 第三:页面添加缓存时间,在页面中控制时间来操作
*/
//===========================================
//生成纯静态文件步骤
//1、连接数据库,然后从数据库里面获取数据
//2、把获取到的数据填充到模版文件里面
//3、需要把动态的页面转为静态页面,生成静态化文件
//============================================
//PHP实现页面静态化有以下步骤:
//1:A.php请求数据库数据:通过mysql或者mysqli或者PDO扩展
//2:在A.html中输出A.php请求的数据库数据:一般是将将在数据库中取出的数组形式的数据赋予新的数组,并且输出
//3:在A.php中包含A.html文件:直接通过require_once()函数或者inclde_once()
//4:开启数据缓存ob_start()=>获取获取缓存内容并且将数据生成在静态文件中file_put_contents(&#39;index.shtml&#39;,ob_get_clean());
//header("content-type:text/htm;charset=utf-8");
if(is_file(&#39;./index.html&#39;) && (time() - filemtime(&#39;./index.html&#39;) < 1200))
{
  //缓存未失效则直接加载静态文件
  require_once(&#39;./index.html&#39;);
}
else 
{
  //缓存失效了则重新生成
  // 引入数据库链接操作
  require_once(&#39;./db.php&#39;);
  $sql = "select * from news where `category_id` = 1 and `status` = 1 limit 4";
  try
  {
      $db = Db::getInstance()->connect();
      $result = mysql_query($sql, $db);
      $newsList = array();
      while($row = mysql_fetch_assoc($result)) 
      {
          $newsList[] = $row;
      }
  }
  catch(Exception $e)
  {
      // TODO
  }
  ob_start();
  require_once(&#39;template/index.php&#39;);//引入模版文件
  file_put_contents(&#39;./index.html&#39;, ob_get_contents());//生成静态文件
  //ob_clean();
}
Copy after login

静态页面中局部动态化实现

利用Jquery中的ajax请求文件,获取到返回的JSON数据,然后应用到模版就可以了

伪静态

Nginx服务器默认不支持PATH INFO模式,需要额外配置

Apache伪静态设置

1、开启apache mod_rewrite.so 配置 在 httpd.conf中。

测试的话可以用phpinfo查看,看是否loaded modules 有这个模块

2、inculde conf/extra/httpd-vhosts.conf virtual hosts支持,虚拟域名配置

3、编辑vartual host 文件

4、本机host文件加入配置的域名(如果需要本机测试针对windows)

5、伪静态配置

- 5.1 rewrite engine on
- 5.2编写规则

^/post/([0-9]*).html$ /post.php?id=$1
Copy after login

放在 virtualhost 段中

post.php 中编写

<?php 
echo &#39;this is &#39;.$_GET[&#39;id&#39;];
Copy after login

然后可以访问a.com/123.html 返回的就是this is 123.

扩展:如果目录下有123.html这个真正的文件,那么还是加载了动态的post 123.
那么如何设置呢,想要当前文件有了真正的静态文件,那么需要以下配置了

RewriteEngine on
RewriteRule ^/post/([0-9]*).html$ /post.php?id=$1
#存在目录
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME}!-d
#存在文件
RewriteCond%{DOCUMENT_ROOT}%{REQUEST_FILENAME}}!-f
Copy after login

以上两句话意思是如果根目录下有请求的目录或者文件,那就用他

当然这个要放在刚刚的那个rewrite的上面。

Nginx伪静态

伪静态是影响服务器性能的,不是越多越好,需要按需求而定

总结:以上就是本篇文的全部内容,希望能对大家的学习有所帮助。

相关推荐:

phpUse the functions pathinfo(), parse_url() and basename() to parse the URL

##php Implemented web version of the rock-paper-scissors game

phpMethod to monitor whether data is successfully inserted into the Mysql database

The above is the detailed content of Share a simple method to achieve static page in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles