CakeDC Blog

TIPS, INSIGHTS AND THE LATEST FROM THE EXPERTS BEHIND CAKEPHP

5 CakePHP security tips

This article is part of the CakeDC Advent Calendar 2024 (December 20th 2024)

We all know the importance of security in our sites, so here we have 5 quick tips that can improve the security of your site quickly:

  • Ensure all cookies are configured for security
// config/app.php
'Session' => [
        // .. other configurations
        'cookie' => 'CUSTOM_NAME_FOR_YOUR_SESSION_COOKIE',
        'ini' => [
            'session.cookie_secure' => true,
            'session.cookie_httponly' => true,
            'session.cookie_samesite' => 'Strict',
        ],
    ],
  • Audit your dependencies
    • Both backend and frontend dependencies could be impacted by security issues. In the case of the backend, you can have a quick look by running composer audit. In case of issues, you'll see an output similar to:
$ composer audit
Found 7 security vulnerability advisories affecting 4 packages:
+-------------------+----------------------------------------------------------------------------------+
| Package           | composer/composer                                                                |
| CVE               | CVE-2024-35241                                                                   |
| Title             | Composer has a command injection via malicious git branch name                   |
| URL               | https://github.com/advisories/GHSA-47f6-5gq3-vx9c                                |
| Affected versions | >=2.3,<2.7.7|>=2.0,<2.2.24                                                       |
| Reported at       | 2024-06-10T21:36:32+00:00                                                        |
+-------------------+----------------------------------------------------------------------------------+
// in src/Application::middleware()

    // Cross Site Request Forgery (CSRF) Protection Middleware
    // https://book.cakephp.org/4/en/security/csrf.html#cross-site-request-forgery-csrf-middleware
    ->add(new CsrfProtectionMiddleware([
        'httponly' => true,
    ]));
  • Enforce HTTPS
    • Ensure your live applications are enforcing HTTPS to prevent downgrading to HTTP. You can handle that in a number of ways, for example using your webserver configuration, or a Proxy. If you want to handle it via CakePHP builtins, add
// in src/Application::middleware()

    ->add(new HttpsEnforcerMiddleware([
        'hsts' => [
            'maxAge' => 10,
            'includeSubDomains' => true,
            'preload' => false, // use preload true when you are sure all subdomains are OK with HTTPS
        ],
    ]))
// in src/Application::middleware()
    $securityHeaders = (new SecurityHeadersMiddleware())
        ->setReferrerPolicy() // limit referrer info leaked
        ->setXFrameOptions() // mitigates clickjacking attacks
        ->noOpen() // don't save file in downloads auto
        ->noSniff(); // mitigates mime type sniffing
    $middlewareQueue
        // ...
        ->add($securityHeaders)
        // ...

This is just a quick example of 5 changes in code you could apply today to improve your CakePHP website security. Keep your projects safe!

This article is part of the CakeDC Advent Calendar 2024 (December 20th 2024)

Latest articles

The CakeDC Advent Calendar is BACK!

It’s the most wonderful time of the year! I don’t just mean the holidays… I’m talking about the CakeDC Advent Calendar!    If you missed it last year, we put together a series of blog posts in the form of a holiday advent calendar. Each day, you will get to open the gift of a new article written by one of our team members. You can wake up every morning in December with Cake(PHP). Does it get any better?    So what can you expect this year?  Great topics like: 

  • CakePHP upgrades
  • Security tips
  • CakePHP and the power of AI
  • Supabase + CakePHP
  • CakePHP Horizontal Scaling
  • CakePHP and FrankenPHP
  • Advanced Exports in CakePHP 5
  • + so much more! 

  Enjoy our gift to you that lasts the whole month through (maybe I should write poems instead of blogs?).    While you wait, here are some links from last year’s calendar to hold you over: https://www.cakedc.com/yevgeny_tomenko/2024/12/21/cakedc-search-filter-plugin   https://www.cakedc.com/ajibarra/2024/12/12/almost-20-years-a-bit-of-history-about-cakephp   https://www.cakedc.com/jorge_gonzalez/2024/12/20/5-cakephp-security-tips
  See you tomorrow! 

