CakePHP 4 Create Signature Pad & Save Using jQuery

Reading Time: 6 minutes
1,754 Views

Inside this article we will see a very interesting topic i.e How to create a signature pad & save using jquery in CakePHP 4. Signature Pad – HTML5 canvas based smooth signature drawing using variable width spline interpolation.

This tutorial will give you a idea to integrate a signature pad into your application and save signature generated image to server. For signature pad integration we will use jquery plugin and to save signature to server as an image we will use CakePHP 4 framework.

Learn more –

Let’s get started.

CakePHP 4 Installation

To create a CakePHP project, run this command into your shell or terminal. Make sure composer should be installed in your system.

$ composer create-project --prefer-dist cakephp/app:~4.0 mycakephp

Above command will creates a project with the name called mycakephp.

Create Controller

Open project into terminal and run this command into it.

$ bin/cake bake controller Signature --no-actions

It will create SignatureController.php file inside /src/Controller folder. Open controller file and write this code into it.

<?php

declare(strict_types=1);

namespace App\Controller;

class SignatureController extends AppController
{
    public function initialize(): void
    {
        parent::initialize();
    }

    public function index()
    {
        // for open frontend layout + form submit
        if ($this->request->is("post")) {

            $file_string = $this->request->getData('signed');

            $image = explode(";base64,", $file_string);

            $image_type = explode("image/", $image[0]);

            $image_type_png = $image_type[1];

            $image_base64 = base64_decode($image[1]);

            $folderPath = WWW_ROOT . 'img/';

            $file = $folderPath . uniqid() . '.' . $image_type_png;

            file_put_contents($file, $image_base64);

            $this->Flash->success("Signature saved successfully");
        }
    }
}

Inside above controller we have two methods – initialize() which is a constructor and other index() responsible for showing frontend signature pad including it’s submission as well.

Concept To Save Signature –

$file_string = $this->request->getData('signed');

$image = explode(";base64,", $file_string);

$image_type = explode("image/", $image[0]);

$image_type_png = $image_type[1];

$image_base64 = base64_decode($image[1]);

$folderPath = WWW_ROOT . 'img/';

$file = $folderPath . uniqid() . '.' . $image_type_png;

file_put_contents($file, $image_base64);

WWW_ROOT . “img/” returns the path upto of /img folder of webroot.

Above following code will save form data once we submit with form. Also it will upload the image into /webroot/img folder.

Create Template

Create Signature folder inside /templates folder. Next, needs to create index.php file inside /templates/Signature folder.

Open index.php file and write this following code into it. This will give the frontend layout for form.

<html>

<head>
    <title>Create Signature Pad Using jQuery in CakePHP 4</title>

    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.css">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" />

    <link rel="stylesheet" type="text/css" href="http://keith-wood.name/css/jquery.signature.css">

    <style>
        .kbw-signature {
            width: 100%;
            height: 200px;
        }

        #sig canvas {
            width: 100% !important;
            height: auto;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="row">
            <div class="col-md-8 offset-md-3 mt-5">
                <div class="card">
                    <div class="card-header">
                        <h5>Create Signature Pad Using jQuery in CakePHP 4</h5>
                    </div>
                    <div class="card-body">

                        <?= $this->Flash->render() ?>

                        <form method="POST" action="/signature">
                            <div class="col-md-12">
                                <label class="" for="">Draw Signature:</label>
                                <br />
                                <div id="sig"></div>
                                <br><br>
                                <button id="clear" class="btn btn-danger">Clear Signature</button>
                                <button class="btn btn-success">Save</button>
                                <textarea id="signature" name="signed" style="display: none"></textarea>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>

    <script type="text/javascript" src="http://keith-wood.name/js/jquery.signature.js"></script>

    <script type="text/javascript">
        var sig = $('#sig').signature({
            syncField: '#signature',
            syncFormat: 'PNG'
        });
        $('#clear').click(function(e) {
            e.preventDefault();
            sig.signature('clear');
            $("#signature").val('');
        });
    </script>
</body>

</html>

Disable CSRF Token

When we submit a cakephp form, it needs a CSRF token should be submitted with form submission request.

We are not interested to send CSRF token with form data. To disable it, Open Application.php from /src folder.

Remove these lines of code from middleware() method.

->add(new CsrfProtectionMiddleware([
    'httponly' => true,
]))

Add Route

Open routes.php file from /config folder. Add this route into it.

//...

$routes->connect(
    '/signature',
    ['controller' => 'Signature', 'action' => 'index']
);
//...

Application Testing

Open terminal and run this command to start development server.

$ bin/cake server

URL: http://localhost:8765/signature

When we hit Save button, it will save the signature image into /webroot/img folder.

We hope this article helped you to learn about CakePHP 4 Create Signature Pad & Save Using jQuery in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more