Это сработало в моих тестах:
define('MAX_PER_PAGE',10);
// sanity checks for per-page and page index
$numPosts = ctype_digit((string)$_GET['perpage']) ? $_GET['perpage'] : 5;
$ostart = $start = max(1, ctype_digit((string)$_GET['page']) ? $_GET['page'] : 1) - 1;
$mode = 0;
if ($mode == 0) {
$file = "blogfile.txt";
}
// read the file into an array, strip newlines and ignore empty lines
file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES | FILE_TEXT);
// sort array (see custom function at bottom)
usort($line, 'blogsort');
$lines = count($line);
// get total number of pages
$numPages = ceil($lines / $numPosts);
// additional sanity checks (also sets $ostart if it was invalid; used later)
$numPosts = min(MAX_PER_PAGE, max(1, $numPosts));
if ($start * $numPosts > $lines ) {
$ostart = $start = max(0, $lines - $numPosts);
}
else {
$start *= $numPosts;
}
// Only grab the part of the array we need
$sliced = array_slice($line, $start, $numPosts);
// loop through posts, but break early if we run out
for ($n = 0; $n < $numPosts && isset($sliced[$n]); $n++ ) {
$blog = explode("|", $sliced[$n]);
if (isset($blog[0])) {
echo "<div class=\"blog-post\">\n",
"<p class=\"blog-title\">{$blog[1]}</p>\n",
"<p class=\"blog-message\">{$blog[2]}</p>\n",
"<p class=\"blog-date\">Posted: {$blog[0]}</p>\n",
"<div style=\"clear: both;\"></div>\n",
"</div>\n\n";
}
}
// back link
if ($ostart > 0) {
echo "<a href=\"{$_SERVER['SCRIPT_NAME']}?perpage={$numPosts}&page={$ostart}\">← Older</a>";
}
else {
echo "None Older";
}
echo " || ";
// forward link
if ($ostart + 1 < $numPages) {
$next = $ostart + 2;
echo "<a href=\"{$_SERVER['SCRIPT_NAME']}?perpage={$numPosts}&page={$next}\">Newer →</a>";
}
else {
echo "None Newer";
}
function blogsort($a, $b) {
$dateA = strtotime(substr($a, 0, strpos($a, '|')));
$dateB = strtotime(substr($b, 0, strpos($b, '|')));
if ($dateA == $dateB) {
return 0;
}
elseif ($dateA > $dateB) {
return -1;
}
else {
return 1;
}
}