How to Reduce Server Load with PHP: Caching, Pagination, and Result Caching Techniques
Learn practical PHP strategies to lower server load—including using Memcached or Redis for data caching, implementing pagination to limit query size, and caching computational results—complete with clear code snippets and guidance on adapting these techniques to improve performance and stability.
1. Use Caching
Caching stores data in memory to avoid repeated database or external‑resource access. PHP can use extensions such as Memcached or Redis. The following example shows how to connect to a Memcached server, retrieve a value, and on a cache miss fetch the original data and store it for one hour.
// Connect to Memcached server
$memcached = new Memcached();
$memcached->addServer('localhost', 11211);
// Try to get data from cache
$data = $memcached->get('cached_data');
// If cache miss, fetch from database or other source
if (!$data) {
$data = /* code to fetch data */;
// Store data in cache for 1 hour (3600 seconds)
$memcached->set('cached_data', $data, 3600);
}
// Continue processing with $data
// ...2. Use Pagination
When a query returns many rows, pagination limits the number of records sent per request. Compute the offset from the current page, fetch only the required slice, and generate simple page numbers for navigation.
// Number of items per page
$pageSize = 10;
// Current page number (default to 1)
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
// Starting offset for the query
$start = ($page - 1) * $pageSize;
// Retrieve $pageSize rows starting at $start
$data = /* code to fetch $pageSize rows from $start */;
// Output the rows
foreach ($data as $item) {
// display $item
}
// Total number of records
$totalCount = /* code to get total count */;
$totalPage = ceil($totalCount / $pageSize);
// Render simple pagination links (plain text)
for ($i = 1; $i <= $totalPage; $i++) {
echo $i . ' ';
}3. Cache Computation Results
Expensive calculations whose results remain valid for a period can be cached in the same Memcached instance. The example checks for a cached result, performs the heavy computation only when necessary, and stores the outcome for one hour.
// Try to get cached result
$result = $memcached->get('cached_result');
// If not cached, compute and store
if (!$result) {
$result = /* heavy computation code */;
$memcached->set('cached_result', $result, 3600);
}
// Use $result for further processing
// ...Combining data caching, pagination, and result caching can substantially reduce server load and improve response times. These techniques can be complemented by CDN acceleration, database indexing, or query optimization for additional gains.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
