- We offer certified developers to hire.
- We’ve performed 1500+ Web/App/eCommerce projects.
- Our clientele is 1000+.
- Free quotation on your project.
- We sign NDA for the security of your projects.
- Three months warranty on code developed by us.
PHP remains an important technology for building dynamic websites, web applications, content management systems, e-commerce platforms, customer portals, and business software. Its flexibility allows developers to create everything from simple contact forms to complex applications that handle confidential customer information and financial transactions. However, every application that accepts user input, communicates with a database, manages user sessions, or exposes an online interface introduces potential security risks.
A website can be developed using modern PHP features and still remain vulnerable if its authentication process is weak, its dependencies are outdated, its database queries are unsafe, or its server is misconfigured. Attackers frequently look for these weaknesses because exploiting one overlooked vulnerability can provide access to sensitive information, administrative functionality, or critical application resources.
Following PHP security best practices helps developers reduce these risks, protect sensitive data, maintain application availability, and build greater trust with users. Security should not be treated as a final development task. It needs to be considered throughout the application lifecycle, from initial architecture and coding decisions to deployment, monitoring, maintenance, and incident response.
This guide explains how to secure PHP applications against common vulnerabilities and cyber attacks. It covers secure coding techniques, SQL injection prevention, cross-site scripting protection, authentication, password storage, session management, file uploads, API security, server configuration, dependency management, and ongoing security testing. Practical PHP examples demonstrate how to implement these protections in real development scenarios.
Whether you maintain an existing PHP website, develop a new application, manage an e-commerce platform, or work on enterprise software, the following recommendations provide a structured foundation for improving application security.
Understanding PHP Application Security
Why PHP Security Matters
The Most Common PHP Security Vulnerabilities
Keep PHP and Its Dependencies Updated
Validate and Sanitize User Input
Prevent SQL Injection Attacks
Protect Against Cross-Site Scripting
Implement Cross-Site Request Forgery Protection
Secure Authentication and Login Systems
Store Passwords Securely
Configure PHP Sessions Safely
Protect File Upload Functionality
Prevent Remote and Local File Inclusion
Secure File Handling and Filesystem Access
Protect Against Command Injection
Prevent Server-Side Request Forgery
Use Secure HTTP Headers
Enforce HTTPS and Secure TLS Configuration
Protect Sensitive Data and Application Secrets
Secure Database Connections and Permissions
Implement Secure Error Handling and Logging
Apply PHP Security Best Practices for APIs
Configure PHP for Production Security
Protect Against Brute-Force Attacks and Bots
Secure File Downloads and Document Access
Apply the Principle of Least Privilege
Use Secure Coding Standards and Architecture
Protect PHP Applications Against Business Logic Abuse
Secure E-Commerce and Payment Processing
Strengthen WordPress and Other PHP-Based CMS Platforms
Use Composer Securely
Test PHP Applications for Security Vulnerabilities
Integrate Security into the Development Lifecycle
Monitor, Maintain, and Respond to Security Incidents
Common PHP Security Mistakes to Avoid
PHP Security Checklist for Developers
Frequently Asked Questions About PHP Security
Conclusion
PHP application security is the practice of protecting PHP-based websites and applications against unauthorised access, data exposure, malicious input, software vulnerabilities, and other threats that could compromise confidentiality, integrity, or availability.
A secure PHP application does more than prevent attackers from submitting harmful input. It establishes multiple layers of protection around every important operation, including authentication, database access, file processing, payment handling, administrative functions, and communication with external services.
Consider a typical business website with a registration form, customer dashboard, contact form, document upload feature, and administrative panel. Each feature has different security requirements.
A registration form must validate submitted information and protect account creation.
A customer dashboard must verify that the logged-in user is authorised to access each requested record.
A contact form must handle untrusted input without executing malicious scripts.
A document upload feature must prevent executable files from being uploaded and exposed.
An administrative panel must enforce strong authentication and appropriate access controls.
A payment integration must verify transaction results through trusted server-side processes.
These controls should work together rather than operate as isolated security measures.
A threat model identifies the assets an application needs to protect, the people or systems that might attack it, the entry points exposed to those attacks, and the consequences of a successful compromise.
For example, a customer portal may need to protect email addresses, billing records, password hashes, session identifiers, and downloadable invoices. Its potential attack surfaces include login forms, API endpoints, search parameters, uploaded documents, password reset links, and third-party integrations.
A useful initial assessment asks five questions:
What information or functionality must remain protected?
Which parts of the application accept external input?
What permissions does each user role require?
What would happen if an attacker gained access to an account, database, or server?
How would the team detect and recover from an attack?
The answers help developers prioritise controls according to actual risk instead of applying security measures without understanding their purpose.
PHP applications commonly rely on several interconnected components:
The browser or client application.
The web server, such as Apache or Nginx.
The PHP runtime and PHP-FPM, where applicable.
The application code and its framework.
The database server.
External APIs and third-party services.
The operating system, network, and hosting environment.
A vulnerability in any one of these components can affect the security of the entire application.
For instance, parameterised SQL queries can reduce SQL injection risk, but they cannot compensate for an exposed database administration interface. Similarly, secure password hashing does not prevent account takeover if password reset tokens are predictable or administrator accounts lack appropriate protections.
The central principle is defence in depth: use several complementary controls so that a single failure does not automatically compromise the entire system.
No single PHP security checklist can guarantee that an application will remain secure forever. New vulnerabilities emerge, dependencies change, application features expand, and attackers develop new techniques.
A sustainable security programme therefore combines:
Secure development practices.
Automated and manual testing.
Timely security updates.
Restricted permissions.
Monitoring and alerting.
Regular backups.
Documented incident response procedures.
This approach helps teams identify weaknesses before attackers exploit them and respond more effectively when something goes wrong.
A website’s security directly affects its users, business operations, reputation, and ability to comply with applicable legal and contractual obligations.
An exploited PHP vulnerability can expose customer information, alter website content, interrupt services, distribute malware, or provide a route into connected systems. The consequences depend on the application’s architecture, the permissions available to the compromised process, and the information it handles.
PHP applications often process personally identifiable information, customer communications, account credentials, business documents, order histories, and payment-related records.
If attackers gain access to this information, the organisation may face customer complaints, remediation expenses, regulatory investigations, and loss of trust.
Data protection should therefore begin with a clear understanding of what the application actually needs to collect and retain. Avoid storing information that is unnecessary for the application’s purpose, and apply stronger controls to data that would cause greater harm if exposed.
Attackers may exploit vulnerable PHP applications to modify files, create unauthorised accounts, inject malicious content, or establish persistence on a server.
A compromised website can also become a platform for phishing, malware distribution, spam, or attacks against other systems.
Restricting filesystem permissions, updating vulnerable packages, isolating applications, and monitoring unusual activity reduces the opportunities available to attackers.
Security incidents can affect availability as well as confidentiality. Excessive login attempts, resource-intensive requests, vulnerable plugins, malicious file processing, and application-level denial-of-service attacks may prevent legitimate visitors from accessing a website.
Rate limiting, sensible resource limits, caching, monitoring, and appropriate infrastructure protections can reduce these risks.
Customers expect websites to handle their information responsibly. Security failures can undermine that confidence, particularly when an application processes financial information or confidential business records.
Depending on the organisation, its customers, and the data involved, security requirements may also arise from privacy laws, payment industry standards, contracts, or sector-specific regulations.
For example, organisations that handle payment card data may need to comply with relevant Payment Card Industry Data Security Standard requirements. The exact obligations depend on the payment architecture and applicable scope.
Security controls should be selected and documented according to the application’s real operating environment rather than based on assumptions that one technical measure satisfies every compliance requirement.
Understanding common attack techniques helps developers identify the places where security controls are most important. Many successful attacks do not require a sophisticated exploit. They exploit ordinary development mistakes, such as trusting request parameters, exposing configuration files, or assuming that hiding a button prevents unauthorised access.
The following vulnerabilities deserve particular attention in PHP applications.
| Vulnerability | Typical cause | Primary protection |
|---|---|---|
| SQL injection | Building SQL queries from untrusted input | Prepared statements |
| Cross-site scripting (XSS) | Rendering untrusted content without context-appropriate encoding | Output encoding |
| Cross-site request forgery (CSRF) | Accepting unauthorised state-changing browser requests | CSRF tokens and request controls |
| Broken access control | Failing to check ownership or permissions | Server-side authorisation |
| Insecure authentication | Weak login and recovery mechanisms | Strong authentication controls |
| Session hijacking | Exposed or predictable session identifiers | Secure cookie settings and session rotation |
| Remote code execution | Unsafe evaluation, file inclusion, or command execution | Remove dangerous patterns and isolate execution |
| Unrestricted file uploads | Trusting filenames or extensions | Content validation and isolated storage |
| Server-side request forgery (SSRF) | Fetching attacker-controlled URLs without adequate restrictions | Destination validation and network controls |
| Information disclosure | Exposing stack traces, secrets, or internal paths | Production configuration and careful logging |
| Insecure deserialisation | Processing untrusted serialised PHP objects | Avoid unsafe deserialisation |
| Dependency vulnerabilities | Using vulnerable libraries or abandoned packages | Dependency auditing and updates |
These categories overlap. A single feature, such as importing a document, can involve file validation, path traversal, archive extraction, parser vulnerabilities, and access control.
Injection occurs when an application treats untrusted data as part of an executable instruction. SQL injection is a common example, but similar problems can occur with operating system commands, template expressions, and other interpreters.
The appropriate protection depends on the interpreter involved. Prepared statements protect SQL values, for example, but do not automatically make shell commands or HTML output safe.
An application may authenticate a user correctly but still allow that user to access another person’s records.
Imagine an invoice endpoint that accepts an invoice identifier in the URL. If the application retrieves the invoice using only that identifier and never checks ownership, a customer may be able to view another customer’s invoice by changing the identifier.
This is an authorisation failure, often associated with insecure direct object references. The correct solution is to enforce access rules on the server for every protected operation.
PHP supports file operations, stream wrappers, and object serialisation. These features are useful, but they become dangerous when external input determines which file is loaded, which object is reconstructed, or which operation is executed.
Treat file paths, archive entries, serialised data, and external resource identifiers as untrusted unless their origin and integrity are established.
Development configurations sometimes display errors directly in the browser, reveal filesystem paths, or expose debugging tools. These details may help an attacker identify the framework, installed components, or internal directory structure.
Production environments should minimise public error information while retaining enough structured logging to diagnose failures securely.
One of the most important PHP website security practices is maintaining supported versions of the PHP runtime, frameworks, libraries, and server software.
Security patches address known weaknesses. Delaying updates leaves an application exposed to vulnerabilities that attackers may already understand and actively target.
PHP receives security support according to its official release lifecycle. Once a branch reaches the end of its support period, it no longer receives routine upstream security fixes.
Before selecting a version, review the official PHP supported versions page and the relevant release notes.
Choose a supported version compatible with your framework, application code, hosting environment, and required extensions.
Do not assume that an old application is secure simply because it continues to function. Compatibility and security are separate concerns.
Updating PHP directly on a production server without testing can introduce compatibility problems. A safer approach separates testing from deployment.
A practical workflow is:
Review the security advisory or release notes.
Identify affected packages and application components.
Apply updates in a development or staging environment.
Run automated tests and test critical user journeys.
Check logs for warnings and compatibility issues.
Deploy using a documented release process.
Verify application health after deployment.
Retain a tested rollback procedure.
Security fixes should be prioritised according to exploitability, exposure, business impact, and the availability of mitigations.
A PHP application may use Symfony, Laravel, a CMS, an authentication package, an image-processing library, or dozens of other dependencies.
A secure core runtime does not protect an application from a vulnerable third-party component.
Maintain an inventory of dependencies, including packages used indirectly by other packages. Remove components that are no longer required, especially abandoned libraries that receive no security maintenance.
For Composer-based projects, run:
composer audit
This checks installed package information against security advisories available to Composer’s audit functionality. The result is useful, but it is not proof that the entire application is vulnerability-free.
Also review official framework advisories and the security notices of important third-party libraries.
Automatically installing every new dependency version directly on a live website can create operational risk. Conversely, postponing every update indefinitely creates security risk.
Use a repeatable process that locks dependency versions, tests changes, prioritises security fixes, and deploys them promptly.
For high-risk vulnerabilities, a temporary mitigation may be necessary while a permanent fix is prepared. Document the mitigation and set a deadline for removing it.
An application may depend on an old plugin, a custom library, or a PHP extension that is no longer maintained.
If a component cannot receive security fixes, determine whether it can be upgraded, replaced, isolated, or removed. Continuing to use an unsupported component requires an explicit risk decision rather than an assumption that no attack will occur.
Input validation is a fundamental PHP security control because applications routinely receive information from sources they cannot fully trust.
These sources include:
Form submissions.
Query string parameters.
HTTP request headers.
Cookies.
API requests.
Uploaded files.
Webhook payloads.
Data imported from external services.
Values stored in databases that originated from users.
A common mistake is assuming that input becomes trustworthy after it has been received through a form or stored in a database. Data can be modified in the browser, submitted directly to an endpoint, or changed through another application feature.
Validation checks whether a value conforms to the rules of the relevant field.
For example, a registration form may expect an email address, a positive customer quantity, or a date within a permitted range.
PHP provides functions such as filter_var() for common validation tasks.
<?php
$email = $_POST['email'] ?? '';
if (!is_string($email) ||
filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
http_response_code(400);
exit('Invalid email address.');
}
// Continue with the validated email address.
This example rejects missing, non-string, and invalid email values. In a real application, the response should follow the application’s normal error-handling and user-experience conventions.
Email syntax validation does not establish that an address exists or belongs to the user. Ownership usually requires a verification message or another appropriate process.
Allowlist validation defines the acceptable values or formats rather than trying to identify every possible malicious value.
For instance, if a user can choose a report format, the application may permit only pdf and csv.
<?php
$format = $_GET['format'] ?? 'pdf';
$allowedFormats = ['pdf', 'csv'];
if (!is_string($format) ||
!in_array($format, $allowedFormats, true)) {
http_response_code(400);
exit('Unsupported report format.');
}
An allowlist is particularly effective for fixed choices, role names, sorting options, status values, and supported file formats.
However, a string should not be considered safe merely because it matches a regular expression. The application must still handle the value appropriately for the operation in which it is used.
Validation should cover more than whether a value contains unexpected characters.
Check:
Whether the value has the expected type.
Whether numeric values fall within permitted limits.
Whether arrays contain only the expected elements.
Whether strings have acceptable lengths.
Whether dates are valid and relevant.
Whether identifiers correspond to existing records.
Whether the user is authorised to act on those records.
For example, a quantity field might accept an integer between 1 and 100. A file upload might have a maximum size and a restricted set of permitted formats.
Use explicit rules that match the application’s business requirements.
Validation and output encoding solve different problems.
Validation determines whether submitted data meets the application’s requirements. Output encoding changes how data is represented when it is inserted into a particular output context.
A valid name can still contain characters that need HTML encoding. Similarly, an email address that passes validation should not automatically be inserted into a JavaScript string without the appropriate handling.
Use validation at the point where input enters the application, then apply context-specific protections when using that data.
Stored data may have originated from an earlier version of the application, an administrator, an import process, or an external integration.
If an application displays stored comments, profile descriptions, or product information, it should not assume that database content is safe to render as HTML.
Apply the relevant output-encoding rules when displaying the information.
Reusable validation rules can make an application more consistent. Framework request validators, form objects, and domain-specific validation services can reduce duplicated code.
However, a central validator should not become a reason to skip validation at sensitive boundaries. Each endpoint must still enforce the requirements of its operation, including authorisation and business rules.
SQL injection occurs when untrusted input changes the meaning of a database query. Depending on the database permissions and application design, an attack may expose confidential records, alter data, bypass authentication, or damage stored information.
The primary defence against SQL injection in PHP is the use of parameterised queries or prepared statements.
Consider an unsafe query:
<?php
$id = $_GET['id'] ?? '';
$sql = "SELECT id, name, email FROM users WHERE id = '$id'";
The query incorporates request data directly into SQL syntax. An attacker may supply specially constructed input that changes the query’s meaning.
Escaping individual characters is not the preferred general solution. Escaping rules depend on the database, character encoding, and query context, and are easy to apply incorrectly.
PHP’s PDO extension supports parameterised queries for supported database drivers.
<?php
$pdo = new PDO(
'mysql:host=localhost;dbname=app_db;charset=utf8mb4',
$dbUser,
$dbPassword,
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false,
]
);
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if ($id === false || $id === null || $id < 1) {
http_response_code(400);
exit('Invalid record identifier.');
}
$stmt = $pdo->prepare(
'SELECT id, name, email FROM users WHERE id = :id'
);
$stmt->execute(['id' => $id]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
In this example, the identifier is validated and passed separately from the SQL statement. The database driver handles the parameter according to its supported parameterisation mechanism.
The database credentials are represented by variables here. In a production application, obtain them from an appropriately protected configuration or secret-management system.
Prepared statements prevent input values from being interpreted as SQL syntax. They do not automatically validate business rules or determine whether a user is authorised to view the retrieved record.
A single safe query does not make the entire application safe.
Review database operations used for:
User registration and login.
Product searches.
Customer dashboards.
Administrative filters.
Order management.
Report generation.
Pagination.
Sorting.
Data imports.
API endpoints.
Use prepared statements consistently rather than only on pages that appear sensitive.
Prepared statement placeholders generally represent data values, not SQL identifiers such as table names or column names.
For example, the following pattern is unsafe if $sort comes directly from a request:
$sql = "SELECT id, name FROM products ORDER BY $sort";
Instead, map permitted options to predefined SQL fragments.
<?php
$sortOption = $_GET['sort'] ?? 'name';
$sortColumns = [
'name' => 'name',
'price' => 'price',
'created' => 'created_at',
];
if (!is_string($sortOption) ||
!array_key_exists($sortOption, $sortColumns)) {
http_response_code(400);
exit('Invalid sorting option.');
}
$column = $sortColumns[$sortOption];
$stmt = $pdo->query(
"SELECT id, name, price FROM products ORDER BY $column"
);
The interpolated column name comes from a fixed allowlist, not directly from the request. For user-controlled values in the query, continue using parameters.
The database account used by a public-facing application should have only the permissions it needs.
A read-only reporting feature should not require permission to drop tables. A customer-facing application generally should not use a database administrator account.
Where practical, separate credentials for distinct application functions and environments. Restrict access to database administration interfaces and avoid exposing database ports unnecessarily.
This limits the damage that can occur if an application query or credential is compromised.
Raw database errors may reveal table names, SQL fragments, internal paths, and schema details.
Catch database exceptions at the appropriate application boundary, log diagnostic information securely, and return a generic error to the user.
Do not suppress every database exception and continue as though the operation succeeded. The application must handle failures correctly while avoiding unnecessary disclosure.
Cross-site scripting occurs when an application causes untrusted content to execute as script in a user’s browser.
An XSS vulnerability can allow attackers to perform actions in the context of a victim’s session, alter displayed content, capture information available to the page, or redirect users to malicious destinations. The actual impact depends on the browser, application architecture, session protections, and the content exposed to the script.
PHP developers should treat output encoding as a standard requirement whenever application data is inserted into a browser-rendered context.
Stored XSS: Malicious content is saved, for example, in a comment or profile field, and executes when another user views it.
Reflected XSS: Untrusted input is included in a response, such as an error page, without appropriate encoding.
DOM-based XSS: Client-side JavaScript uses untrusted data in a way that causes unsafe browser interpretation.
Stored XSS can be particularly serious on administrative dashboards because a malicious comment may be displayed to users with elevated privileges.
For ordinary HTML text and appropriately quoted HTML attribute values, PHP’s htmlspecialchars() is a useful defence.
<?php
$name = $user['name'] ?? '';
echo htmlspecialchars(
(string) $name,
ENT_QUOTES | ENT_SUBSTITUTE,
'UTF-8'
);
The function encodes characters that could otherwise be interpreted as HTML markup or attribute syntax. The explicit UTF-8 encoding and flags make the intended behaviour clearer.
Use the function at the point where the value is rendered, not as a universal replacement for every security control.
HTML text, JavaScript, CSS, URLs, and HTML attributes have different parsing rules.
For example, HTML encoding alone is not a universal defence for a value inserted into a JavaScript expression. The safest approach is often to avoid placing untrusted data inside executable contexts altogether.
When passing structured data from PHP to JavaScript, use JSON serialization rather than manually building a script string.
<?php
$userData = [
'name' => $user['name'] ?? '',
'active' => (bool) ($user['active'] ?? false),
];
$json = json_encode(
$userData,
JSON_HEX_TAG |
JSON_HEX_AMP |
JSON_HEX_APOS |
JSON_HEX_QUOT |
JSON_THROW_ON_ERROR
);
?>
<script>
const userData = <?= $json ?>;
</script>
This pattern uses JSON encoding and additional hexadecimal escaping flags for safer embedding in the example’s script context. For applications that support it, serving structured JSON through a separate endpoint and consuming it as data is often simpler and easier to maintain.
Do not construct JavaScript source code by concatenating raw user input.
Some applications legitimately allow rich text, such as product descriptions, help articles, or user-authored content.
In these cases, encoding every HTML character would remove the intended formatting. The alternative is to use a well-maintained HTML sanitisation library with an explicit allowlist of permitted elements, attributes, and URL schemes.
For example, an application might permit paragraphs, headings, lists, and basic emphasis while rejecting scripts, event-handler attributes, unsafe embedded content, and dangerous URLs.
Sanitisation policies should be reviewed when requirements change. A custom collection of regular expressions is not a reliable substitute for a dedicated HTML sanitiser.
A Content Security Policy (CSP) can limit which script sources a browser is permitted to load or execute.
For example, a carefully tested policy might begin with:
Content-Security-Policy: default-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'self'
This is an illustrative starting point, not a complete policy for every application. Real websites may need to configure script-src, style-src, img-src, connect-src, and other directives according to their resources.
Avoid adding broad exceptions such as 'unsafe-inline' or 'unsafe-eval' without understanding the consequences. Nonces or hashes can help support controlled script execution.
Deploy new CSP policies in report-only mode first when appropriate, review violations, and then enforce a policy compatible with the application’s requirements.
Search results, validation errors, user profiles, product reviews, administrative tables, and notification messages are common locations for XSS vulnerabilities.
Template engines can provide automatic escaping, but developers must understand when escaping is enabled, which contexts it supports, and how raw-output features bypass it.
Never assume that a framework’s default template protection makes every custom rendering operation safe.
Cross-site request forgery (CSRF) occurs when a victim’s browser is induced to send a request to an application where the victim is already authenticated.
If the application accepts the request based only on automatically attached credentials, the victim may unknowingly change account details, submit an order, or perform another state-changing action.
For browser-based applications that rely on cookies for authentication, state-changing requests should generally include a session-bound or otherwise securely generated CSRF token.
PHP’s cryptographically secure random number generator can create a token.
<?php
session_start();
if (
!isset($_SESSION['csrf_token']) ||
!is_string($_SESSION['csrf_token'])
) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
?>
<form method="post" action="/account/update">
<input
type="hidden"
name="csrf_token"
value="<?= htmlspecialchars(
$_SESSION['csrf_token'],
ENT_QUOTES | ENT_SUBSTITUTE,
'UTF-8'
) ?>"
>
<label for="display_name">Display name</label>
<input
type="text"
id="display_name"
name="display_name"
required
>
<button type="submit">Save changes</button>
</form>
The receiving endpoint must validate the submitted token before processing the change.
<?php
session_start();
$submittedToken = $_POST['csrf_token'] ?? '';
$sessionToken = $_SESSION['csrf_token'] ?? '';
if (
!is_string($submittedToken) ||
!is_string($sessionToken) ||
!hash_equals($sessionToken, $submittedToken)
) {
http_response_code(403);
exit('Request could not be verified.');
}
// Continue with validation, authorisation and the update.
The token is only one part of the control. The endpoint must still validate input and confirm that the authenticated user has permission to change the requested account.
CSRF protection is not limited to profile update forms. Review endpoints that:
Change passwords or email addresses.
Add or remove users.
Modify account settings.
Create or cancel orders.
Change payment or delivery details.
Delete records.
Alter administrative settings.
Do not use GET requests for operations that change application state.
The SameSite cookie attribute helps control when browsers attach cookies to cross-site requests.
Values such as Lax and Strict can reduce CSRF exposure, depending on the application’s navigation and authentication requirements. SameSite=None permits cross-site cookie use in supported browser contexts and requires Secure.
SameSite is a useful additional control, but it should not automatically replace CSRF tokens for sensitive cookie-authenticated operations.
For sensitive browser requests, checking the Origin header and, where appropriate, the Referer header can provide additional protection.
These checks should account for the application’s legitimate origins, reverse proxies, and supported browser behaviour. Missing or unexpected headers should be handled according to an explicit security policy.
Authentication verifies a user’s identity. If the authentication process is weak, attackers may access accounts even when database queries and output handling are secure.
A strong PHP authentication system combines secure credential storage, sensible login controls, session management, account recovery protections, and appropriate multi-factor authentication.
Password rules should encourage long, unique passwords rather than relying exclusively on complicated character combinations.
Allow users to use password managers and paste passwords into password fields. Avoid silently truncating passwords or imposing unnecessarily restrictive maximum lengths.
The permitted length should be appropriate for the chosen password hashing mechanism and implementation.
Check passwords against commonly used or known-compromised password lists where feasible. Avoid revealing whether a particular account exists during login or password recovery.
Multi-factor authentication (MFA) requires another factor in addition to the password. This can reduce the risk associated with stolen or reused credentials.
Depending on the application and risk level, options include authenticator applications, hardware security keys, and passkeys where supported.
Prioritise MFA for administrators, financial functions, privileged users, and accounts that can access sensitive information.
MFA recovery needs its own security design. Recovery codes should be generated securely, stored in a protected form, and invalidated after use. Account recovery must not be weaker than the normal authentication process.
Unrestricted login attempts allow attackers to test many password combinations or attempt credential stuffing with previously exposed credentials.
Rate limiting should consider multiple signals, such as account identifier, IP address, request volume, and suspicious behaviour. IP-based limits alone may be insufficient because attackers can distribute requests across many addresses.
A practical implementation can combine progressive delays, temporary restrictions, bot detection, and alerts for unusual login patterns.
Avoid permanent account lockouts that attackers can deliberately trigger to deny service to legitimate users.
An error message such as “This email address does not exist” may help an attacker enumerate valid accounts.
A more appropriate response is often:
The email address or password is incorrect.
The same principle applies to password reset requests. Responses should avoid unnecessarily disclosing whether a user account exists.
Generic messages should not prevent legitimate users from receiving clear, accessible guidance on how to recover access.
Password reset functionality is part of the authentication system and deserves the same level of attention as the login form.
Use cryptographically random, sufficiently long reset tokens. Store a secure representation of each token, associate it with the intended account, and enforce an expiry time.
A reset token should normally be single-use. Invalidate it after a successful password reset, and consider invalidating existing sessions or requiring reauthentication according to the application’s risk profile.
Send reset links through a verified communication channel. Avoid including passwords in email messages.
After a password reset, provide a notification to the account owner and consider offering a way to revoke existing sessions.
Administrative accounts can make changes that affect the entire application. They should receive stronger protection than ordinary user accounts.
Use MFA, restrict privileged permissions, monitor unusual administrative activity, and avoid shared administrator accounts.
Where practical, separate everyday user accounts from privileged accounts. Require reauthentication before particularly sensitive actions, such as changing payment details, exporting large datasets, or modifying security settings.
Password storage is a critical element of PHP website security. Applications should never store plaintext passwords or rely on fast general-purpose hashes such as MD5 or SHA-1 for password protection.
Instead, use PHP’s built-in password hashing API, which is designed for password storage.
<?php
$password = $_POST['password'] ?? '';
if (!is_string($password) || $password === '') {
http_response_code(400);
exit('A valid password is required.');
}
$passwordHash = password_hash(
$password,
PASSWORD_DEFAULT
);
// Store $passwordHash in a suitable database column.
PASSWORD_DEFAULT selects PHP’s current default password hashing algorithm. PHP may change that default in a future release, so database columns should allow enough space for the resulting hash and future changes.
Do not store the original password alongside the hash. Also avoid logging submitted passwords, even when a registration or login request fails.
When a user logs in, compare the submitted password with the stored hash using PHP’s verification function.
<?php
if (password_verify($submittedPassword, $storedHash)) {
// The password matches the stored hash.
} else {
// Reject the login attempt.
}
Do not attempt to recreate the hashing algorithm manually or compare password hashes using ordinary string equality.
The verification function handles the format and parameters associated with supported password hashes.
Password hashing requirements evolve as computing capabilities and recommended algorithms change.
PHP provides password_needs_rehash() to help determine whether a stored hash should be updated.
<?php
if (password_verify($submittedPassword, $storedHash)) {
if (password_needs_rehash($storedHash, PASSWORD_DEFAULT)) {
$newHash = password_hash(
$submittedPassword,
PASSWORD_DEFAULT
);
// Save $newHash to the database.
}
// Continue with the authenticated login process.
}
A production implementation should handle database failures correctly and complete the login process only after the required security operations succeed.
Password hashing is intended to be one-way. The application verifies a submitted password against the stored hash without decrypting it.
Encryption serves a different purpose: it allows authorised systems to recover the original data using a key.
Passwords should generally be hashed rather than encrypted for storage. Other information, such as an API credential that the application must retrieve later, may require encryption or a dedicated secrets-management solution.
Changing a password, disabling MFA, or replacing an account’s recovery email can have serious security consequences.
Require the current password or another appropriate verification method before performing high-risk account changes. A valid session alone may not provide sufficient assurance if the session has been stolen.
PHP sessions allow applications to associate multiple HTTP requests with an authenticated user or temporary state. Because HTTP is stateless, sessions are central to many login systems.
If an attacker obtains a valid session identifier, the attacker may be able to impersonate its owner. Session security therefore depends on how identifiers are generated, transmitted, stored, and invalidated.
Configure session behaviour before calling session_start().
<?php
ini_set('session.use_strict_mode', '1');
ini_set('session.use_only_cookies', '1');
session_start();
Strict mode helps PHP reject uninitialised session identifiers in supported configurations. Cookie-only session handling prevents session identifiers from being accepted through alternative URL-based mechanisms.
In production, configure these settings centrally and verify the effective configuration for the actual runtime. Avoid relying exclusively on individual scripts to establish security settings.
For a website served exclusively over HTTPS, session cookies should normally use the Secure and HttpOnly attributes.
A typical configuration is:
<?php
ini_set('session.use_strict_mode', '1');
ini_set('session.use_only_cookies', '1');
session_set_cookie_params([
'lifetime' => 0,
'path' => '/',
'secure' => true,
'httponly' => true,
'samesite' => 'Lax',
]);
session_start();
Call session_set_cookie_params() before starting the session.
The Secure attribute restricts cookie transmission to HTTPS connections. HttpOnly prevents ordinary browser JavaScript from reading the cookie directly. SameSite helps control cross-site cookie transmission.
These attributes do not eliminate every session attack. An XSS vulnerability may still allow malicious code to perform actions through the victim’s browser, even if it cannot read an HttpOnly cookie.
An attacker may try to cause a victim to authenticate using a session identifier the attacker already knows. This is known as session fixation.
After a successful login, regenerate the session identifier.
<?php
if ($authenticationSucceeded) {
session_regenerate_id(true);
$_SESSION['user_id'] = $userId;
$_SESSION['authenticated'] = true;
}
The authentication variables shown are illustrative. The application should set its authenticated state only after credentials have been verified and any required authentication checks have succeeded.
Regenerate session identifiers after other significant privilege changes where appropriate.
An authenticated session should not remain valid indefinitely without consideration of risk.
An idle timeout expires sessions after a period of inactivity. An absolute timeout limits the total lifetime of a session, even if activity continues.
For example, an administrative portal may use shorter limits than a low-risk public website. Financial applications may require reauthentication for sensitive transactions.
Timeout values should reflect the application’s risk, user experience, and operational requirements. Enforce them on the server rather than relying only on client-side timers.
When a user logs out, invalidate the server-side session and expire its cookie.
Also consider how the application handles password changes, account suspension, privilege removal, and suspected compromise.
For systems with high security requirements, a session version or revocation mechanism can help invalidate existing sessions across devices. The implementation must check the relevant revocation state when processing authenticated requests.
Session files or database records may contain sensitive authentication state. Restrict access to the storage location and ensure that one application’s sessions cannot be read or modified by unrelated users or applications.
Avoid storing unnecessary personal information, credentials, or long-lived secrets in session data.
File uploads create a significant attack surface because uploaded content may originate from an untrusted user and later be stored, processed, displayed, or downloaded by the application.
An attacker may attempt to upload executable scripts, oversized files, malicious documents, misleading file types, or files crafted to exploit a vulnerable parser.
A secure upload workflow should validate the request, limit resource consumption, verify the content, store the file safely, and enforce access controls whenever it is retrieved.
A filename ending in .jpg does not prove that the file contains a valid image. Similarly, a browser-provided MIME type is not reliable evidence of the file’s true content.
Use a combination of controls appropriate to the permitted formats:
Allowlist extensions.
Inspect content using suitable server-side tools.
Apply file-size limits.
Generate a new storage name.
Reject unexpected file structures.
Store uploads outside executable web directories.
Enforce access controls on retrieval.
Scan content where justified by the application’s risk.
No single check is sufficient for every file type.
PHP provides upload metadata through the $_FILES array. Check the upload error code and verify that the file was uploaded through the expected mechanism.
<?php
if (!isset($_FILES['document'])) {
http_response_code(400);
exit('No file was uploaded.');
}
$file = $_FILES['document'];
if (
!is_array($file) ||
!isset($file['error'], $file['tmp_name'], $file['size']) ||
!is_int($file['error']) ||
$file['error'] !== UPLOAD_ERR_OK
) {
http_response_code(400);
exit('The upload could not be processed.');
}
if (
!is_string($file['tmp_name']) ||
!is_int($file['size']) ||
$file['size'] < 1 ||
$file['size'] > 5 * 1024 * 1024
) {
http_response_code(400);
exit('The file does not meet the upload requirements.');
}
if (!is_uploaded_file($file['tmp_name'])) {
http_response_code(400);
exit('Invalid upload.');
}
This example checks the basic upload state and imposes a 5 MB application-level size limit. The server’s PHP and web server limits should also be configured to prevent oversized requests from consuming excessive resources.
A complete upload handler needs further checks before the file is accepted.
For an image upload, PHP’s Fileinfo extension can help identify the MIME type based on file content.
<?php
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mimeType = $finfo->file($file['tmp_name']);
$allowedTypes = [
'image/jpeg' => 'jpg',
'image/png' => 'png',
'image/webp' => 'webp',
];
if (!is_string($mimeType) ||
!isset($allowedTypes[$mimeType])) {
http_response_code(400);
exit('Unsupported file type.');
}
$extension = $allowedTypes[$mimeType];
This is a useful check, but MIME detection alone does not establish that a file is harmless. Some formats can contain complex structures, and malicious content may target vulnerable image or document-processing libraries.
For image workflows, consider decoding and re-encoding accepted images with a maintained library. This can remove certain forms of embedded content, although it is not a substitute for patching the processing library or enforcing resource limits.
Never use a submitted filename as the direct storage path.
<?php
$storedName = bin2hex(random_bytes(16)) . '.' . $extension;
$uploadDirectory = '/var/app/private-uploads';
$destination = $uploadDirectory . DIRECTORY_SEPARATOR . $storedName;
if (!move_uploaded_file($file['tmp_name'], $destination)) {
http_response_code(500);
exit('The file could not be saved.');
}
The directory in this example must already exist, be writable by the application’s dedicated service account, and be inaccessible for direct script execution or public directory listing.
The application should separately store the generated filename and any permitted display metadata in its database.
A private storage directory is generally safer than placing uploaded files in a publicly executable directory.
If users need to retrieve their documents, serve them through an authorised download endpoint. The endpoint should verify ownership or permission before returning the file.
If public access is genuinely required, use a dedicated static file location or storage service with appropriate restrictions. Prevent uploaded scripts from being executed by the web server.
Applications that accept ZIP files or other archives face additional risks.
An archive may contain path traversal entries, an excessive number of files, or data that expands to a much larger size than the original upload.
When extracting archives:
Reject paths that resolve outside the intended destination.
Limit total extracted size and file count.
Restrict supported file types.
Reject symbolic links or handle them through an explicit safe policy.
Avoid overwriting application files.
Process archives in a restricted environment.
Apply time and memory limits.
Archive extraction should be treated as a separate security-sensitive operation rather than a routine extension of uploading.
PHP settings such as upload_max_filesize and post_max_size affect upload handling. Web servers, reverse proxies, application frameworks, and hosting platforms may impose additional request limits.
Set these limits according to the application’s actual requirements. Large uploads should not be accepted simply because the server can technically process them.
PHP includes functions such as include, require, include_once, and require_once to load application files. Used with trusted, predefined paths, these functions are normal parts of application development.
They become dangerous when external input determines which file is loaded.
An unsafe pattern might look like this:
<?php
$page = $_GET['page'] ?? 'home';
include $page . '.php';
If an attacker can manipulate the value in an unexpected way, the application may load unintended files or, under certain conditions, execute attacker-controlled code.
Do not build include paths directly from request data.
A safer pattern maps supported page identifiers to predefined files.
<?php
$pages = [
'home' => __DIR__ . '/pages/home.php',
'about' => __DIR__ . '/pages/about.php',
'contact' => __DIR__ . '/pages/contact.php',
];
$pageName = $_GET['page'] ?? 'home';
if (!is_string($pageName) ||
!array_key_exists($pageName, $pages)) {
http_response_code(404);
exit('Page not found.');
}
require $pages[$pageName];
The request selects a known application page but cannot directly specify a filesystem path.
The allow_url_include setting should remain disabled unless a specific, justified requirement exists. Remote content should not be included as executable PHP code.
Even when remote inclusion is disabled, local file inclusion and path traversal may remain possible if application code uses unsafe paths.
Review PHP configuration and application code together. A restrictive configuration is valuable, but it cannot replace safe path selection.
Store secrets and sensitive configuration outside publicly accessible directories where possible. Prevent direct access to environment files, source-control metadata, backup archives, and configuration files.
Do not rely solely on a web server rule that blocks a particular filename. A stronger architecture avoids placing sensitive material in publicly served locations in the first place.
PHP applications frequently read, write, rename, and delete files. These operations can become security vulnerabilities when paths, permissions, or filenames are not controlled.
Path traversal occurs when input is used to access files outside an intended directory, often through path components such as ../.
A download endpoint that accepts a filename and appends it to a storage directory may be vulnerable if it does not restrict the resulting path.
A safer design maps opaque document identifiers to server-side file records. The client requests a document by its application identifier, and the application resolves that identifier to an authorised storage location.
Where filesystem paths must be constructed dynamically, validate them against a fixed base directory and account for canonical paths, symbolic links, and race conditions. A simple substring check for .. is not a complete defence.
The PHP process should not be able to modify application code or system files unless a specific operation requires that ability.
Use separate ownership and permissions for executable application files, temporary files, uploads, logs, and generated documents.
Avoid broad permissions such as 0777. They allow more users or processes to modify a resource than necessary.
When replacing configuration, generating reports, or writing sensitive files, incomplete writes can cause inconsistent states.
For critical operations, consider writing to a temporary file in the same filesystem and then performing a controlled rename after the data has been fully written and validated.
Atomicity does not automatically provide access control or protect against malicious input, but it can improve reliability and reduce certain failure scenarios.
Temporary files may contain personal data, exported reports, uploaded documents, or other sensitive information.
Use appropriate temporary-file facilities, restrictive permissions, predictable cleanup processes, and controlled storage locations.
Avoid constructing temporary paths from untrusted input. Ensure that cleanup operations cannot be redirected to arbitrary files.
Command injection occurs when an application passes untrusted input into an operating system command and that input changes the command’s behaviour.
PHP provides functions such as exec(), shell_exec(), system(), and passthru(). These functions can be legitimate in controlled environments, but using them with request data creates substantial risk.
If the application needs to manipulate an image, inspect a document, or process a CSV file, prefer a maintained library that performs the task directly.
Using a library avoids unnecessary shell interpretation and may simplify input validation, error handling, and portability.
However, libraries also need updates and resource limits. Replacing a shell command with an outdated parser does not automatically make the workflow secure.
The following example is unsafe:
<?php
$filename = $_GET['file'] ?? '';
$command = 'some-tool ' . $filename;
exec($command);
The application gives external input an opportunity to alter a command executed by the operating system.
The preferred response is to remove the shell dependency or redesign the operation around fixed, server-controlled resources.
Sometimes a system utility is genuinely required. In that case:
Use a fixed executable path.
Restrict permitted operations.
Validate every argument against a clear allowlist.
Avoid shell interpretation when the available interface supports argument arrays.
Apply OS-level permissions and process isolation.
Set execution time and resource limits.
Avoid executing uploaded or user-generated scripts.
Record failures without exposing sensitive system details.
PHP’s escapeshellarg() may help quote an individual argument in some shell contexts, but it is not a universal solution. It does not determine whether a command is authorised or safe, and it does not eliminate all platform-specific risks.
Even if a command-injection flaw occurs, the consequences are influenced by the permissions available to the PHP process.
Run the application under a dedicated, unprivileged account. Prevent it from reading unrelated application secrets, modifying system binaries, accessing unnecessary network resources, or changing protected application files.
Isolation and least privilege are important safeguards because no input-validation technique can guarantee that every possible mistake will be avoided.
Server-side request forgery, or SSRF, occurs when an attacker influences a server-side component to make requests to unintended destinations.
A PHP application may be exposed to SSRF if it accepts a URL for importing images, fetching previews, checking remote resources, or calling an external service.
Depending on network access and application privileges, an SSRF vulnerability could expose internal services, reach cloud metadata endpoints, or interact with systems that are not directly accessible from the public internet.
A common mistake is allowing users to submit a URL and then passing it directly to a network client.
URL validation is more complicated than checking whether a string starts with https://. Hostnames may resolve to unexpected addresses, redirects can change destinations, and alternative address formats may bypass simplistic checks.
If a feature only needs to communicate with a small number of known services, maintain an allowlist of permitted destinations.
Validate the scheme, hostname, port, and destination policy. Restrict redirects, and ensure that the final destination is permitted.
For applications that must support arbitrary external websites, implement a dedicated fetching service with strong network isolation rather than giving the main application unrestricted network access.
Network-level controls should prevent public-facing application components from reaching sensitive internal services unless required.
Where cloud infrastructure is involved, follow the provider’s guidance for protecting metadata endpoints and workload credentials. Do not assume that application-level URL checks are sufficient by themselves.
Remote requests should have connection timeouts, total execution limits, response-size limits, and appropriate error handling.
These controls help reduce resource exhaustion caused by slow servers or oversized responses.
Validate downloaded content before passing it to another parser or storing it in the application. A response from an approved hostname is not automatically safe to process.
HTTP security headers allow a server to communicate security policies to browsers. They can reduce certain risks and make the browser enforce restrictions that complement application-level controls.
The correct headers depend on the website’s functionality. A policy that is appropriate for a simple information site may break an application that uses external identity providers, embedded content, or third-party scripts.
CSP restricts the sources from which a browser can load or execute particular resources.
It can help reduce the impact of some XSS vulnerabilities by limiting where scripts and other resources may originate.
Develop a policy based on the application’s actual resource requirements. Use report-only deployment and review violations before enforcing a restrictive policy on a live service.
HTTP Strict Transport Security (HSTS) tells browsers to use HTTPS for a domain for a specified period.
For example:
Strict-Transport-Security: max-age=31536000
Enable HSTS only after confirming that HTTPS works reliably across the domain and all relevant subdomains that would be affected by the policy.
The includeSubDomains directive and preload mechanisms have broader consequences and should be enabled only after careful assessment. Incorrect deployment can make subdomains inaccessible to users.
Clickjacking can occur when a malicious site embeds a legitimate application in a frame and tricks a user into interacting with it.
A CSP directive such as frame-ancestors can restrict which origins may embed the application. For older compatibility requirements, X-Frame-Options may also be appropriate.
Choose a policy that reflects legitimate embedding requirements, especially if the application is designed to appear inside an approved partner portal.
The following header instructs browsers not to perform MIME-type sniffing:
X-Content-Type-Options: nosniff
This can help prevent certain content-type interpretation problems. It should be paired with correct content types and appropriate handling of uploaded files.
A Referrer Policy controls how much referring-page information a browser includes in requests.
For example:
Referrer-Policy: strict-origin-when-cross-origin
This setting can limit the disclosure of full URL paths and query parameters to other origins while retaining useful origin information for cross-origin requests.
Avoid placing secrets or sensitive personal information in URLs. A referrer policy is not a substitute for sound data-handling practices.
Security headers can be set through the web server, reverse proxy, framework middleware, or application response handling.
Prefer a consistent configuration so that individual pages do not accidentally omit important headers. Verify the headers on error pages, redirects, API responses, and authentication pages as well as the homepage.
Avoid sending conflicting policies from multiple layers without understanding which policy the browser will apply.
HTTPS protects data transmitted between a browser and a server by using Transport Layer Security (TLS). It helps prevent network attackers from reading or modifying information in transit and allows the browser to verify the server’s identity.
For websites that handle logins, personal information, customer records, or transactions, HTTPS should be treated as a basic requirement rather than an optional enhancement.
Configure a certificate for every hostname through which the application is intended to be accessed. Monitor certificate expiry and automate renewal where possible.
A valid certificate does not make an application secure by itself. It protects the connection to the intended server, but it does not prevent SQL injection, insecure authorisation, malicious application code, or compromised server credentials.
Configure the web server or trusted reverse proxy to redirect HTTP traffic to the canonical HTTPS URL.
Do not rely exclusively on a redirect generated by an individual PHP page, because requests may reach the server before the application code runs.
When operating behind a reverse proxy, configure trusted proxy handling correctly. Do not trust arbitrary client-supplied forwarding headers to determine whether a request used HTTPS.
Mixed content occurs when an HTTPS page loads certain resources over an insecure HTTP connection.
Review images, scripts, stylesheets, fonts, API requests, and embedded resources. Use HTTPS URLs and verify that external resources are delivered securely.
A secure main document does not guarantee that every resource loaded by the page is secure.
Use modern TLS versions and secure server configurations supported by the deployment environment. Disable obsolete protocols and weak cipher configurations according to current platform guidance.
Review certificate chains, renewal procedures, and hostname coverage. For higher-risk environments, include TLS configuration in regular infrastructure reviews.
HTTPS encrypts request paths and query parameters during transit, but URLs may still appear in browser history, server logs, analytics systems, monitoring tools, or referrer information.
Avoid placing passwords, session tokens, reset credentials, or other sensitive information in query strings. Use appropriate request bodies, secure cookies, and short-lived, purpose-specific tokens where necessary.
PHP applications frequently need credentials for databases, email providers, payment gateways, cloud storage, and external APIs. If these secrets are exposed, an attacker may be able to access connected services even without exploiting the application’s main authentication system.
Avoid embedding production passwords, private keys, or API tokens directly in PHP files.
For example, a database connection should obtain credentials from a protected configuration source rather than from values committed to a public repository.
<?php
$dbHost = getenv('DB_HOST');
$dbName = getenv('DB_NAME');
$dbUser = getenv('DB_USER');
$dbPassword = getenv('DB_PASSWORD');
if (
!$dbHost ||
!$dbName ||
!$dbUser ||
$dbPassword === false
) {
throw new RuntimeException(
'Application configuration is incomplete.'
);
}
This example illustrates environment-based configuration. Environment variables must themselves be supplied and protected securely by the deployment platform. They should not be exposed through debugging endpoints or application responses.
For larger systems, a dedicated secrets manager may provide stronger access controls, auditing, and credential rotation.
Development environments often use .env files to store configuration values. These files should not be publicly accessible.
Keep them outside the public web root where possible, exclude them from version control, and verify that deployment procedures do not copy secrets into public directories.
A source-control ignore rule helps prevent accidental commits, but it does not protect a file that is already tracked or exposed on a server.
If a credential is committed to a repository, included in an exposed backup, or otherwise disclosed, removing it from the latest source code is not enough.
Revoke or rotate the credential, investigate possible use, update dependent services, and review logs for suspicious activity.
The response should account for all copies of the secret, including repository history, build artefacts, developer machines, and deployment systems.
Some information must be recoverable by the application and may therefore require encryption at rest.
Use established cryptographic libraries and authenticated encryption methods appropriate to the use case. Store encryption keys separately from the encrypted data, restrict access to them, and document key rotation and recovery procedures.
Do not invent a custom encryption algorithm or use a static key embedded in publicly accessible application code.
The safest sensitive record is often the one the application does not need to retain.
Review what information is collected, why it is required, who can access it, and how long it should remain available. Delete records securely according to applicable retention requirements and operational needs.
Reducing the amount of stored information can reduce the impact of a successful database compromise.
Database security involves more than preventing injection. Applications must also protect database credentials, limit permissions, control network access, and handle stored information responsibly.
Avoid using a root or administrator account for routine application operations.
Create a database account with the permissions required by the application. Where practical, separate accounts for read-only tasks, background jobs, reporting, and schema migrations.
The account that performs application migrations may require broader permissions than the account that handles ordinary customer requests. Keeping those roles separate reduces the consequences of a compromised web process.
A database used by a PHP application should generally accept connections only from approved application hosts or network segments.
Do not expose database administration services to the public internet unless there is a clearly justified and strongly protected requirement.
Use firewall rules, private network connectivity, and authenticated access. Monitor failed connection attempts and unusual access patterns.
If application and database traffic crosses a network that is not fully trusted, configure TLS for the connection.
Certificate verification is important because encryption without reliable endpoint verification may not protect against an active intermediary.
Follow the database driver’s and provider’s documentation for certificate configuration and secure connection settings.
Backups should be encrypted where appropriate, access-controlled, monitored, and protected from unauthorised modification or deletion.
A backup containing customer records may be as sensitive as the production database itself.
Store copies separately from the primary application environment, and avoid using real production data in development unless a controlled, justified process protects it.
A backup is useful only if it can be restored successfully within an acceptable period.
Schedule restoration tests and document the steps needed to recover the database and application after data loss, accidental deletion, or a security incident.
For higher-risk environments, protect backup credentials separately and consider immutable or otherwise tamper-resistant backup storage.
Error handling influences both security and reliability. Poorly handled errors can expose internal details, hide an attack, or cause an application to continue in an inconsistent state.
The objective is to provide users with understandable messages while retaining sufficient diagnostic information for authorised technical staff.
Development environments benefit from detailed warnings and stack traces. Public production environments generally should not display them to visitors.
A typical production configuration includes:
display_errors = Off
log_errors = On
Additional settings should be reviewed according to the PHP version, framework, and hosting environment.
Do not depend only on application code to hide errors if the PHP runtime or server is configured to display them directly.
Logs can help identify suspicious requests, repeated authentication failures, application exceptions, and unexpected permission changes.
Useful security events may include:
Failed and successful authentication attempts.
Password resets and MFA changes.
Privilege or role changes.
Repeated access-denied responses.
Unexpected file upload failures.
Unusual API activity.
Changes to security-related settings.
Application and dependency errors.
Log enough context to investigate events, but avoid recording passwords, full session identifiers, authentication tokens, or unnecessary personal information.
Logs should be accessible only to authorised personnel and systems. Where feasible, forward important events to a central logging service with appropriate access controls and retention settings.
Consider how an attacker with control of the PHP process might attempt to modify local logs. Centralised logging can help preserve evidence outside the compromised host.
User-controlled values may contain line breaks or other characters that interfere with log formatting. Attackers can exploit this to make events appear misleading or to confuse automated log analysis.
Use structured logging where possible, encode or normalise untrusted values appropriately, and keep log fields separate rather than concatenating arbitrary request data into free-form messages.
A public response should reveal only the information needed to explain what happened and what the user can do next.
For example, a generic server error page is more appropriate than a response containing database credentials, filesystem paths, or internal stack traces.
Assign an incident or correlation identifier when useful so support staff can locate the relevant diagnostic entry without exposing the underlying details to the user.
PHP APIs often provide access to account information, business records, application functionality, and third-party integrations. They require the same core protections as web pages, together with controls suited to automated clients and machine-to-machine communication.
Do not assume that an API endpoint is protected simply because its URL is difficult to guess.
Depending on the architecture, authentication may use secure session cookies, OAuth 2.0 access tokens, or another established mechanism.
For token-based APIs, validate the token’s signature or authenticity, issuer, intended audience, expiry, and relevant permissions as appropriate to the token format.
Do not accept a token merely because it contains a user identifier.
Authentication establishes who is making the request. Authorisation determines what that identity is permitted to do.
A user who can access their own orders should not automatically be able to retrieve another customer’s orders by changing an identifier.
For each API operation, check the user’s role, ownership, tenant membership, or other relevant permission. Perform these checks on the server even when the frontend hides inaccessible actions.
Validate JSON structures, data types, required fields, and allowed values before processing a request.
Reject malformed payloads and unsupported content types. Limit request sizes to prevent excessive memory consumption.
Avoid trusting client-supplied role names, prices, account balances, payment states, or ownership fields. Derive sensitive values from trusted server-side records and authorised operations.
APIs may be called automatically and at high frequency. Without rate limits, a single client or distributed set of clients may consume excessive resources or repeatedly attempt sensitive operations.
Set limits according to endpoint risk. Login, password reset, search, document generation, and expensive reporting operations may require different thresholds.
For authenticated APIs, consider per-user or per-client limits in addition to network-based limits. Return appropriate status codes and retry guidance when limits are exceeded.
Webhooks allow external services to notify an application about events such as payments, orders, and account changes.
A secure webhook handler should verify the sender using the provider’s documented signature mechanism or another trusted authentication method. If signatures cover the raw request body, preserve the exact body required by the verification process.
Also consider timestamps, replay protection, event identifiers, idempotency, and duplicate delivery. A valid signature does not automatically guarantee that an event is current or that it should be applied twice.
Return only the fields a client needs.
An endpoint that returns an entire database record may accidentally expose internal notes, account identifiers, permissions, or other sensitive fields.
Define response structures explicitly and review them when data models change. This reduces accidental information disclosure and makes API behaviour easier to maintain.
Secure PHP code can still be undermined by a poorly configured runtime. Production settings should reflect the application’s actual requirements and be reviewed after PHP upgrades or infrastructure changes.
The following table lists several configuration settings worth reviewing.
| Setting | Security consideration |
|---|---|
display_errors |
Disable public error display in production |
log_errors |
Enable appropriate error logging |
expose_php |
Consider disabling unnecessary PHP version disclosure |
allow_url_include |
Keep disabled unless a justified requirement exists |
session.use_strict_mode |
Enable strict session ID handling |
session.use_only_cookies |
Avoid URL-based session identifiers |
file_uploads |
Disable if the application never needs uploads |
upload_max_filesize |
Set an appropriate per-file limit |
post_max_size |
Restrict total request body size |
max_execution_time |
Set reasonable limits for ordinary requests |
memory_limit |
Limit memory consumption according to workload |
These settings are not a universal configuration file. Some values depend on framework behaviour, background jobs, upload requirements, and the hosting platform.
PHP settings may differ between the command-line interface and the web runtime. PHP-FPM pools, Apache modules, container images, hosting panels, and application bootstrap code can also affect effective configuration.
Check the configuration actually used by the production web application. Do not leave a publicly accessible phpinfo() page on a production server, because it can reveal environment details.
The open_basedir setting can limit the directories PHP is allowed to access in supported configurations. It may provide an additional boundary in some deployments, but it is not a complete security sandbox and should not replace operating system permissions or application-level access controls.
Likewise, disable_functions may reduce exposure to particular functions but is not a substitute for safe coding, process isolation, or least privilege.
Avoid relying on a long list of configuration restrictions as the only defence against application compromise.
Development environments may require debugging tools, test credentials, verbose logs, or additional packages.
Production environments should not expose these tools or use development secrets.
Use separate configuration, credentials, access policies, and deployment procedures. Ensure that development-only endpoints, test accounts, debugging routes, and temporary scripts are removed or disabled before release.
Resource exhaustion can occur through oversized requests, expensive regular expressions, large data exports, or operations that consume excessive CPU or memory.
Set appropriate limits for request size, execution time, memory usage, upload size, and background processing. Consider queues for expensive operations that do not need to finish during a single web request.
Resource limits should be combined with monitoring and rate limiting rather than treated as complete protection against denial-of-service attacks.
Automated attacks often target login pages, registration forms, password recovery, search endpoints, and public APIs. A secure PHP application should distinguish normal usage from suspicious patterns without unnecessarily blocking legitimate customers.
Rate limits can be applied at several levels:
Web application endpoints.
API gateways or reverse proxies.
Web application firewalls.
Authentication services.
Infrastructure-level network controls.
Use the layers that fit the architecture. For example, infrastructure-level limits can reduce traffic reaching PHP, while application-level controls can apply rules based on account identity and operation type.
After repeated failed authentication attempts, the application can introduce increasing delays, temporary restrictions, or additional verification.
Ensure that the controls do not create an easy denial-of-service mechanism against known users. Account-level restrictions should be designed carefully, especially where attackers can submit requests using someone else’s email address.
Credential stuffing uses username and password combinations exposed in previous breaches.
Mitigations include MFA, compromised-password screening, rate limiting, anomaly detection, and alerts for unusual authentication patterns.
A login from a new location is not automatically malicious, and a familiar IP address is not proof of legitimacy. Use multiple signals rather than a single simplistic rule.
Registration, contact, review, and enquiry forms may attract spam or automated submissions.
Possible controls include rate limits, honeypot fields, reputation checks, and accessible challenge mechanisms where appropriate. CAPTCHA-style challenges can help in some situations but may introduce accessibility and usability problems.
Do not depend on hidden form fields or JavaScript-only checks as the sole protection. Attackers can submit requests directly to the server.
Download functionality can expose private information when the application trusts a client-supplied filename or fails to verify ownership.
A secure download workflow should identify the requested record, authorise access, resolve its storage location, and return the correct content with suitable response headers.
A document identifier is not a permission.
If a customer requests an invoice, verify that the invoice belongs to the authenticated customer or that the user has another legitimate permission to access it.
Administrative privileges, delegated access, and tenant-level permissions should be checked according to the application’s rules.
For files that should be downloaded rather than displayed, use an appropriate Content-Disposition header.
Content-Disposition: attachment; filename="document.pdf"
When filenames contain non-ASCII characters or special characters, follow established HTTP header formatting rules rather than inserting raw user input into the header.
For untrusted documents, consider serving them from a separate origin and preventing active content from executing in the context of the main application.
Return the correct content type for known file formats. Avoid trusting a client-supplied MIME type when deciding how a file should be served.
For uncertain or potentially dangerous content, a conservative content type and attachment disposition may reduce browser interpretation risks.
Signed or time-limited download links can be useful for controlled access. Generate them with secure randomness or a suitable cryptographic signature, restrict their lifetime, and bind them to the intended resource and permissions where appropriate.
Remember that a bearer link can be used by anyone who obtains it while it remains valid. Avoid exposing sensitive links through logs, analytics, or public pages.
The principle of least privilege means that every user, process, service, and component receives only the permissions necessary to perform its assigned tasks.
This principle limits the impact of both accidental mistakes and successful attacks.
The PHP process should generally be able to read the application code and write only to designated directories, such as logs, temporary storage, and required upload locations.
Avoid giving the web application broad access to system files, deployment credentials, unrelated projects, or administrative tools.
An application may have ordinary customers, support staff, content editors, finance users, and administrators.
These roles should not automatically share the same permissions. Define what each role can view, create, modify, export, and delete.
For particularly sensitive operations, require explicit permission checks rather than assuming that a general administrative role is sufficient.
Background jobs, reporting tools, payment integrations, and public-facing endpoints may require different capabilities.
Where practical, use separate credentials and service identities so that compromising one component does not provide unrestricted access to every connected system.
Rotate credentials when personnel, responsibilities, or infrastructure change.
Permissions can accumulate over time as teams and applications evolve.
Review administrator accounts, API tokens, database grants, service identities, and file access. Remove unnecessary access promptly, particularly when employees leave or services are retired.
Secure code is easier to review, test, and maintain when the application follows consistent conventions. Ad hoc security checks scattered throughout an application make it harder to establish whether every endpoint has the required protections.
A maintainable PHP application often separates request handling, validation, business logic, data access, and response rendering.
This separation helps developers identify where security decisions belong.
For example, a controller may validate the request and authenticate the user, a service may enforce a business operation, and a repository may execute parameterised database queries.
The exact architecture can vary. What matters is that critical protections remain explicit, testable, and difficult to bypass.
Frameworks such as Laravel and Symfony provide tools for routing, validation, database access, authentication, sessions, and other common application tasks.
Using a framework can reduce the need to implement security-sensitive functionality from scratch. However, the framework’s protections work only when configured and used correctly.
Developers should understand when middleware runs, how authentication guards operate, whether templates escape output by default, and how authorisation policies are applied.
Features that bypass normal framework abstractions deserve careful review. Examples include raw SQL queries, direct response output, manual cookie handling, shell commands, custom token validation, and dynamic file operations.
These operations are not automatically insecure, but they may bypass protections that developers otherwise rely on.
Peer review can identify assumptions that automated tests may miss.
Pay particular attention to changes involving authentication, authorisation, payment processing, uploads, imports, database queries, secrets, and access to external systems.
Reviewers should ask not only whether the code works as intended, but also what happens when inputs are malformed, permissions are missing, dependencies fail, or requests are repeated.
Static analysis tools can identify suspicious patterns without requiring the application to be running.
Depending on the tool and project, they may detect unsafe SQL construction, questionable input handling, type errors, insecure function usage, and other coding issues.
Static analysis can produce false positives and miss vulnerabilities that depend on runtime behaviour. Treat its output as one part of a broader security review.
Not every serious security issue is caused by a technical vulnerability such as SQL injection. Some arise because an application allows a user to perform a valid operation in an invalid way.
These weaknesses are often called business logic vulnerabilities.
An e-commerce application should not accept the final order price as authoritative merely because the browser submitted it.
The server should calculate prices using trusted product records, applicable discounts, taxes, shipping rules, and the current order state.
A customer may submit a modified request containing a different price or discount identifier. The application must determine whether that discount is valid for the account, product, quantity, and order.
An attacker or malfunctioning client may submit the same payment or order request several times.
Use transaction identifiers, idempotency mechanisms, database constraints, and carefully designed state transitions to prevent duplicate processing.
The appropriate mechanism depends on the payment provider and application architecture. Do not assume that disabling a button in the browser prevents repeated requests.
An order might move from pending to paid, fulfilled, cancelled, or refunded. Not every transition should be permitted from every state.
Enforce valid transitions on the server. A client should not be able to mark an unpaid order as fulfilled merely by submitting a different status value.
Keep authoritative state changes within trusted application logic and verify external events before acting on them.
Mass assignment occurs when an application copies request fields directly into an object or database record without restricting which properties the user may change.
For example, a profile update endpoint should not allow a customer to change their role, account status, or permission flags by including extra fields in the request.
Use explicit field allowlists, framework-specific guarded properties, and dedicated request models. Enforce sensitive changes through separate authorised operations.
Two simultaneous requests can sometimes exploit timing gaps in an application’s logic.
For example, two requests may attempt to redeem the same voucher before either transaction records that it has been used.
Use appropriate database transactions, unique constraints, locking, and atomic updates for operations that require consistency.
Security testing should include repeated and concurrent requests where the business operation involves money, limited inventory, quotas, or one-time actions.
E-commerce applications handle valuable data and transactions, making security controls especially important.
A PHP-based store should protect customer accounts, order information, payment workflows, administrative access, and the integrity of pricing and fulfilment decisions.
Whenever possible, use a reputable payment provider’s supported integration rather than designing a payment processing system from scratch.
Follow the provider’s current integration documentation and security requirements. Keep secret API keys on the server and use restricted credentials for the required environment.
A hosted checkout or tokenised payment flow can reduce the amount of sensitive payment data handled directly by the PHP application, although the applicable compliance obligations still depend on the complete setup.
Do not treat a browser redirect to a success page as proof that a payment succeeded.
The server should verify the payment through the provider’s trusted API or authenticated webhook mechanism. Validate the transaction reference, expected amount, currency, order association, and relevant payment state.
Handle duplicate and out-of-order notifications safely. A payment event should not be allowed to change an unrelated order.
Store administrators may be able to refund transactions, change product prices, access customer information, and alter fulfilment settings.
Require strong authentication, appropriate role separation, and audit logs for sensitive actions.
Where the risk justifies it, require reauthentication or additional approval before large refunds, bulk exports, or changes to payment settings.
Do not retain sensitive payment data unless there is a clear, lawful, and appropriately protected reason to do so.
Use provider-managed tokens and approved payment methods where possible. Follow the applicable payment industry standards and provider requirements for the chosen integration.
Security and reliability testing should include declined payments, timeouts, repeated submissions, invalid signatures, duplicate notifications, refunds, and interrupted checkout flows.
Verify that order status remains correct when the application or payment provider experiences a temporary failure.
Content management systems such as WordPress use PHP extensively and have their own security considerations. Their risk profile depends on the core software, installed plugins, themes, configuration, user permissions, and hosting environment.
Update supported CMS releases and third-party components promptly after assessing compatibility and risk.
Remove unused themes and plugins rather than leaving them installed indefinitely. An inactive component may still create risk if vulnerable files or accessible functionality remain on the server.
Before making changes to an important production site, maintain tested backups and use a staging environment when practical.
Review whether a component is actively maintained, whether security updates are provided, and whether its developer publishes relevant support information.
Avoid relying on modified or unauthorised distributions of premium plugins and themes. Such packages may contain malicious code or lack the expected update mechanisms.
Review plugin permissions and functionality before installation, especially for components that process uploads, manage users, or integrate with payment systems.
Use unique administrator credentials, MFA where available, and appropriate role assignments.
Content editors rarely need unrestricted access to every site setting. Separate publishing permissions from user management, plugin installation, and server-level operations.
Restrict access to configuration files and sensitive directories. Avoid writable permissions across the entire application when only a small number of directories need write access.
Review backup files, database exports, debugging endpoints, and source-control metadata to ensure that they cannot be downloaded publicly.
CMS security features do not automatically protect custom code. Developers should continue to validate input, use safe database APIs, escape output, verify permissions, and implement nonce or CSRF protections according to the platform’s conventions.
For WordPress development, use the official WordPress Developer Resources and security documentation for the relevant APIs rather than relying on assumptions about how a function behaves.
Composer is widely used to manage PHP dependencies. Its configuration and package lifecycle affect the security of the resulting application.
For an application, commit composer.lock so that deployments use the dependency versions that were tested.
Without a lock file, dependency resolution may select different versions at different times, potentially changing application behaviour or introducing unexpected incompatibilities.
Libraries intended for reuse may have different repository practices, but deployable applications generally benefit from reproducible dependency resolution.
Run dependency security checks during development and deployment.
composer audit
Review the findings, identify whether affected packages are present in the deployed application, and determine the appropriate upgrade or mitigation.
A clean audit does not prove that every package is secure. Advisories may not yet exist for a vulnerability, and custom application code is outside the scope of a dependency-only check.
Package installation can execute scripts and interact with the filesystem. Run dependency management with an appropriately restricted account and understand which package scripts execute during installation.
Do not install unknown packages solely because they appear in a search result. Review package provenance, maintenance status, source code where appropriate, and the permissions the package will have in the application.
Tools used exclusively for testing, static analysis, or development may not need to be present in the production environment.
Where appropriate, use Composer’s production installation options and a tested build process to exclude development dependencies.
Ensure that the resulting application still has every runtime dependency it requires.
Dependencies may be compromised through malicious releases, stolen maintainer credentials, or unauthorised package changes.
Reduce exposure by limiting unnecessary dependencies, reviewing changes, protecting build credentials, and using trusted package sources.
For higher-risk applications, consider dependency provenance controls, reproducible builds, and restricted network access during production deployment.
Security testing helps identify weaknesses before attackers discover them. It should be performed during development, before major releases, and periodically after deployment.
No single tool can identify every vulnerability. A reliable testing programme combines automated scanning, code review, configuration checks, dependency analysis, and manual testing of important workflows.
Static application security testing (SAST) examines source code without executing the application.
Depending on the tool, SAST can identify:
Potential SQL injection paths.
Unsafe command execution.
Insecure file inclusion.
Weak cryptographic practices.
Hardcoded credentials.
Unvalidated input flows.
Dangerous deserialisation patterns.
Certain authentication and authorisation mistakes.
Static analysis is particularly useful when integrated into a development workflow, because developers can investigate findings close to the time the code was written.
However, a tool may flag safe code or fail to recognise a vulnerability that depends on application-specific logic. Review findings rather than assuming every alert is exploitable or every clean result is conclusive.
Dynamic application security testing (DAST) evaluates a running application by sending requests and examining its responses.
Depending on its capabilities and configuration, a scanner may identify exposed endpoints, reflected XSS, insecure headers, authentication weaknesses, or other detectable issues.
Test a staging environment whenever possible. Scans against production systems should be authorised, appropriately scoped, and configured to avoid destructive actions or excessive traffic.
A scanner cannot reliably determine whether every user can access every record they should be denied. Those questions often require application-specific tests.
Review the security of the full deployment, not just PHP source files.
Include:
PHP runtime and extensions.
Composer dependencies.
Framework and CMS versions.
Web server configuration.
Database permissions.
TLS settings.
Container images and operating system packages.
Publicly accessible administrative interfaces.
Backup and storage permissions.
Infrastructure scanning and application testing cover different risks. Use both when appropriate.
Manual testing is important for vulnerabilities that depend on business rules.
Create test accounts with different permissions and verify that each account can access only the intended resources.
For example, test whether a customer can:
Read another customer’s invoice.
Change another user’s account settings.
Access administrative endpoints.
Reuse an expired password reset token.
Continue using a session after logout or revocation.
Modify a sensitive record by changing request fields.
Perform a restricted action through a direct API call.
These tests should verify the server’s response rather than relying on what the user interface displays.
Penetration testing evaluates an application from an attacker’s perspective within an agreed scope.
A qualified tester may examine injection flaws, access control, authentication, session handling, business logic, file uploads, API security, and deployment weaknesses.
Define the permitted targets, test accounts, timing, data-handling rules, and reporting process before testing begins.
After receiving the findings, prioritise remediation by risk, confirm fixes through retesting, and document any remaining accepted risks.
A security assessment reflects the application at a particular point in time. New features, plugins, dependencies, and infrastructure changes can introduce fresh vulnerabilities.
Repeat relevant tests after major releases, significant architectural changes, or high-risk dependency updates.
For continuous delivery environments, automate appropriate tests so that security checks remain part of normal development rather than an occasional separate activity.
Secure development works best when security is included in planning, implementation, testing, deployment, and maintenance.
Treating security as a final checklist can leave fundamental weaknesses embedded in the architecture. Integrating it earlier makes vulnerabilities easier to prevent and less expensive to correct.
Before building a feature, identify the information it handles, the actions it permits, and the threats it introduces.
For a document-sharing feature, requirements might include:
Only authorised users can upload documents.
Files must meet size and format restrictions.
Stored files must not execute as scripts.
Users can access only documents they are permitted to view.
Download links must have defined access and expiry rules.
Sensitive events must be logged.
The feature must remain within defined resource limits.
These requirements provide clear criteria for development and testing.
A feature should not be considered complete solely because its normal user journey works.
Acceptance criteria should also cover invalid input, missing permissions, expired sessions, repeated requests, and dependency failures where relevant.
For example, an account update feature should confirm that the correct user can make a permitted change and that another user cannot make the same change by modifying the request.
Source repositories and deployment pipelines may contain code, configuration, package metadata, and credentials that affect production systems.
Require appropriate access controls, review sensitive changes, protect release branches where necessary, and use dedicated deployment identities.
Avoid granting every developer unrestricted production access when a controlled release mechanism can provide the required functionality with less risk.
Useful automated checks include:
Composer dependency audits.
Static analysis.
Unit and integration tests.
Secret scanning.
Infrastructure configuration checks.
Appropriate application security scans.
Tests for important authorisation rules.
Automation improves consistency, but high-risk findings should not be ignored simply because a pipeline can be configured to pass.
Establish a process for reviewing exceptions and tracking remediation deadlines.
A security report should explain the affected component, the potential impact, the conditions required for exploitation, and the recommended remediation.
Assign an owner and target date to significant findings. After a fix is deployed, verify that the original weakness is no longer present and that the change has not introduced another problem.
A documented process makes security improvement measurable and helps prevent recurring vulnerabilities.
Preventive controls reduce risk, but no application can assume that every attack will be blocked. Monitoring and incident response are necessary to identify suspicious activity and recover safely.
Collect relevant application, web server, authentication, infrastructure, and database events.
Examples of suspicious activity include unusual login failure patterns, unexpected administrator changes, repeated access-denied responses, unexplained file modifications, and abnormal outbound network requests.
Establish thresholds and alerting rules that reflect the application’s normal behaviour. Too many irrelevant alerts can cause important events to be overlooked.
Monitoring systems often have broad access to logs and operational information.
Use dedicated identities, restrict permissions, protect API tokens, and avoid exposing monitoring dashboards publicly.
Security monitoring should not create a new path into the production environment.
A useful response plan identifies who is responsible for investigation, containment, recovery, communication, and post-incident review.
It should cover scenarios such as compromised administrator accounts, leaked credentials, suspected data exposure, malicious file uploads, and vulnerable dependencies.
Document how to contact the relevant personnel and providers when ordinary systems are unavailable.
The immediate response depends on the incident, but may involve:
Confirming the affected systems and the available evidence.
Restricting suspicious access or isolating compromised components.
Preserving relevant logs and forensic evidence.
Revoking exposed credentials and sessions.
Identifying the entry point and extent of the compromise.
Applying fixes and removing unauthorised changes.
Restoring from trusted backups where necessary.
Monitoring the recovered environment for recurring activity.
Avoid deleting evidence or restoring an infected backup without understanding the incident. A rushed recovery may reintroduce the same vulnerability or allow the attacker to regain access.
If personal information or other regulated data may have been exposed, determine which legal, contractual, and regulatory notification requirements apply.
Requirements vary by jurisdiction, data type, organisation, and incident circumstances. Seek appropriate legal and incident-response advice rather than assuming that one notification rule applies to every situation.
After containment and recovery, identify the technical and organisational factors that allowed the incident to occur.
Review whether the application had missing patches, weak access controls, insufficient monitoring, inadequate backups, or unclear operational responsibilities.
Use the findings to improve controls and testing. The objective is not merely to restore service but to reduce the likelihood and impact of a similar incident in the future.
Even experienced developers can introduce vulnerabilities when deadlines are tight or security requirements are unclear. The following mistakes deserve particular attention during code review.
Browser validation improves usability, but attackers can bypass it by submitting requests directly.
Always enforce critical validation rules on the server.
Manual escaping is not a dependable replacement for parameterised SQL queries.
Use prepared statements for SQL values and a fixed allowlist for dynamic SQL identifiers.
A valid login does not automatically grant access to every record or operation.
Check permissions on every protected endpoint and resource.
Plaintext password storage exposes credentials immediately if the database is compromised.
Use PHP’s password hashing and verification functions.
Stack traces and database errors may disclose information useful to attackers.
Disable public error display in production and use controlled logging.
Unused components increase maintenance obligations and may contain exploitable weaknesses.
Remove components that are no longer needed and keep the remaining dependencies supported.
Session identifiers, reset tokens, and security tokens should not be based on timestamps, sequential numbers, or other predictable values.
Use cryptographically secure randomness or an established cryptographic mechanism appropriate to the token’s purpose.
A web application firewall can block some suspicious traffic, but it cannot reliably correct every underlying coding flaw.
Fix vulnerabilities in the application and use perimeter controls as an additional layer.
Broad filesystem permissions increase the damage possible after a compromise.
Give the PHP process write access only to the directories and resources it genuinely needs.
HTTPS protects data in transit. It does not prevent application logic errors, insecure access control, stolen credentials, or malicious code executing within the application.
Combine TLS with secure coding, authentication, authorisation, and monitoring.
Backups can contain complete copies of customer information and configuration secrets.
Restrict access, protect backup integrity, and test restoration procedures.
A one-off security scan cannot protect an application indefinitely.
Maintain dependencies, review changes, monitor activity, and retest important security boundaries over time.
A practical checklist helps teams translate security recommendations into repeatable development and maintenance tasks. Use the following checklist during code reviews, pre-deployment assessments, and periodic security audits.
This checklist is a starting point, not a security certification. Additional controls may be required for payment systems, healthcare applications, enterprise platforms, and other high-risk environments.
The most important PHP security best practices include using prepared SQL statements, validating all untrusted input, encoding output appropriately, storing passwords with secure password hashing, implementing strong authentication, protecting sessions, restricting file uploads, and enforcing server-side authorisation.
Developers should also maintain supported PHP versions, audit third-party dependencies, protect application secrets, use HTTPS, and monitor suspicious activity.
The appropriate priorities depend on the application’s exposure and the consequences of a compromise. A public login system, for example, requires particular attention to authentication, session management, and account recovery.
Yes. PHP can be used to build secure websites and applications when developers follow appropriate security practices and maintain the underlying software.
The security of an application depends on its code, dependencies, configuration, architecture, deployment, and maintenance. The programming language alone does not determine whether a website is secure.
Modern PHP releases provide useful security capabilities, and established frameworks offer tools for common security requirements. Developers must still configure these tools correctly and address application-specific risks.
Use prepared statements with PDO or MySQLi rather than concatenating user input into SQL queries.
For example:
$stmt = $pdo->prepare(
'SELECT id, email FROM users WHERE email = :email'
);
$stmt->execute(['email' => $email]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
Prepared statements separate SQL structure from parameter values. For dynamic column names and sorting options, use a strict allowlist because SQL identifiers generally cannot be handled as ordinary value parameters.
Also restrict database permissions and review all database access paths.
Start by updating PHP and its dependencies, identifying exposed endpoints, reviewing authentication and access control, and checking how the application handles untrusted input.
Use HTTPS, secure cookies, prepared statements, output encoding, CSRF protection, restricted filesystem permissions, and protected configuration files.
Then introduce security testing, centralised logging, backups, and an incident response process. No single measure can guarantee that a website will never be compromised, so security should be maintained continuously.
Several built-in PHP functions support common security tasks.
| Function | Purpose |
|---|---|
password_hash() |
Creates a password hash |
password_verify() |
Verifies a submitted password |
password_needs_rehash() |
Checks whether a password hash needs updating |
random_bytes() |
Generates cryptographically secure random bytes |
random_int() |
Generates cryptographically secure random integers |
hash_equals() |
Compares strings in a timing-resistant manner |
htmlspecialchars() |
Encodes special characters for appropriate HTML contexts |
filter_var() |
Performs validation or filtering according to the selected filter |
hash_hmac() |
Generates a keyed message authentication code |
json_encode() |
Serialises PHP values into JSON |
is_uploaded_file() |
Checks whether a path refers to an HTTP-uploaded file |
move_uploaded_file() |
Moves an uploaded file to a destination |
These functions are useful building blocks, not complete security solutions. Their effectiveness depends on correct usage and the surrounding application design.
Laravel and Symfony both provide established tools for building PHP applications, including routing, validation, database access, and authentication-related functionality.
The best choice depends on the project, developer expertise, existing architecture, maintenance requirements, and available integrations.
A framework can help reduce common implementation mistakes, but neither framework makes an application automatically secure. Developers must understand its security features, follow recommended practices, keep dependencies updated, and test access control and business logic.
No. Input sanitisation alone is insufficient because different operations require different protections.
SQL injection prevention relies primarily on parameterised queries. XSS prevention requires context-appropriate output encoding or carefully controlled HTML sanitisation. File uploads require content validation and safe storage. Access control requires server-side permission checks.
Use validation to enforce acceptable input rules, then apply the appropriate security control for each operation.
Define an allowlist of permitted file types, check upload errors, enforce size limits, inspect file content, and generate server-controlled storage names.
Store files outside executable public directories whenever possible. Apply restrictive filesystem permissions, scan or reprocess content when appropriate, and serve private files through authorised download endpoints.
For archives and complex document formats, also account for path traversal, decompression attacks, and vulnerabilities in processing libraries.
Use htmlspecialchars() for ordinary HTML text and appropriate quoted HTML attribute contexts. Use JSON encoding for structured data passed to JavaScript, and avoid constructing executable JavaScript from untrusted input.
If users are allowed to submit HTML, use a maintained sanitisation library with a restrictive allowlist.
A Content Security Policy can provide additional protection, but it should complement, not replace, safe output handling.
Use secure session cookie settings, enable strict session handling, regenerate session identifiers after authentication, enforce session timeouts, and invalidate sessions when users log out.
For HTTPS applications, configure the Secure and HttpOnly cookie attributes and choose an appropriate SameSite policy.
Protect server-side session storage and implement revocation procedures for compromised accounts. Consider reauthentication for high-risk actions.
The frequency depends on the application’s risk, release schedule, and regulatory obligations.
Dependency audits and automated checks can run during development and deployment. Manual security reviews should accompany significant changes to authentication, authorisation, payments, uploads, and external integrations.
Higher-risk applications may also require periodic penetration testing and independent assessments. Retest vulnerabilities after remediation to confirm that the fixes work as intended.
No. Security plugins and web application firewalls can block some malicious requests and provide useful monitoring, but they cannot reliably eliminate every application vulnerability.
They may not detect an authorisation flaw, an incorrect transaction state, or a vulnerable workflow that appears legitimate at the HTTP level.
Use these tools as additional layers alongside secure coding, timely updates, least-privilege permissions, and application-level testing.
Begin by identifying the PHP version, framework, dependencies, server configuration, and critical application features.
Determine whether the current runtime and components still receive security updates. Plan a controlled upgrade if they are unsupported, and test compatibility in a staging environment.
Review database queries, file operations, authentication, sessions, access control, and error handling. Remove unused components, protect secrets, create tested backups, and prioritise remediation based on risk.
For a legacy application, a staged migration may be safer than attempting a complete rewrite without adequate testing.
Authentication verifies identity. Authorisation determines what an authenticated identity is permitted to do.
For example, a customer may successfully log in but should only be allowed to view their own invoices. The application must authenticate the customer and separately verify permission to access each invoice.
Both controls are necessary. Strong authentication cannot compensate for missing authorisation checks.
No. HTTPS protects information in transit and helps browsers establish a secure connection to the intended server.
SQL injection is addressed through safe database query construction. XSS requires appropriate output handling and other browser-side protections.
HTTPS is essential, but it is only one component of a secure application.
Avoid hardcoding secrets in source code or committing them to version control. Use protected environment configuration or a dedicated secrets manager, depending on the deployment environment.
Restrict which processes can access each credential, rotate exposed secrets, and audit their use where possible.
Do not include secrets in error messages, application logs, public configuration files, or client-side JavaScript.
Begin with a risk-based assessment and address the most important weaknesses first.
Patching unsupported or vulnerable components, fixing unsafe SQL queries, improving authentication, enforcing authorisation, protecting uploads, and correcting production configuration can provide significant improvements without requiring a complete rewrite.
Introduce automated testing and make security improvements incrementally. For legacy applications, isolate especially risky components and create a realistic upgrade plan.
Protecting a PHP website from vulnerabilities and cyber attacks requires a combination of secure coding, sound architecture, careful configuration, and continuous maintenance.
The most effective approach begins with a few fundamental principles: treat external input as untrusted, separate data from executable instructions, enforce permissions on the server, protect authentication credentials, manage sessions securely, and restrict access to files, databases, and application secrets.
Developers should also maintain supported software versions, review Composer dependencies, enforce HTTPS, configure safe production error handling, and test the application regularly. File uploads, API endpoints, password recovery, payment processing, and administrative functions deserve particular attention because mistakes in these areas can have serious consequences.
Security testing should extend beyond automated scanners. Manual reviews of access control, business logic, transaction handling, and account recovery help identify problems that generic tools may overlook. Logging, monitoring, protected backups, and a documented incident response plan then provide the ability to detect and recover from incidents that preventive controls do not stop.
Most importantly, PHP security is not a one-time implementation task. Applications change, dependencies evolve, and new threats emerge. A sustainable process combines ongoing risk assessment, timely remediation, repeatable testing, and clear operational responsibility.
By applying these PHP security best practices consistently, development teams can reduce avoidable vulnerabilities, protect sensitive information, improve application reliability, and build a stronger foundation for long-term website security.