Can AI Write PHP Code?

I asked ChatGPT 3.5 “Can AI write PHP code?”. ChatGPT 3.5 is a free version of Artificial Intelligence.

I’ve been a freelance PHP developer since 2006. I consider myself to be a senior developer.

https://youtu.be/k7CNqcKxKTg

Here is what ChatGPT responded:

Yes, AI can be trained to generate PHP code. PHP is a widely used scripting language for web development, so some models and tools can assist in generating PHP code snippets or even more complex scripts.

However, it’s important to note a few things:

1.**Quality and Intent**: The quality of AI-generated code can vary. AI can produce syntactically correct code based on training data, but it might not always produce efficient or well-structured code that adheres to best practices or security guidelines without careful oversight.

2.**Use Cases**: AI-generated PHP code can be useful for generating boilerplate code, automating repetitive tasks, or even suggesting solutions based on specifications. It can help developers save time and focus on higher-level aspects of development.

3.**Limitations**: AI models are trained on existing data and patterns. They might struggle with highly specialized or novel requirements that deviate significantly from the data they were trained on.

4.**Human Oversight**: Regardless of AI assistance, human oversight, and validation are crucial. Developers should review and test all generated code to ensure it meets project requirements and standards.

In summary, AI can write PHP code and assist developers in various ways. Still, it is most effective as a tool to augment human creativity and expertise rather than replace it entirely.

I’ve been experimenting with ChatGPT 3.5 for maybe 6 weeks as of the writing of this article. I am interested in article writing and PHP code creation.

Before we get started, let’s discuss what is known as prompts. Prompts are the way to interact with ChatGPT 3.5. The better the prompt the better the reply from ChatGPT 3.5.

It is a learning experience.

The other thing that needs to be discussed immediately is the more PHP programming experience the developer has, increases the potential for using and implementing PHP code produced by ChatGPT 3.5.

Recently my local Linux group discussed using AI to generate code. The consensus was that in the short term, there would be little change. The short term is maybe the next 3 years.

The group felt that at some point the junior and mid-range PHP developers would be displaced.

The group also found this scenario interesting in that as the senior developers retire or exit programming there would be no one to replace them, as the juniors and mid-range developers would be non-existent. It might take 6 to 10 years to create a senior developer.

Let me give you a few examples.

If I ask AI to “create a login script in PHP using the MySQL database”. ChatGPT responded:

Creating a login script in PHP using MySQL involves several steps, including connecting to the database, querying user credentials, and validating the login. Below is a basic example of how you can implement this:

1.**Create a MySQL Database:**

First, you need a MySQL database with a table to store user information. Here’s an example SQL to create a `users` table:

CREATE TABLE users (
    id INT(11) AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL,
    password VARCHAR(255) NOT NULL, — Hashed password
    email VARCHAR(100) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Note: Always hash passwords before storing them in the database for security reasons.

Use PHP’s `password_hash()` function for this purpose.

2.**PHP Login Script:**

Create a PHP script (`login.php`) that handles the login process. Here’s an example:

<?php
session_start();
// Database connection parameters
$host = 'localhost';
$db = 'your_database';
$user = 'your_username';
$pass = 'your_password';
// Create connection
$conn = new mysqli($host, $user, $pass, $db);
// Check connection
if ($conn->connect_error)
{
    die("Connection failed: " . $conn->connect_error);
}
// Check if form was submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);
    // Prepare the SQL statement
    $stmt = $conn->prepare("SELECT password FROM users 
        WHERE username = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $stmt->store_result();
    // Check if user exists
    if ($stmt->num_rows > 0) 
    {
        $stmt->bind_result($hashedPassword);
        $stmt->fetch();
        // Verify the password
        if (password_verify($password, $hashedPassword)) 
        {
            // Set session variables
            $_SESSION['username'] = $username;
            header("Location: welcome.php"); // Redirect to welcome page
            exit();
        } else {
            $error = "Invalid username or password.";
        }
    } else {
        $error = "Invalid username or password.";
    }
    $stmt->close();
}
$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width,
            initial-scale=1.0">
        <title>Login</title>
    </head>
    <body>
        <h2>Login</h2>
        <?php if (isset($error)): ?>
            <div style="color: red;">
           <?php echo $error; ?></div>
        <?php endif; ?>
        <form action="login.php" method="post">
            <label for="username">Username:</label>
            <input type="text" name="username" id="username" required>
            <br>
            <label for="password">Password:</label>
            <input type="password" name="password" id="password" required>
            <br>
            <button type="submit">Login</button>
        </form>
    </body>
</html>

Instructions:

Database Setup: Ensure you have a MySQL database with a users table containing username (VARCHAR) and password (VARCHAR) fields. Use password_hash() when storing passwords.

Testing: Access login.php in your web browser, enter your credentials and check the behavior on both successful and failed logins.

Redirect Page: Create a welcome.php file to greet the user after login.

Security Notes:

Ensure your site uses HTTPS to protect user credentials.

Implement measures against SQL injection (this script uses prepared statements, which helps).

Consider adding Cross-Site Request Forgery (CSRF) protection for your forms.

Secure session management practices should be followed.

Feel free to customize the layout and logic to fit your application’s needs!

I ask “Should a cookie be implemented?” AI responds:

Implementing cookies can enhance user experience, especially for remembering user sessions or preferences. However, it’s important to handle them securely. Here are some points to consider regarding cookies in the context of a login system:

When to Use Cookies

Remember Me Functionality: Allow users to stay logged in even after closing their browser. This is usually done by storing a cookie with a token.

User Preferences: Save user-specific settings, like theme or language.

Security Considerations

Secure and HttpOnly Flags: Set the Secure flag for cookies to ensure they are only sent over HTTPS. The HttpOnly flag prevents client-side scripts from accessing the cookie, reducing the risk of XSS attacks.

SameSite Attribute: Use the SameSite attribute to help protect against CSRF attacks by controlling how cookies are sent with requests.

Token-Based Authentication: If you implement a “Remember Me” feature, use a securely generated token stored in the cookie, linked to the user’s session on the server.

Example of Implementing Cookies

Here’s a modified version of the login script that includes a “Remember Me” feature:

Updated login.php

<?php
session_start();
// Database connection parameters
$host = 'localhost';
$db = 'your_database';
$user = 'your_username';
$pass = 'your_password';
// Create connection
$conn = new mysqli($host, $user, $pass, $db);
// Check connection
if ($conn->connect_error)
{
    die("Connection failed: " . $conn->connect_error);
}
// Check if form was submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);
    $rememberMe = isset($_POST['remember_me']);
    // Prepare the SQL statement
    $stmt = $conn->prepare("SELECT password FROM users 
        WHERE username = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $stmt->store_result();
    // Check if user exists
    if ($stmt->num_rows > 0) 
    {
        $stmt->bind_result($hashedPassword);
        $stmt->fetch();
        // Verify the password
        if (password_verify($password, $hashedPassword)) 
        {
            // Set session variables
            $_SESSION['username'] = $username;
            // Handle "Remember Me" functionality
            if ($rememberMe) 
            {
                // Generate a token
                $token = bin2hex(random_bytes(16));
                // Store the token in the database with the username
                $stmt = $conn->prepare("UPDATE users SET 
                    remember_token = ? WHERE username = ?");
                $stmt->bind_param("ss", $token, $username);
                $stmt->execute();
                setcookie("remember_me", $token, time() + 
                    (86400 * 30), "/", "", true, true); // 30 days
            }
            header("Location: welcome.php"); // Redirect to welcome page
            exit();
        } else {
            $error = "Invalid username or password.";
        }
    } else {
        $error = "Invalid username or password.";
    }
    $stmt->close();
}
$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, 
            initial-scale=1.0">
        <title>Login</title>
    </head>
    <body>
        <h2>Login</h2>
        <?php if (isset($error)): ?>
            <div style="color: red;"><?php echo $error; ?></div>
        <?php endif; ?>
        <form action="login.php" method="post">
            <label for="username">Username:</label>
            <input type="text" name="username" id="username" required>
            <br>
            <label for="password">Password:</label>
            <input type="password" name="password" 
                id="password" required>
            <br>
            <label for="remember_me">
            <input type="checkbox" name="remember_me" 
                id="remember_me"> Remember Me
            </label>
            <br>
            <button type="submit">Login</button>
        </form>
    </body>
</html>

Additional Steps

Database Changes: Ensure your users table has a remember_token column to store the token.

Token Validation: On subsequent visits, check if the cookie is set. If it is, validate the token against the database and log the user in automatically.

Logout Logic: Clear the cookie and remove the token from the database when a user logs out.

Conclusion

Using cookies responsibly can enhance user experience, but always prioritize security by following best practices.

ChatGPT can make mistakes. Check important info.

Summary

I asked ChatGPT to create a PHP login script as an example and to answer the question “Can AI write PHP code?”. It does a great job. This experiment reinforces my statement that to effectively use AI to generate code, requires a senior developer.

Upon request, AI-generated login cookie code with lots of comments and explanations.

All in all, I think using AI, as a senior developer, might reduce development time by 30% – 50% – a big savings.

I did not mention that AI can have what is referred to as hallucinations. It would be worth your time to understand AI hallucinations.