Getting Started with PHP 8+ without using a Framework

Getting Started with PHP 8+ without using a Framework

Getting Started with PHP 8+ Without Using a Framework

PHP is a powerful and widely used server-side scripting language. While frameworks like Laravel and Symfony simplify development, sometimes you may want to work with PHP without a framework to maintain full control over your code. This guide will help you get started with PHP 8+ from scratch.

Getting Started with PHP 8+ Without Using a Framework

PHP is a powerful and widely used server-side scripting language. While frameworks like Laravel and Symfony simplify development, sometimes you may want to work with PHP without a framework to maintain full control over your code. This guide will help you get started with PHP 8+ from scratch.

1. Setting Up Your Environment

Install PHP 8+

Make sure you have PHP 8 or later installed on your system. You can check your version by running:

php -v

If you don’t have PHP installed, download it from php.net or use a package manager:

  • Mac (Homebrew): brew install php
  • Linux (APT): sudo apt install php
  • Windows: Use XAMPP or WAMP

Start a Local Development Server

Once PHP is installed, you can start a built-in development server with:

php -S localhost:8000

This starts a server at http://localhost:8000 where you can test your PHP scripts.

2. Project Structure

Even without a framework, organizing your files properly is essential. A basic structure might look like this:

my_php_project/
├── public/
│   ├── index.php
│   ├── style.css
│   └── script.js
├── src/
│   ├── Database.php
│   ├── Router.php
│   ├── Controller.php
├── views/
│   ├── home.php
│   ├── about.php
├── .env
└── composer.json
  • public/ - Contains the entry point (index.php), assets like CSS/JS.
  • src/ - Stores PHP classes such as database connections and routing.
  • views/ - Contains HTML templates.
  • .env - Environment variables (not committed to Git).
  • composer.json - Used for dependency management.

3. Writing a Simple Router

A simple router helps you manage URLs without a framework. Create public/index.php:

<?php
$request = $_SERVER['REQUEST_URI'];

switch ($request) {
    case '/':
        require __DIR__ . '/../views/home.php';
        break;
    case '/about':
        require __DIR__ . '/../views/about.php';
        break;
    default:
        http_response_code(404);
        echo "Page not found";
}

Now, visiting http://localhost:8000/ will load views/home.php, and http://localhost:8000/about will load views/about.php.

4. Connecting to a Database with PDO

Avoid using mysqli directly; instead, use PDO for secure database interactions. Example:

<?php
class Database {
    private $pdo;
    
    public function __construct() {
        $dsn = "mysql:host=localhost;dbname=my_database;charset=utf8mb4";
        $user = "root";
        $password = "";
        
        try {
            $this->pdo = new PDO($dsn, $user, $password, [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
            ]);
        } catch (PDOException $e) {
            die("Database connection failed: " . $e->getMessage());
        }
    }

    public function getPdo() {
        return $this->pdo;
    }
}

Use this class in your scripts:

$db = new Database();
$pdo = $db->getPdo();
$statement = $pdo->query("SELECT * FROM users");
$users = $statement->fetchAll();

5. Using Composer for Dependency Management

Even without a framework, Composer helps manage dependencies. Install it:

composer init
composer require vlucas/phpdotenv

This installs phpdotenv for managing environment variables. Load .env values in your scripts:

<?php
require 'vendor/autoload.php';
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

echo $_ENV['DB_NAME'];

6. Handling Forms and Requests

Create a form in views/home.php:

<form action="/submit.php" method="POST">
    <input type="text" name="name" placeholder="Your Name" required>
    <button type="submit">Submit</button>
</form>

Handle the form submission in public/submit.php:

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = htmlspecialchars($_POST['name']);
    echo "Hello, $name!";
}

Conclusion

This guide introduces PHP 8+ without a framework. With a structured approach, routing, database connections, and Composer for package management, you can build scalable applications from scratch. Happy coding!

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close