prismspecs
prismspecs

Reputation: 1489

Saving canvas to file on server with PHP

I am not very experienced in PHP but I managed to cobble together a few examples to make this. I just want to save the image of a canvas element to a file on the server. Right now a PNG with 0 bytes is created, so I'm nearly there.

It was suggested to me to try another solution from a separate thread, though unfortunately it gives me the same error (a png file of 0 bytes). Here is the entire index.php code for that:

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Fingerprint Test</title>

        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" ></script>
    </head>
    <body>

        <canvas id="myCanvas" width="578" height="200"></canvas>

        <form name="form1">
            <input type="text" id="my_hidden">
        </form> 

        <script>
            var canvas = document.getElementById('myCanvas');
            var context = canvas.getContext('2d');

            // begin custom shape
            context.font = "30px Arial";
            context.fillText("Hello World",10,50);
        </script>

        <button onclick="makePrint()">Click me</button> 

        <script>
            function makePrint() {
                document.getElementById('my_hidden').value = canvas.toDataURL('image/png');
                document.forms["form1"].submit();
            }
        </script>

        <?php 
            $upload_dir = "images/";  //implement this function yourself
            $img = $_POST['my_hidden'];
            $img = str_replace('data:image/png;base64,', '', $img);
            $img = str_replace(' ', '+', $img);
            $data = base64_decode($img);
            $file = $upload_dir."image_name.png";
            $success = file_put_contents($file, $data);
            header('Location: '.$_POST['return_url']);
        ?>
    </body>
</html>

Note that I have also tried giving the INPUT form the name "my_hidden" in addition to it being the ID.

EDIT: With this particular method, my problems were solved by two changes. First, "my_hidden" must indeed by the NAME as well as ID of the input field. Second, the form element must have a method='post' on it.

Upvotes: 0

Views: 1268

Answers (1)

Michael Bates
Michael Bates

Reputation: 1934

By default a form will do a HTTP GET, and you haven't specified a method attribute on the <form>. Because it's a GET $_POST['my_hidden'] will be undefined.

Try this:

<form name="form1" method="post">
    <input type="text" name="my_hidden">
</form> 

See here for more about the default form method: What is the default form HTTP method?

Upvotes: 2

Related Questions