CakePHP AI Integration: Build a CakePHP MCP Server with Claude

Learn how to build a CakePHP MCP server (local) for AI integration.

Intro

Unless your crew left you stranded on a desert island earlier this year, I'm sure you've heard about every big name in the industry integrating their applications and exposing their data to "agents". Model Context Protocol https://modelcontextprotocol.io/docs/getting-started/intro was created to define how the your application could interact and provide features to Agents. These features could be readonly, but also methods (or tools) to allow the Agent operate with your application, for example, creating orders, updating post titles, reordering invoices, or creating reports for your bookings. As a developer, this is a quick win! Providing access, even readonly, could expand the quality of the interaction between your users and your application. In my opinion, the benefits are: Agents deal with context very well, they can use the conversation history, and also extract required data to use the available tools. Agents can transform the data, providing "features" to your users that you didn't implement. For example building charts on the fly, or creating scripts to transform the data for another tool. Quickly after the publication of the MCP protocol, the PHP community started working on a standarized SDK to help with the implementation of MCP servers. Even if the SDK is in active development right now, we are going to explore it and build a local MCP server, connecting Claude Desktop to it. The idea behind the example is to open your application to Claude Desktop, so the Agent (Claude) can connect directly to your code using the specified tools. For production environments, there are many other considerations we should be handling, like authorization, rate limiting, data exchange and privacy, etc. We'll leave all these production grade issues for another day and jump into an example you can implement "today" in your CakePHP application. Development vs. Production: This tutorial focuses on a local development setup for your CakePHP MCP server. Production environments require additional considerations including:
  • Authentication and authorization
  • Rate limiting
  • Data privacy and security
  • Audit logging
  • Input validation and sanitization
  • Error handling and monitoring

What is a CakePHP MCP Server?

A CakePHP MCP server is a specialized implementation that allows AI agents like Claude to interact with your CakePHP application through the Model Context Protocol. This CakePHP AI integration creates a bridge between your application logic and AI capabilities, enabling:
  • Natural language interfaces for complex queries
  • Automated content generation and management
  • Real-time data analysis and reporting

Prerequisites

Before starting, ensure you have:
  • PHP 8.1 or higher
  • Composer
  • SQLite or MySQL
  • Claude Desktop (free tier available)

Step 1: Set Up the CakePHP CMS Application

We'll use the official CakePHP CMS tutorial. # Clone the repository git clone https://github.com/cakephp/cms-tutorial cd cms-tutorial # Install dependencies composer install # Run database migrations bin/cake migrations migrate # Start the development server bin/cake server

Create a Test User

  1. Navigate to http://localhost:8765/users/add
  2. Create a new user with your preferred email and password
  3. Log in at http://localhost:8765/users/login
  4. Verify you can create an article via http://localhost:8765/articles/add

Step 2: Install Claude Desktop

Download and install Claude Desktop from https://claude.com/download

Step 3: Install the CakePHP MCP Plugin

To build your CakePHP MCP server, install the MCP utility plugin and SDK in your CakePHP project: composer require cakedc/cakephp-mcp:dev-2.next-cake5 mcp/sdk:'dev-main#4b91567' Note: These packages are in active development.

Step 4: Create the CakePHP MCP Server Script

Create a new file bin/mcp to initialize your CakePHP MCP server: #!/usr/bin/env sh cd /absolute/path/to/your/cms-tutorial && php vendor/cakedc/cakephp-mcp/bin/mcp-server Important: Replace /absolute/path/to/your/cms-tutorial with your actual project path. For example: /home/user/cms-tutorial or C:\Users\YourName\cms-tutorial Make the script executable: chmod +x bin/mcp

Step 5: Create Your First CakePHP MCP Tool

