Chapter 10: Dynamic Website Hosting (PHP, Python, Node.js with MySQL)
10.3 PHP with MySQL
Friends, this lab uses PHP-FPM with a configured FastCGI handler. Apache can also use a PHP module in supported setups. Check the handler, script, pool and database independently.
मित्रांनो, या lab मध्ये PHP-FPM आणि ठरलेला FastCGI handler वापरू. Apache मध्ये समर्थित setup असेल तर PHP module देखील वापरता येतो. Handler, script, pool आणि database वेगळे तपासा.
दोस्तों, इस lab में PHP-FPM और तय FastCGI handler इस्तेमाल करेंगे। समर्थित setup में Apache PHP module भी इस्तेमाल कर सकता है। Handler, script, pool और database अलग-अलग जाँचो।
Install PHP
| Platform | Packages and interfaces to verify |
|---|---|
| Amazon Linux 2023 or CentOS Stream 9 | The approved versioned PHP CLI, FPM and required PDO MySQL and multibyte extensions. Inspect the actual FPM unit and pool socket. |
| Ubuntu with Nginx | The installed PHP series, FPM unit and required extensions. Read the versioned or custom socket configuration. |
| Ubuntu with Apache | The assigned handler, such as an approved PHP module or FPM integration, plus the required runtime extensions. |
On AL2023 or CentOS Stream, inspect the assigned PHP-FPM unit and chosen web server. Use the expanded procedure below to validate the pool and apply only the required site change.
php -v
php --ini
php -m
Some package configurations ship a PHP handler for a specific site or server layout. Inspect the actual enabled modules, includes and pool listener. A new named site needs its own verified request mapping.
Nginx server block for PHP
AL2023 and CentOS Stream 9. Confirm the actual Nginx include and assigned PHP-FPM socket before preparing an owned site file.
sudo nginx -t
sudo nginx -T
Ubuntu. Inspect the loaded site include and the installed versioned PHP-FPM unit. Keep existing site links intact.
ls -ld /etc/nginx/sites-available /etc/nginx/sites-enabled
sudo ss -lxnp
Look for the pool’s configured listen path and compare it to the active socket. A packaged unversioned symlink may exist, and a custom pool can choose a different path.
Apache virtual host for PHP
Apache must have the chosen PHP handler configured for this site. Verify its loaded modules, scoped directory and index settings, and actual FPM integration if used.
The PHP application
Use the checked source and named local or hosted lab below. Configure the runtime credential through the assigned environment.
php -l public/index.php
Quick PHP test page
Use php -l for the approved source and a named request for the expected rendered page. Keep full PHP and environment diagnostics private.
PHP file downloads instead of running?
If the browser receives PHP source, keep the affected route out of public reach until the correct handler is verified. If the handler instead returns a gateway error, check the actual pool listener and its logs.
Ravindra Bagale's Tip
Do not publish a full PHP configuration report for a smoke test. Check the runtime in the authorized shell and use a named request for a known rendered marker.
Ravindra Bagale's Tip – मराठी
Smoke test साठी पूर्ण PHP configuration public करू नका. मंजूर shell मध्ये runtime तपासा आणि site च्या hostname ने तयार झालेल्या page मधली ओळखता येणारी ओळ पहा.
Ravindra Bagale's Tip – हिंदी
Smoke test के लिए पूरा PHP configuration public मत करो। मंजूर shell में runtime जाँचो और site के hostname से बनी हुई page की पहचान वाली पंक्ति देखो।
Lab
Chala, khalchya temporary loopback lab madhe fakt kalpanik student add kara. POST cha 303 paha, punha GET ne navin row disate ka te tapaasa. Hosted example madhe form bandh aahe ani list read-only aahe.
Render and update the practice student list with PHP and MySQL
A classroom registration exercise needs a list that reflects the rows already stored in the practice database. It also needs a small way to add a synthetic student when working on a local isolated example. A prepared HTML file would become stale after every insertion. PHP can read the database at request time, render the rows as a web page and apply the intended form submission before showing the updated list. This lesson separates the web server, the PHP worker, the database session and the public HTML they produce.
Use the appdb.students contract from the database lesson. The three initial records are fictional. The app reads id, name and city and, in the enabled local form exercise, inserts the latter two values. The regular hosted example leaves the write form disabled. A real application that allows a person to change records needs its own login, authorization, user data and session policy. A temporary local form token helps verify this lesson's request handling and does not authorize members of an outside audience.
The executable sample uses PDO, PHP's database access interface, with the PDO MySQL driver. A compatible MariaDB server can serve the same simple schema when its driver and account settings have been verified. You can run the local PHP development server to prove the request, SQL and content behavior. A managed deployment can use an approved Nginx or Apache configuration and PHP-FPM. Keep the two proofs distinct. Running PHP from your shell does not show which PHP environment the web server actually uses.
Decide how the web server runs the PHP code
A request to the public site reaches the configured HTTP listener, whose vhost supplies a document root and routing rules. Static file requests can be served directly. In an FPM setup the front server uses a PHP-specific handler to forward an executable script request to PHP-FPM through FastCGI. FastCGI is a protocol for passing request information and results to a separate application process. Both ends need to agree on the socket or address and the requested script. The web server then returns the result, which should be ordinary generated HTML instead of the source file.
Apache can use an installed PHP handler module or forward to a PHP-FPM pool using its approved FastCGI arrangement. The package and configuration determine which path it uses. Do not infer that every Apache PHP package uses the same mechanism or that the handler is activated automatically in a new virtual host. Inspect the actual enabled modules and site mapping. Installing PHP's CLI binary can prove the language is present without configuring any web-serving mechanism at all. On Nginx inspect the effective FastCGI rule and its exact socket or local port.
| Layer | Work for the student page | Independent evidence |
|---|---|---|
| Front server | Choose the site and forward its PHP request. | Expected hostname, matched route and site response or entry in its logs. |
| PHP runtime | Run the selected script with the approved extensions and settings. | Script validates with PHP and a web request shows its generated marker and rows. |
| PDO MySQL session | Connect to the intended database as the runtime user and query the current table. | Known seed row and the matching privilege from the same connection path. |
| Browser | Interpret generated HTML and submit the practice form when enabled. | Expected page, response code and persisted row after the synthetic submission. |
Pay attention to failure boundaries. A successful static asset proves the named web server can send that file. It does not prove a PHP worker accepts requests. A generated readiness response can prove PHP executes without demonstrating a SQL lookup. A working CLI query under the operator's login does not identify the web process's database role. Plan one test per boundary so the first failure points to an appropriate check.
Inspect the installed CLI, PHP-FPM unit and database extension
On a dedicated guest, read the OS release and the approved package names. Use the currently supported PHP version and its matching FPM and MySQL driver from the assigned repository. Package names can have a version suffix, especially with parallel PHP packages. Ubuntu installations commonly provide versioned FPM units and sockets. RPM layouts can use a php-fpm unit and a pool file under a path such as /etc/php-fpm.d. Confirm the actual unit and pool, rather than assuming the name from another lab. No command in this discovery needs to stop the front server.
cat /etc/os-release
php -v
php --ini
php -r 'echo implode(", ", PDO::getAvailableDrivers()), PHP_EOL;'
php -m
The example needs PDO MySQL, multibyte string support and the standard session extension for the optional local form. Check that the CLI lists mysql among PDO drivers and has mbstring. A separate FPM process may load additional or different INI files. Inspect its actual configuration after verifying its binary and service. An error such as “could not find driver” points to the executing runtime's extension settings. Installing a client command called mysql does not load PHP's database extension.
Use the package manager's information query to choose the assigned PHP runtime and extensions. Some Amazon Linux examples bundle a particular PHP version and offer related packages by different names. Ubuntu's php-fpm, php-mysql and php-mbstring package selectors can resolve to the default supported series for the release. CentOS Stream's approved stream and extension package set determine what is available there. Read the install transaction, do not change unrelated versions, and use the service's approved validation and activation flow after preparing the new scope.
# Examples of read-only management checks. Choose the actual assigned unit.
systemctl cat php-fpm
systemctl is-active php-fpm
sudo ss -lxnp
sudo journalctl -u php-fpm --no-pager -n 18
Compare the pool's listen value with the actual local socket. The owner, group and mode must permit the front server's worker to connect. Restrict the permissions to the intended process identities. A broad socket permission or sharing a pool across unrelated sites can widen who may send PHP work to that runtime. On a labelled host network or file decisions can also depend on its actual policy. Read the focused error and approved configuration rather than applying a generic ownership or global permission change.
Write one PHP entry point that checks inputs and uses the narrow SQL role
Save this example as public/index.php in a newly prepared application stage. The working directory can have configuration and tests beside public, but the front server should serve only the approved public directory. The database credentials come from the runtime's configured environment or the corresponding managed secret integration, not the source below. Use the dedicated database from the prior exercise and supply DB_HOST, DB_PORT, DB_NAME, DB_USER and DB_PASSWORD as appropriate. The host and schema defaults are for the one-host practice environment. The user and password have no baked-in values.
<?php
declare(strict_types=1);
header('Content-Type: text/html; charset=utf-8');
header('Cache-Control: no-store');
function showError(int $status, string $message): never {
http_response_code($status);
echo htmlspecialchars($message, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
exit;
}
function setting(string $name, string $fallback = ''): string {
$value = getenv($name);
return $value === false ? $fallback : $value;
}
function displayValue(string $value): string {
return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
function formText(string $name, int $limit): ?string {
$raw = $_POST[$name] ?? null;
if (!is_string($raw)) {
return null;
}
$value = trim($raw);
return $value !== '' && mb_check_encoding($value, 'UTF-8')
&& mb_strlen($value, 'UTF-8') <= $limit ? $value : null;
}
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$localForm = PHP_SAPI === 'cli-server' && setting('ENABLE_LOCAL_FORM') === '1';
if ($method !== 'GET' && ($method !== 'POST' || !$localForm)) {
header($localForm ? 'Allow: GET, POST' : 'Allow: GET');
showError(405, 'Method unavailable for this exercise.');
}
$token = '';
if ($localForm) {
if (!session_start([
'use_strict_mode' => 1,
'cookie_httponly' => 1,
'cookie_samesite' => 'Strict',
])) {
error_log('Student list: could not start the local form session');
showError(503, 'Practice form temporarily unavailable.');
}
if (!isset($_SESSION['form_token'])) {
$_SESSION['form_token'] = bin2hex(random_bytes(24));
}
$token = $_SESSION['form_token'];
}
if ($method === 'POST') {
$claimed = $_POST['form_token'] ?? null;
if (!is_string($claimed) || !hash_equals($token, $claimed)) {
showError(403, 'Form token rejected.');
}
$name = formText('name', 100);
$city = formText('city', 50);
if ($name === null || $city === null) {
showError(422, 'Enter a name up to 100 characters and a city up to 50.');
}
}
$host = setting('DB_HOST', '127.0.0.1');
$port = setting('DB_PORT', '3306');
$database = setting('DB_NAME', 'appdb');
$user = setting('DB_USER');
$password = setting('DB_PASSWORD');
if ($user === '' || $password === '') {
error_log('Student list: database credentials not configured');
showError(503, 'Student list temporarily unavailable.');
}
try {
$dsn = "mysql:host={$host};port={$port};dbname={$database};charset=utf8mb4";
$pdo = new PDO($dsn, $user, $password, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false,
]);
if ($method === 'POST') {
$insert = $pdo->prepare('INSERT INTO students (name, city) VALUES (?, ?)');
$insert->execute([$name, $city]);
header('Location: /', true, 303);
exit;
}
$rows = $pdo->query('SELECT id, name, city FROM students ORDER BY id')
->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $failure) {
error_log('Student list: database operation failed');
showError(503, 'Student list temporarily unavailable.');
}
?>
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>PHP student list</title></head>
<body>
<h1>Practice students</h1>
<table>
<caption>Synthetic records from the practice database</caption>
<thead><tr><th scope="col">ID</th><th scope="col">Name</th><th scope="col">City</th></tr></thead>
<tbody>
<?php foreach ($rows as $row): ?>
<tr><td><?= (int) $row['id'] ?></td>
<td><?= displayValue($row['name']) ?></td>
<td><?= displayValue($row['city']) ?></td></tr>
<?php endforeach; ?>
</tbody>
</table>
<?php if ($localForm): ?>
<h2>Add a synthetic student</h2>
<form method="post" action="/">
<input type="hidden" name="form_token" value="<?= displayValue($token) ?>">
<label>Name <input name="name" maxlength="100" required></label>
<label>City <input name="city" maxlength="50" required></label>
<button type="submit">Add student</button>
</form>
<?php endif; ?>
</body>
</html>
Trace the GET path first. The file sets response headers and chooses the supported method. It obtains settings from the PHP process environment, opens a database session, then reads the expected columns. PDO's fetch mode supplies an array for each row keyed by column names. The output loop prints each row as HTML. The string rendering helper encodes special characters for this text context, so a person's synthetic name containing an ampersand can be displayed as text. The SQL query's data binding addresses SQL; output encoding addresses HTML.
Trace the optional local POST path separately. The method is available only when using PHP's development server and explicitly enabling the exercise. The local GET generates a per-session unpredictable form token. The POST needs that same session and token, then passes string, UTF-8 and length checks before calling the prepared INSERT. HTML maxlength is a convenience for a cooperative browser. The server must still enforce the rules. On a normal successful autocommit connection the standalone INSERT applies, and status 303 directs the client to GET again rather than rerendering after the submission.
A redirect prevents a normal reload of the resulting GET page from repeating that POST. It does not guarantee each submitted operation happens once if a client resends the original request. Production rules may need unique operation identities or other safeguards specific to the course exercise's domain. When credentials or an expected query are unavailable, the app returns a concise temporary error. Its controlled server log message identifies the part of the code that failed without displaying a connection exception or environment secrets. Operators can inspect deployment settings through authorized channels.
Lab one. Prove the list and optional form using an isolated loopback service
Prerequisites are a local PHP CLI that supplies the required extensions and a dedicated training database with the shared table and runtime grants. Use synthetic data only. The server runs just on your own loopback. It is not a production PHP server. Put the checked index.php in a fresh stage's public directory. Start the shell below from that stage and inspect the first command's syntax result. Replace the port and secret with the values already authorized in your local or disposable exercise.
(
set -eu
public="$PWD/public"
php -l "$public/index.php"
export DB_HOST=127.0.0.1 DB_PORT=3306 DB_NAME=appdb DB_USER=appuser
printf '%s' 'Practice DB password: ' >&2
IFS= read -r -s DB_PASSWORD
printf '\n' >&2
export DB_PASSWORD
export ENABLE_LOCAL_FORM=1
session_dir=$(mktemp -d "${TMPDIR:-/tmp}/php-student-session.XXXXXX")
trap 'find "$session_dir" -maxdepth 1 -type f -name "sess_*" -delete; rmdir "$session_dir"' EXIT
php -d display_errors=0 -d "session.save_path=$session_dir" \
-S 127.0.0.1:18803 -t "$public"
)
The password prompt reads without showing the typed value and confines the variable to the child practice shell. The server uses a fresh private directory for its session files. The port is a high local test port. If it is in use choose a different one and use it consistently in the browser. Do not change the bind to a wider network address. If the database runs in a different host or network namespace, change the approved connection values and use its documented trusted settings rather than treating this one-host sample as the complete deployment.
Open
http://127.0.0.1:18803/and verify the practice heading and three expected seed rows if the database was newly set up. In developer tools record the document status and HTML type. Work from the same browser session for the next step so the form token and associated session match.Submit one synthetic unique name, for example “PHP rehearsal & proof”, and a sample city such as Pune. Inspect the request results. The POST should return 303, then the browser follows its location with GET. The resulting page should display the ampersand as part of the name. Query the same database through the expected role or inspect the page after a fresh request to confirm the row persisted.
Reload the final GET page and verify that doing so does not add a second row. In a new clean test request submit a missing form token or an ordinary empty value under the lab's known conditions. Confirm that the resulting 403 or validation response does not create a row. Keep the scope inside this synthetic local instance and use only its own request data and test session.
For the read-only check restart your own loopback sample with the form flag omitted. Verify that the list still works and that no add form appears. A direct POST should produce the method policy result. This confirms the server enforces the policy rather than depending only on whether a button is visible.
Do not use real personal information in the debug page or test requests. If PHP cannot connect, compare the same approved connection with the database command-line test from the setup lesson and verify the settings available to this process. If a validated POST succeeds but a later read seems unchanged, inspect its documented response status and query the same table and unique marker. Confirm you are not comparing separate databases or using a source code copy with a different configuration. Remove the test row through the assigned admin scope if the database is being kept for the next exercise. The runtime grant deliberately cannot delete rows.
Stop only the local PHP child from its running terminal. Verify the temporary port no longer serves the test and that the scratch session files are removed. The database and its three seed rows belong to the continuing exercise if the trainer assigned it; do not stop or delete an independent database service simply because the HTTP process is done. For a wholly disposable fixture, retire its own database and files according to the local scope.
Configure a reviewed PHP-FPM entry for the hosted read-only route
For a managed setup use a dedicated assigned pool and the actual socket or private listening address it exposes. Place the public file in the approved site directory. Keep application configuration and credentials outside the served directory. The sample below is an Nginx site for one PHP entry point, using a fixed file rather than telling the worker to execute any path from a request. Use your verified package include and adjust the approved root and pool path. Test this with read-only behavior, since the sample checks its running server interface before displaying the local write form.
server {
listen 80;
server_name student-list.example.test;
root /var/www/student-list-lab/public;
location = / {
index index.php;
}
location = /index.php {
internal;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root/index.php;
fastcgi_pass unix:/run/php-fpm/student-list-lab.sock;
}
location / {
return 404;
}
}
Here an index request is resolved to the one allowed script by an internal redirect. The internal location keeps direct requests to that script path from being a separate public route. Confirm the selected FastCGI include provides the ordinary request parameters and does not conflict with the explicit script filename. The socket path is an example for the owned pool. On Ubuntu the actual socket can be versioned under /run/php/. An FPM socket is an interface for PHP request instructions, so a plain HTTP request to that local path is not a meaningful application smoke test.
With an approved Apache PHP-FPM configuration, the same public root and main index can route according to the vhost's loaded FastCGI handler. The mod_proxy and mod_proxy_fcgi features need to be enabled in a supported FPM configuration. For a package using another handler, follow its approved integration and avoid sending the raw PHP file as static content. Inspect the effective module and routing rules for the named site. Enabling or changing global modules for unrelated sites is outside this small publishing exercise.
# An excerpt for a reviewed Apache vhost with mod_proxy_fcgi.
# Use the assigned DocumentRoot, directory policy and actual FPM socket.
DirectoryIndex index.php
<Files "index.php">
SetHandler "proxy:unix:/run/php-fpm/student-list-lab.sock|fcgi://localhost/"
</Files>
PHP-FPM commonly clears inherited worker environment variables unless its pool explicitly makes required entries available. Confirm how the service supplies DB_USER and DB_PASSWORD to the specific owned pool. The pool can allow designated variables from a protected service configuration without copying every process environment value into the worker. Check the package's actual mechanism and the site owner's policy. Do not print the values in a diagnostic handler. A CLI test launched from your shell can see variables that a managed FPM worker legitimately cannot.
Validate the intended pool and web setup under the package's commands. Review any file or socket warnings before applying the owned configuration. Use the existing distro-specific start or reload plan for the intended daemons and keep the packaged default intact. A currently active daemon can still fail to load a pool, or a site block can refer to a previous socket. Compare the actual pool listener with the exact configured route, then use a named HTTP test that exercises the worker and PDO query.
Lab two. Verify the request through the real FastCGI integration
Use a dedicated approved host with the installed front server and FPM, the marked schema and authorized runtime credentials. After preparing the read-only PHP file and verified site block, record the site name and binding. A supported status or log check can show that the PHP pool is ready to accept requests. Verify the FPM socket and the worker's access to the script and its own runtime configuration. Do not use phpinfo() as a public diagnostic page. Debugging requires limited expected output, not the entire process configuration.
# Approved isolated HTTP listener example for the named test site.
SITE='student-list.example.test'
curl --noproxy '*' --resolve "$SITE:80:127.0.0.1" \
--silent --show-error --max-time 5 --include "http://$SITE/"
Expect status 200, an HTML media type, the practice heading and seed rows from the configured database. The hosted route does not show a write form, and the application rejects a POST without applying it. If you also serve a synthetic static asset, check that it works independently and does not come from the app's rendered fallback. The Nginx sample above serves only the index entry. An asset plan would need deliberate safe routing according to the expected release. Verify page behavior through the actual permitted route when that route is part of the exercise.
If the response contains PHP source, stop making that script publicly reachable through the incorrect mapping and review the approved handler before restoring the route. Classify what bytes came back without copying sensitive source into public logs or student reports. A missing handler can leave software serving a file as plain data. A handler with an unavailable pool can instead produce a 502. An application message about its data dependency usually means PHP accepted the request and reached its own connection or query path. Check which component produced the exact HTTP response before adjusting the server socket or database.
After a managed exercise, preserve the original configurations and remove only the newly owned test definition, public files and pool when nobody needs them. Remember that its pool and web site config can be independent artifacts. Restore them through the approved validation and reload process. Keep the original guest services and shared database running when other lessons use them. Confirm known controls after cleanup. If the practice credential or data will be retired, use its designated database owner and scope separately.
Review which PDO parameters and grants the operation uses
The DSN identifies a driver and connection details. In this sample it selects MySQL, an explicit TCP address and port, the practice database and the expected character encoding. The data source name is a configuration choice from the owned environment. The code passes the login values separately. The connection must reach a supported database that recognizes this account and allows the particular query. A socket-based deployment would need its specific socket DSN and an account matching that transport, so do not assume changing the text to localhost preserves the same authentication or connectivity.
Start with a successful direct database read through the intended app session. Compare its selected database, matched account and one known row with the result in PHP. SELECT id, name, city names the columns the page actually renders. Keeping the query explicit makes it easier to see where a schema change would affect the code. The ORDER BY id gives the training list a predictable order. If no rows exist, the table can still render with no data rows. Decide whether your exercise calls for seed values or whether that is a meaningful empty collection.
The local form uses a prepared statement with a stable SQL template and separately supplied values. This allows the driver and database to treat the name and city as data for the specified operation. Change the predicate or operation only through reviewed application code. Choose the runtime account's narrow permission scope according to the path that actually writes. The chapter's shared lab user needs SELECT and INSERT for the synthetic form. A deployed service that only reads should use a narrower role if it remains read-only. An application query does not need a grant to administer the database or list other users.
Character encoding matters when the submitted name contains a character beyond ordinary ASCII. The connection uses utf8mb4 and the specimen file declares UTF-8. The server-side checks reject invalid encodings and use a multibyte length rather than counting only bytes. The table's declared capacities still provide separate storage rules. When a string is printed into HTML, explicitly encode it for that output context. A query can be safely parameterized and still produce an unsafe or unreadable page if the rendering of its returned values is handled incorrectly.
Explain what the validated form and redirect demonstrate
In the local server the cookie associates a browser with a PHP session. The form contains a token created for that session. On a subsequent POST the application compares the submitted token with the one it stored. The sample's local-only guard and separate token check help you see the application decide before touching storage. Neither implements a full user identity or operator authorization scheme. A real multi-user registration service must authorize each write, handle personal data carefully and apply the complete security and session policy for its public path.
Follow one invalid example in the local lab. A request without the expected form token receives 403 before the app attempts an insert. A request with a good token and a blank city gets a validation response. A valid synthetic submission asks PDO to execute one inserted row and then receives 303. By comparing the database before and after each controlled request, you can tell whether a failed response happened before or after an intended write. This evidence is stronger than seeing an error message arise somewhere on the page.
The final GET after the redirect reads the current committed records. Refreshing that GET is a read. A repeated POST is a different action and may create another row because the schema uses a new generated ID rather than a unique request or student-registration policy. Decide separately what duplicate business operations mean. A form token helps verify that the session originated the request, and a redirect helps separate browser navigation from submission. Neither substitutes for database-side conditions when duplicate prevention is a requirement. This course uses a single synthetic marker and asks you to verify each operation explicitly.
Compare the shell and pool environments without exposing their contents
A student can run php -l and get a successful parser result while the public page reports a 503. The linter checks PHP syntax; it does not make a request or connect to the database. Next check that the expected PDO driver is present in the environment that executed the request. Confirm that the assigned pool receives the needed environment variables or secrets and points to the intended service. The public response should never reveal the values. A managed system may use different loaded configuration files, users and file access from your laptop.
For example, the Linux shell exports the password and the direct CLI-server test passes. The platform starts PHP-FPM through a systemd unit with its own configuration and clear environment rules. The worker legitimately has no value for the newly exported shell variable. Confirm how the authorized service should make the required variables available, and validate the pool again. A site-specific configuration or managed secret mechanism can pass these values without giving all workers access to credentials for unrelated applications. Keep the database role narrow even after transport and configuration work.
Workers and the front server also need consistent paths. The site maps an internal script request to an absolute filesystem path supplied to FPM. Even when the socket connects, the worker may not see the same path because of service confinement, working directories or ownership. Use the exact configured root and a known-file response. An error such as “Primary script unknown” can indicate an incorrect script filename or unreadable path, while an inability to connect to the socket shows an earlier failure. Avoid adding arbitrary script paths to the handler as a workaround.
Diagnose which PHP and database boundary failed
| Observed result | Compare next | Question it answers |
|---|---|---|
| HTML file works, PHP route gives a welcome page. | Check request host, active site and expected index rule. | Did the front server pick the intended application site? |
| PHP source appears or downloads. | Take that route out of public reach and inspect the effective handler. | Was the script accidentally treated as a static file? |
| Proxy response reports a gateway problem. | Check the PHP-FPM listener, socket path, permissions and daemon logs. | Could the web server reach and use the expected FastCGI process? |
| PHP returns the sample 503 body. | Check the pool's runtime configuration and an approved database session. | Does the deployed worker have the expected driver, credentials and database? |
| Local valid POST is followed by a page with the old list. | Check the 303, final GET, expected stored record and same processing environment. | Was the row actually written and then read from the intended data store? |
| Hosted browser does not offer the local form. | Read the documented mode and verify the normal GET and method policy. | Is the expected hosted route operating read-only? |
Keep the direct list request, status and correct source of the logs together. A front server log describes a client or FastCGI exchange. A pool error log can show startup, path and application errors. Database logs and query tests answer separate questions about credentials and server readiness. Use the exact event time and an approved synthetic marker. Internal errors can contain useful context inside the trusted logs, while the public response needs only enough information to explain that the data is temporarily unavailable.
For a managed production design, monitor the process and one meaningful database-backed read. The runtime can be available while the user cannot access the current list. An obsolete worker pool can respond from a different release after the app code was updated elsewhere. Record the expected marker to settle which file it executed. Do not clear an entire deployment cache, restart unrelated services or switch the database to a privileged user just to remove a symptom. A small proof on the selected site gives a more reliable path to a repair.
Match worker capacity and request lifetime to the deployed PHP mode
A PHP-FPM pool manages a set of workers that can execute PHP requests. A setting such as pm.max_children limits the child processes for a pool. The exact process model and workload determine how many requests can progress. Deliberately starting more workers also consumes memory and can allow more simultaneous database connections. Begin with the approved deployment settings. If requests queue or slow down, measure the pool and database behaviour before increasing a limit. A timeout may come from a worker queue, the database session or the response stage.
Each request in the sample creates a PDO connection when it needs to read or insert. The application has no persistent client setup. A real deployment might use connection reuse according to its service design, but it still needs clear ownership and capacity calculations. If the same DB account serves several managed pools, estimate each pool's potential demand and check the database limits. Compare the time to obtain a session with the time to execute the actual query. Both can contribute to the browser's wait, and changing the PHP worker count can move the bottleneck to the database instead of solving it.
A useful timing report records the normal size and result of the synthetic read before a config change. Compare a known app response and the separate database check under the same expected load. If an Apache or Nginx static response remains steady while only PHP requests queue, inspect its pool and dependency rather than assuming every client or DNS answer slowed down. Keep diagnostics on the assigned service. The beginner exercise aims to identify which process handled the request, so it does not create load on a live shared server.
Prove the new application code without changing its stored records
Suppose the learner changes a heading or a field label. The approved source stays in the public root, the datasource remains the same and the query still returns the seed records. Back up the previous site-specific configuration and checked release when changing a live scope. Verify the new source syntax, selected pool settings and the status of the real named response. An unchanged record count plus the new rendered heading can prove a code-only change. Avoid using a destructive schema operation to make the newer page visibly different.
If a new code release expects a changed field, keep that work separate. Plan and verify the schema update with the authorized migration role and record whether old or new code is compatible with the resulting table. Reverting one PHP file cannot restore data or table definitions that changed separately. Keep the migration and publication evidence together without including credentials. Test the original expected row and one known request from both before and after the deployment so the difference is attributable to the app and not another database.
For an operator's handoff, specify which local process and HTTP route you tested. A development PHP server test verifies the executable program and its loopback settings. A front-to-FPM test verifies the actual worker interface and server mode. Both can use identical PHP and SQL while their site scope and available form differ. State those distinctions beside the statuses, especially the read-only hosted POST response. That gives the next learner a procedure they can repeat without enabling writes on a site that only needed a list.
Identify the runtime configuration that belongs to this deployment
For the final acceptance, write down the PHP interface and extension list for the chosen app. A runtime update can change the installed FPM binary and socket and leave an older CLI first in the shell's search path. Verify each component identity through its approved service and request evidence. Keep a separate log and configuration comparison for this one pool. When another service uses a different PHP series, compare only the assigned pool and avoid changing a shared default version to make the example output match.
Interview questions with explained answers
What is the difference between PHP CLI and PHP-FPM?
The CLI runs PHP commands and scripts from your shell. PHP-FPM manages workers for FastCGI requests. They can load different settings and run as different identities, so a successful CLI check does not prove the configured web path.
What does the web server pass to PHP-FPM besides a socket address?
It passes FastCGI request parameters including how the chosen executable script should be identified. The exact script path must match a permitted file visible to the worker. The connection by itself cannot tell the worker which site rule was intended.
Why do you need both prepared SQL and HTML output encoding?
A prepared query separates SQL structure from submitted values. Encoding converts characters so a value appears as text in its HTML context. Neither mechanism replaces the other, and input validation and authorization remain separate decisions.
Why is a connection exception hidden from a public browser?
The useful public result is that the operation failed or its dependency is unavailable. Detailed errors can reveal private paths, configuration and database internals. Keep scoped diagnostic evidence in the operator's trusted logs.
What does a 303 response do after this form?
It tells the client to retrieve the resulting page with a subsequent GET. That separates a normal page refresh from repeating the submitted POST, while the application's duplicate policy still needs separate design.
Check your understanding
php -lpasses on the guest. Does that prove PHP-FPM can read the database?Show answer
It establishes syntax for the selected source. Test the actual worker configuration, driver and accepted named query response separately.
The front server points to the wrong FPM socket. Which diagnostic is likely to matter first?
Show answer
Compare the actual listening pool, its socket permissions and the web server's FastCGI target. Changing database grants cannot repair that earlier connection.
The form value contains an ampersand. Which helper makes it show as plain text in HTML?
Show answer
The selected HTML rendering uses
htmlspecialcharsfor the destination context. The bound SQL value is a distinct operation.The hosted sample is read-only. Is hiding the form enough to enforce that behaviour?
Show answer
No. It rejects the write method on the server. A real read-only configuration should also use appropriately narrow credentials.
Which result shows that a valid local submission wrote a row?
Show answer
The POST yields the expected redirect and the following GET or approved query shows the stored synthetic marker in the intended database.
Independent practice tasks
Draw the named read request through the front server, PHP-FPM and PDO session. Label the script filename and database role along different edges.
Run the local form test and record the response status and row count for the rejected and accepted synthetic operations. Verify that repeating the final GET cannot insert the row again.
Compare the local runtime and approved hosted route requirements. Identify the port or socket, config source and evidence that distinguishes a 502 front-layer failure from a PHP data failure.
Revision cards
- FastCGI and FPM
- A request interface and a managed set of PHP workers. Verify socket choice, worker access and script mapping.
- PDO MySQL
- The PHP driver that opens an approved database session using its runtime settings.
- Prepared INSERT
- A stable statement with separately supplied values. The database role still limits its permitted operations.
- Output encoding
- Render values safely for HTML rather than trusting the database to know the web context.
- Form token
- A value tied to the local session, checked before the optional synthetic write.
- 303 See Other
- A successful write redirects to a GET so the list can be read without repeating ordinary form submission.
Official sources
- PHP-FPM process manager
- PHP-FPM pool, listener and environment settings
- PHP local development HTTP server
- PDO MySQL connection parameters
- PDO prepared statements
- PDO error handling
- PHP HTML output encoding
- PHP multibyte string length
- PHP session settings
- PHP random token bytes
- Nginx FastCGI request configuration
- Nginx index mapping
- Apache FastCGI proxy handler
- MySQL role and table privileges
- HTTP methods, status and 303 response
- Amazon Linux package guide