Introduction
\nA slow PHP application is not just wasted seconds of waiting, but also disappointed users, lower search engine rankings, and increased server load. Fortunately, even a beginner developer can significantly improve the performance of their code without delving into complex system settings. In this article, we will cover basic yet effective methods for optimizing PHP applications that will help your website or web service run faster and more stable.
\nWe will look at four key areas: data caching, database optimization, proper memory management, and using modern PHP features. Each section will be accompanied by practical code examples.
\n\nCaching: Your Main Speed Tool
\nCaching is saving the results of expensive operations for reuse. Instead of generating a page or executing a complex SQL query every time, you serve a pre-saved copy.
\n\nIn-Memory Caching with Memcached or Redis
\nThe fastest way to cache is using in-memory stores like Memcached or Redis. They store data in RAM, allowing retrieval in microseconds.
Example of simple caching of a database query result using Memcached:
<?php\n$memcached = new Memcached();\n$memcached->addServer('localhost', 11211);\n\n$cacheKey = 'user_profile_123';\n$userData = $memcached->get($cacheKey);\n\nif ($userData === false) {\n // Data not in cache — execute the heavy query\n $userData = getUserFromDatabase(123);\n // Save to cache for 10 minutes (600 seconds)\n $memcached->set($cacheKey, $userData, 600);\n}\n\necho $userData['name'];\n?>\n\nCaching Entire HTML Pages
\nFor static or rarely changing pages, you can cache the complete HTML output. This reduces load on the PHP interpreter and web server.
\n<?php\n$cacheFile = 'cache/index.html';\n$cacheTime = 3600; // 1 hour\n\nif (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < $cacheTime) {\n // Serve the cached page\n readfile($cacheFile);\n exit;\n}\n\n// Start output buffering\nob_start();\n\n// ... your regular PHP code that generates the page ...\n\n$html = ob_get_clean();\nfile_put_contents($cacheFile, $html);\necho $html;\n?>\n\nDatabase Optimization
\nThe database is the most common bottleneck in most PHP applications. A few simple changes can yield a huge speed boost.
\n\nUse Indexes
\nWithout indexes, MySQL performs a full table scan, which is extremely slow on large datasets. Add indexes to fields used in WHERE, JOIN, and ORDER BY clauses.
-- Example: orders table\nCREATE INDEX idx_user_id ON orders(user_id);\nCREATE INDEX idx_created_at ON orders(created_at);\n\nAvoid N+1 Queries
\nThis is a classic mistake: making a database query for each item inside a loop. Instead, use a single query with JOIN or a subquery.
Bad example (N+1):
\n<?php\n$users = $db->query("SELECT * FROM users");\nforeach ($users as $user) {\n // A separate query is made for each user\n $orders = $db->query("SELECT * FROM orders WHERE user_id = " . $user['id']);\n}\n?>\n\nGood example (single query):
\n<?php\n$usersWithOrders = $db->query("\n SELECT u.*, o.* \n FROM users u \n LEFT JOIN orders o ON u.id = o.user_id\n");\n?>\n\nLimit Data Retrieval
\nNever request all rows if you only need 10. Use