Securing PHP Applications in the Age of AI-Generated Code

AI assistants write PHP quickly, but they can also reintroduce old security mistakes. Learn the common flaws, a review checklist, Composer audit and static analysis with PHPStan or Psalm.

AI coding assistants have made it easy to produce working PHP in seconds: a login form, a search page, a file upload handler. The trouble is that "working" and "secure" are different things. Language models learn from enormous amounts of public code, and a lot of public PHP code was written years ago, before many of today's safer practices became standard. When an assistant suggests code, it can confidently reproduce those old patterns.

For businesses running PHP applications, whether a custom portal, a WordPress site with custom plugins, or a Laravel or CodeIgniter system, this matters directly. A single SQL injection or cross-site scripting flaw can expose customer records, and under India's DPDP Act 2023 the organisation handling personal data is responsible for protecting it. This article covers the flaws AI suggestions most often introduce and a practical process for catching them.

Common flaws in AI-suggested PHP

These problems appear repeatedly when reviewing generated code:

  • SQL built by string concatenation. Variables from $_GET or $_POST dropped straight into a query string.
  • Missing output escaping. User input echoed back into HTML without htmlspecialchars(), leading to cross-site scripting.
  • Weak or absent validation. Trusting that an ID is an integer, an email is valid, or an uploaded file is really an image because of its extension.
  • Outdated functions and packages. Suggestions using the removed mysql_* functions, md5() or sha1() for passwords, or old versions of libraries with known vulnerabilities.
  • Missing CSRF protection on forms that change data.
  • Hard-coded secrets such as database passwords or API keys placed directly in example code that then gets committed.
  • Verbose error output with display_errors turned on, leaking file paths and query details to visitors.
  • Insecure file handling, such as saving uploads with the original filename inside the web root.

None of these are new. What has changed is the speed at which they can enter a codebase when developers accept suggestions without reading them closely.

Before and after: prepared statements with PDO

SQL injection remains one of the most damaging flaws, and it is easy to fix. Here is a typical generated snippet, followed by a safer version:

// Before: vulnerable to SQL injection
$email = $_POST['email'];
$sql = "SELECT id, name FROM customers WHERE email = '$email'";
$result = $pdo->query($sql);
$customer = $result->fetch();

// After: validated input and a prepared statement
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if ($email === false || $email === null) {
    http_response_code(422);
    exit('Please enter a valid email address.');
}

$stmt = $pdo->prepare('SELECT id, name FROM customers WHERE email = :email');
$stmt->execute(['email' => $email]);
$customer = $stmt->fetch(PDO::FETCH_ASSOC);

if ($customer) {
    echo htmlspecialchars($customer['name'], ENT_QUOTES, 'UTF-8');
}

Three things changed. The input is validated before use. The query uses a placeholder, so the database treats the value as data rather than SQL. The output is escaped before it reaches the browser. Also make sure your PDO connection sets PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION and, for MySQL, consider setting PDO::ATTR_EMULATE_PREPARES to false so native prepared statements are used. Note that placeholders cannot be used for table or column names; if those must vary, check them against a fixed allow-list.

If you use a framework, prefer its query builder or ORM, which use parameter binding by default, and be especially careful with "raw" methods such as DB::raw() or whereRaw(), where the same injection risk returns.

A review checklist for AI-generated PHP

Use this list when reviewing any pull request that contains generated code:

  1. Are all database queries parameterised, with no user input concatenated into SQL?
  2. Is every piece of user-controlled data escaped for the context it is output in: HTML, HTML attribute, JavaScript or URL?
  3. Is input validated for type, length, format and allowed values on the server, not only in the browser?
  4. Are passwords hashed with password_hash() and checked with password_verify()?
  5. Do forms that change data include CSRF tokens, and do sensitive actions check that the user is authorised, not just logged in?
  6. Are file uploads checked by content type and size, renamed, and stored outside the web root or in a non-executable location?
  7. Are secrets loaded from environment variables or a secrets store, never hard-coded?
  8. Are errors logged rather than displayed in production?
  9. Does the code call any function or package that does not exist or is deprecated? Assistants sometimes invent plausible-looking ones.
  10. Can the author explain what every line does?

Keep dependencies current with Composer audit

AI tools may suggest installing a package version they saw often in training data, which can be old. Composer includes an audit command that checks your installed packages against known security advisories:

composer audit
composer outdated --direct

Run composer audit in your CI pipeline so a build fails or warns when a dependency has a known vulnerability. Commit composer.lock so every environment installs the same versions, review updates regularly rather than in a panic, and remove packages you no longer use. Also keep PHP itself on a version that still receives security fixes; running an end-of-life PHP version means newly discovered flaws will not be patched.

Static analysis with PHPStan and Psalm

Static analysers read your code without running it and report likely errors. They catch many problems that generated code introduces, such as calling methods that do not exist, passing the wrong types, or ignoring a possible null.

  • PHPStan works through rule levels, so you can start at a low level on an existing project and raise it over time. Framework extensions, such as Larastan for Laravel, help it understand framework-specific code.
  • Psalm offers similar type checking and also includes taint analysis, run with --taint-analysis, which traces user input to dangerous sinks such as SQL queries and HTML output.

Either tool is a good choice; what matters is running it automatically on every pull request. Add a baseline for existing issues so the team is not overwhelmed, and require that new code introduces no new errors. Combine this with a coding standard checker and your normal test suite for a layered defence.

Building a secure workflow around AI

Security is easier to maintain when it is part of the process rather than a final check. Agree as a team that AI suggestions are drafts, that generated code goes through the same review and CI checks as anything else, and that no production data or secrets are pasted into external AI tools. Give developers short, regular security training focused on the flaws listed above. Over time, these habits make AI a productivity aid rather than a new source of vulnerabilities.

How NextWebGen can help

NextWebGen develops and maintains PHP applications, and we can review existing code, set up Composer audits and static analysis in your pipeline, and fix the issues found. If you are concerned about the security of a PHP system, especially one built quickly with AI assistance, request a free quote for a review.