dataDesk BLOG

Welcome to the blog of Mr.G

Nature

/Dev/HowTo

(Last modified: December 21 2024 01:37:55)

php project structure

When you're working on a PHP-focused project, the structure can differ from a typical front-end-focused project (like one with JavaScript, SCSS, and HTML). PHP-based projects are often server-side applications, and their folder structure depends on the frameworks, deployment strategy, and how the application is built.

Here's a breakdown of how a PHP-based project differs and a recommended structure:


Key Differences in PHP Projects

  1. PHP is Server-Side:

    • Your code runs on the server, and the client receives the output (usually HTML, CSS, and JavaScript).
    • There's often no need to distinguish between src and dist, as PHP files are not "built" or "compiled"; they are interpreted directly by the server.
  2. Focus on Backend Logic:

    • The project revolves around PHP scripts, templates, and logic for dynamic rendering.
    • Static assets like CSS, JavaScript, and images are still present but serve the front-end.
  3. Deployment is Different:

    • PHP projects are typically deployed by copying the entire folder to a server or uploading files via FTP or version control.
    • There’s usually no "build" process (unless you're also using modern tools for static assets like JavaScript or SCSS).

Recommended Folder Structure for PHP Projects

Here’s a standard folder structure for a PHP project:

project
├── public                 // Publicly accessible files
│   ├── index.php          // Entry point (e.g., front controller)
│   ├── css
│   │   └── styles.css     // CSS files
│   ├── js
│   │   └── script.js      // JavaScript files
│   ├── images
│   │   └── logo.png       // Images accessible by the browser
│   └── uploads            // User-uploaded files (if applicable)
├── src                    // Application source code (non-public)
│   ├── controllers        // PHP controllers
│   │   └── HomeController.php
│   ├── models             // Database models
│   │   └── UserModel.php
│   ├── views              // HTML templates or views
│   │   └── home.php
│   └── helpers            // Utility/helper PHP functions
│       └── Utils.php
├── config                 // Configuration files
│   ├── database.php       // Database connection settings
│   └── app.php            // Application settings
├── vendor                 // Composer dependencies (if using Composer)
├── storage                // Temporary files (e.g., logs, cache)
│   ├── cache
│   ├── logs
│   └── sessions
├── tests                  // Test scripts (optional)
│   ├── Unit
│   └── Integration
├── .env                   // Environment variables (e.g., database credentials)
├── composer.json          // Composer dependency configuration
├── README.md              // Documentation
└── .htaccess              // Apache configuration (if applicable)

Explanation of Each Folder

1. public/

  • This is the only folder accessible by the browser.
  • It contains:
    • index.php: The entry point for the application. This is often referred to as the "front controller" in frameworks like Laravel.
    • Static files: CSS, JS, images, and fonts.
    • Uploads: A folder for user-uploaded files (e.g., images, documents). Ensure this folder is secure.

2. src/

  • Contains all the core PHP logic for your application.
  • This is not publicly accessible for security reasons.
  • Subfolders typically include:
    • controllers/: Handles incoming requests and prepares data for views.
    • models/: Manages the data and database interactions.
    • views/: Contains HTML templates mixed with PHP logic (e.g., home.php).
    • helpers/: Stores reusable utility functions (e.g., date formatters, string helpers).

3. config/

  • Stores configuration files (e.g., database connection details, app settings).
  • Sensitive information like database credentials should be in a .env file or similar.

4. vendor/

  • Automatically created by Composer (PHP's dependency manager).
  • Contains third-party libraries and dependencies (e.g., for database handling or routing).

5. storage/

  • Contains runtime data like logs, cache, or session files.
  • This folder should not be publicly accessible.

6. tests/

  • Stores unit and integration tests.
  • Helps ensure your application behaves as expected.

7. Root Files

  • .env: Stores sensitive information (e.g., database credentials, API keys). This file should never be committed to version control.
  • composer.json: Defines your dependencies if you're using Composer.
  • .htaccess: For Apache-specific rules (e.g., redirecting all requests to index.php).

Comparison of Static Asset Organization in PHP

In PHP projects, static files like CSS and JavaScript are still stored in the public folder but are kept separate from the PHP code.

  1. Example of Static Files in public/:

    public
    ├── css
    │   └── styles.css
    ├── js
    │   └── script.js
    ├── images
    │   └── logo.png
  2. Why Keep Static Files Separate?

    • Static assets are served directly by the web server (e.g., Apache, Nginx), while PHP files are processed by the server.
    • Keeping them in public ensures clarity and security. PHP files (e.g., src/controllers) are not directly accessible by the browser.

Key Differences Between PHP and Front-End Project Structures

Aspect PHP Project Front-End Project
Build Process Typically no build process; PHP is interpreted directly Often involves bundling, transpiling, and minification
Static Assets Stored in public/ Often generated in dist/
Code Organization Backend logic in src/ Code split into src/ and dist/
Deployment Entire project may be deployed (except src/ subfolders) Only dist/ folder is deployed

Example Workflow for PHP Projects

  1. Development:

    • Write PHP logic in src/.
    • Place static assets like CSS and JS in public/.
  2. Production:

    • Deploy the entire project to the server but:
      • Restrict access to src/ using .htaccess or server configuration.
      • Ensure only public/ is exposed to the web.

It's better not to let users directly call or access files inside the /src folder. Here’s why:


Why Not Allow Direct User Access to /src

  1. Security Risks:

    • Files in /src often contain sensitive logic, database queries, or configuration details. If exposed, this could lead to vulnerabilities like SQL injection, data exposure, or unauthorized access to your system.

    Example:
    If a user can access src/helpers/Utils.php directly via http://example.com/src/helpers/Utils.php, they might:

    • See raw PHP code if your server misconfigures and doesn't process the PHP files.
    • Execute unintended scripts if the files aren't properly sanitized.
  2. Separation of Concerns:

    • /src is meant for your application's internal logic. It should not be exposed to the browser.
    • Users should only interact with the entry point (e.g., public/index.php), which calls files in /src as needed.
  3. Flexibility in Development:

    • By routing all requests through an entry point, you can control how your application evolves without breaking user-facing URLs.
    • If users can call /src directly, changing the folder structure or file names could break your application.

Best Practice: Route All User Requests Through index.php

The front controller pattern is a common best practice in PHP applications. It routes all user requests through a single file, typically index.php in the public/ folder. This file determines how to process the request and includes the appropriate PHP files from /src.


Example Workflow

  1. User Requests:

    • A user requests http://example.com/home.
    • The server routes this request to public/index.php.
  2. Application Logic in index.php:

    • index.php determines which controller or logic in /src should handle the request.
  3. Controller Handles Request:

    • The HomeController in /src/controllers processes the request and returns an HTML response to the user.

Example Folder Structure

project
├── public
│   ├── index.php       // All requests go through here
│   ├── css
│   │   └── styles.css  // Public static files
│   ├── js
│   │   └── script.js
│   └── images
│       └── logo.png
├── src
│   ├── controllers
│   │   └── HomeController.php
│   ├── models
│   │   └── UserModel.php
│   ├── views
│   │   └── home.php
│   ├── helpers
│   │   └── Utils.php
│   └── config.php

Example public/index.php

<?php
// Load application configuration
require_once __DIR__ . '/../src/config.php';

// Autoload classes (if using Composer or custom autoloader)
require_once __DIR__ . '/../vendor/autoload.php';

// Parse the requested URL
$requestUri = $_SERVER['REQUEST_URI'];

// Simple routing logic
switch ($requestUri) {
    case '/':
    case '/home':
        require_once __DIR__ . '/../src/controllers/HomeController.php';
        $controller = new HomeController();
        $controller->index(); // Call a method in HomeController
        break;

    case '/about':
        require_once __DIR__ . '/../src/controllers/AboutController.php';
        $controller = new AboutController();
        $controller->show();
        break;

    default:
        http_response_code(404);
        echo "404 - Page Not Found";
        break;
}

Example src/controllers/HomeController.php

<?php

class HomeController {
    public function index() {
        // Load a view file (HTML template with PHP logic)
        require_once __DIR__ . '/../views/home.php';
    }
}

Can You Let Users Access /src Directly?

Technically, you can if you:

  1. Place files in /src where users can call them directly (e.g., http://example.com/src/helpers/Utils.php).
  2. Add logic in each file to handle user requests appropriately.

Why This is NOT Recommended

  1. Inconsistent Organization:

    • If users access /src files directly, you lose the ability to centralize routing and control how requests are handled.
  2. Maintenance Challenges:

    • If your application grows, you’ll need to manually update each file to ensure they behave properly when accessed directly.
  3. Security Concerns:

    • Files in /src are not designed to be entry points and might expose sensitive logic or functionality if accessed directly.

What If It's Only for Internal Use?

If your project is for internal use only (e.g., accessed by trusted users), you can still follow best practices to maintain structure and security. Here's what you can do:

  1. Restrict Access to /src via .htaccess or Server Config:

    • Prevent public access to /src entirely but allow PHP scripts to include these files.

    Example .htaccess:

    <Directory "/path-to-project/src">
       Order Deny,Allow
       Deny from all
    </Directory>

    For Nginx:

    location /src {
       deny all;
    }
  2. Authenticate Users:

    • Add user authentication to ensure only authorized users can interact with your PHP application.
  3. Use a Single Entry Point for All Requests:

    • Even for internal applications, route all requests through index.php for consistency.

Conclusion

  • DO NOT allow users to directly access files in /src. These files should contain internal logic and helpers, not public-facing code.
  • Instead, route all requests through index.php in the public/ folder.
  • If it's an internal application for trusted users, you can still follow best practices for future scalability and security.

Who I am

"Just me, myself, and I, exploring the universe of unknownment, embracing the mystery of what lies beyond, one star at a time."

Share this page on Facebook | X.com | Reddit

Latest Posts

  • Image Lem - Warren Buffett walked into a University of Florida classroom in 1998 ... [2098423133938356224] (1)
    Published: September 12 2026
    Read
  • Image Sam Stoffel - Jack Dorsey's simple rule for success in business [2089319019065057280]
    Published: August 19 2026
    Read
  • Image Peter-Steinberger-What-Happens-When-4.7-_1786407922546
    Published: August 16 2026
    Read
  • Image Monitor_server_action____
    Published: August 16 2026
    Read
  • Image Disk_and_RAID_testing_commands
    Published: July 31 2026
    Read

Tags

WebDev New York London AI NORWAY DIY Ideas Life Family News Clothing Invest Sports Health