Create the file: src/Mcp/Articles.php <?php namespace App\Mcp; use App\Model\Entity\Article; use Cake\ORM\Locator\LocatorAwareTrait; use Mcp\Capability\Attribute\McpTool; class Articles { use LocatorAwareTrait; #[McpTool(name: 'createArticle')] public function createArticle(string $title, string $body): array { try { $article = new Article([ 'title' => $title, 'body' => $body, 'user_id' => $this->fetchTable('Users')->find()->firstOrFail()->id, // a default user ID for simplicity ]); if (!$this->fetchTable('Articles')->save($article)) { return [ 'success' => false, 'message' => 'Failed to create article: ' . json_encode($article->getErrors()), ]; } return [ 'success' => true, 'message' => 'Article created successfully', ]; } catch (\Throwable $e) { return [ 'success' => false, 'message' => 'Exception to create article: ' . $e->getMessage(), ]; } } } The #[McpTool] Attribute: This PHP 8 attribute registers the method as an MCP tool that Claude can discover and use in your CakePHP AI integration. The name parameter defines how Claude will reference this tool. Simplified User Assignment: For demonstration purposes, we're using the first available user. In production CakePHP AI integrations, you'd implement proper user authentication and context.

Step 6: Configure Claude Desktop for CakePHP MCP Integration

Add your CakePHP MCP server to Claude Desktop's configuration:
  1. Open Claude Desktop
  2. Go to Settings → Developer → Edit Config
  3. Add your MCP server configuration:
{ "mcpServers": { "cakephp-cms": { "command": "/absolute/path/to/your/cms-tutorial/bin/mcp" } } }
  1. Save the configuration and restart Claude Desktop

Step 7: Test Your CakePHP AI Integration

Once Claude Desktop restarts, you should see your CakePHP MCP server connected:
  1. MCP Server Connected: Look for the server indicator in Claude Desktop showing your CakePHP MCP integration is active
  2. Available Tools: You can view available CakePHP MCP tools by clicking the tools icon
  3. The createArticle tool: Should appear in the list of available tools
  4. Now you can use the Claude Desktop prompt to generate articles, that will be saved directly into your CakePHP application!

Wrapping up

You've successfully built a CakePHP MCP server and implemented CakePHP AI integration with Claude! This Model Context Protocol CakePHP implementation opens up powerful possibilities for AI-enhanced user experiences and automation in your web applications.

CakeFest 2025 Wrap Up

For years I have heard the team talk about Madrid being one of their favorite cities to visit, because they hosted CakeFest there more than a decade ago. I can now confirm… they were right! What a beautiful city. Another great CakeFest in the books… Thanks Madrid!   Not only are we coming down from the sugar high, but we are also honored to be celebrating 20 years of CakePHP. It was amazing to celebrate with the attendees (both physical and virtual). If you watched the cake ceremony, you saw just how emotional it made Larry to reminisce on the last 20 years. I do know one thing, CakePHP would not be where it is without the dedicated core, and community.    Speaking of the core, we had both Mark Scherer and Mark Story joining us as presenters this year. It is a highlight for our team to interact with them each year. I know a lot of the other members from the core team would have liked to join us as well, but we hope to see them soon. The hard work they put in day after day is unmatched, and often not recognized enough. It’s hard to put into words how grateful we are for this group of bakers.    Our event was 2 jam packed days of workshops and talk presentations, which you can now see a replay of on our YouTube channel (youtube.com/cakephp). We had presenters from Canada, Germany, India, Spain, USA, and more! This is one of my favorite parts about the CakePHP community, the diversity and representation from all over the world. When we come together in one room, with one common goal, it’s just magical. Aside from the conference itself, the attendees had a chance to network, mingle, and enjoy meals together as a group.  I could sense the excitement of what’s to come for a framework that is very much still alive. Speaking of which… spoiler alert: CakePHP 6 is coming. Check out the roadmap HERE.   I feel as though our team leaves the event each year with a smile on their face, and looking forward to the next. The events are growing each year, although we do like to keep the small group/intimate type of atmosphere. I am already getting messages about the location for next year, and I promise we will let you know as soon as we can (when we know!). In the meantime, start preparing your talks, and send us your location votes.   The ovens are heating up….

We Bake with CakePHP