众所周知,大部分网站的新闻资讯或商品信息都是静态页面。这样做的好处主要是为了:1、加快访问速度,避免过多的操作数据库;2、SEO优化,便于搜索引擎收录。
本示例围绕 CMS 系统的静态页面方案出发,展示批量生成静态 html 功能。
注:本文程序只能在 Windows 的 DOS 或 Linux 下执行 PHP 命令来运行。
本示例主要有4个文件:config.inc.php(配置文件)、Db.class.php(数据库 PDO 类)、Model.class.php(PDO数据库操作类)、index.php(执行文件)
config.inc.php
复制代码 代码如下:
header('Content-Type:text/html;Charset=utf-8');
date_default_timezone_set('PRC');
define('ROOT_PATH', dirname(__FILE__)); // 根目录
define('DB_DSN', 'mysql:host=localhost;dbname=article'); // MySQL 的 PDO dsn
define('DB_USER', 'root'); // 数据库用户名
define('DB_PWD', '1715544'); // 数据库密码(请您根据实际情况自行设定)
function __autoload($className) {
require_once ROOT_PATH . '/includes/'. ucfirst($className) .'.class.php';
}
?>
Db.class.php
复制代码 代码如下:
// 连接数据库
class Db {
static public function getDB() {
try {
$pdo = new PDO(DB_DSN, DB_USER, DB_PWD);
$pdo->setAttribute(PDO::ATTR_PERSISTENT, true); // 设置数据库连接为持久连接
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // 设置抛出错误
$pdo->setAttribute(PDO::ATTR_ORACLE_NULLS, true); // 设置当字符串为空转换为 SQL 的 NULL
$pdo->query('SET NAMES utf8'); // 设置数据库编码
} catch (PDOException $e) {
exit('数据库连接错误,错误信息:'. $e->getMessage());
}
return $pdo;
}
}
?>
Model.class.php
复制代码 代码如下:
// 操作 SQL
class Model {
/**
* SQL 增删改操作,返回受影响的行数
* @param string $sql
* @return int
*/
public function aud($sql) {
try {
$pdo = Db::getDB();
$row = $pdo->exec($sql);
} catch (PDOException $e) {
exit($e->getMessage());
}
return $row;
}
/**
* 返回全部数据,返回 PDOStatement 对象
* @param string $sql
* @return PDOStatement
*/
public function getAll($sql) {
try {
$pdo = Db::getDB();
$result = $pdo->query($sql);
return $result;
} catch (PDOException $e) {
exit($e->getMessage());
}
}
}
?>
index.php
复制代码 代码如下:
require_once './config.inc.php';
$m = new Model();
$ids = $m->getAll("SELECT id FROM article ORDER BY id ASC");
foreach ($ids as $rowIdArr) {
$idStr .= $rowIdArr['id'].',';
}
$idStr = rtrim($idStr, ','); // 所有文章的 ID 号集合
$idArr = explode(',', $idStr); // 分割成数组
// 下面的程序循环生成静态页面
foreach ($idArr as $articleId) {
$re = $m->getAll("SELECT id,title,date,author,source,content FROM article WHERE id =". $articleId); // $re 为每篇文章的内容,注意:其类型为:PDOStatement
$article = array(); // $article 为一个数组,保存每篇文章的title、date、author、content、source
foreach ($re as $r) {
$article = array(
'title'=>$r['title'],
'date'=>$r['date'],
'author'=>$r['author'],
'source'=>$r['source'],
'content'=>$r['content']
);
}
$articlePath = ROOT_PATH. '/article'; // $articlePath 为静态页面放置的目录
if (!is_dir($articlePath)) mkdir($articlePath, 0777); // 检查目录是否存在,不存在则创建
$fileName = ROOT_PATH . '/article/' . $articleId . '.html'; // $fileName 生成的静态文件名,格式:文章ID.html(主键ID不可能冲突)
$articleTemPath = ROOT_PATH . '/templates/article.html'; // $articleTemPath 文章模板路径
$articleContent = file_get_contents($articleTemPath); // 获取模板里面的内容
// 对模板里面设置的变量进行替换。即比如:把模板里面的 替换成数据库里读取的 title,替换完毕赋值给变量 $articleContent
$articleContent = getArticle(array_keys($article), $articleContent, $article);
$resource = fopen($fileName, 'w');
file_put_contents($fileName, $articleContent); // 写入 HTML 文件
}
/**
* getArticle($arr, $content, $article) 对模板进行替换操作
* @param array $arr 替换变量数组
* @param string $content 模板内容
* @param array $article 每篇文章内容数组,格式:array('title'=>xx, 'date'=>xx, 'author'=>xx, 'source'=>xx, 'content'=>xx);
*/
function getArticle($arr, $content, $article) {
// 循环替换
foreach ($arr as $item) {
$content = str_replace('', $article[$item], $content);
}
return $content;
}
?>
运行截图(Windows 的 DOS 为例)
运行完毕截图:
运行2分钟左右就可以生成 9000多 html。
来自Lee.的专栏 转载注明出处!!!

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.


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

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

Zend Studio 13.0.1
Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

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.
