I’ve been asked for the source of save.php, which handles saving an image to the server.
In JavaScript, the data url of the canvas is posted to save.php over AJAX. (As an aside, this is the single usage of Ajax in CanvasPaint, so it really doesn’t deserve to be that prominent of a tag for the site on del.icio.us…)
req.open("POST", "save.php", true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.send("u="+canvas.toDataURL());
In PHP, base64_decode() does all the magic:
$dataurl = str_replace(" ", "+", $_POST["u"]);
$data = substr($dataurl, strpos($dataurl, “,”));
$file = fopen(”image.png”, “wb”);
fwrite($file, base64_decode($data));
fclose($file);
Add a couple of security checks (mimetype, data url length, evil hax0ring attempts…) and filename generation, and you’re done.
January 18th, 2007 at 12:0
Great stuff!
Though perhaps you should mention that you have to echo back “image.png” (or whatever the filename is).
e.g.
…
fclose($file);
echo ‘image.png’;
August 19th, 2007 at 23:1
Thank you very much –this has saved me hours of frustration.
-Ryan
January 15th, 2008 at 13:0
Hello there.
I’m trying to code a simple save function for my project based on canvas, and I have a problem. When I use the method presented in the post, I get an error from my apache, that the url is too long… and it is quite long. I’ve decided to have the save function inside the main php file, I’ve used sajax to do the saving part, but still, the data is too big to get there. I’m using a 300×300 canvas, would any of you have an advice for me?
January 15th, 2008 at 14:0
“URL too long” sounds like you’re submitting the data with a GET request (= a URL parameter), and not a POST request like in the example above (= as the body of an HTTP request). POST should not have a maximum length, or at least not one you will be likely to hit — that’s how files are uploaded, for example.
So make sure when you call sajax, you’re specifying POST as the method.
January 15th, 2008 at 16:0
Ah, thank you very much c3o, I forgot to change the request type, silly me :)
September 23rd, 2008 at 17:1
“Add a couple of security checks (mimetype, data url length, evil hax0ring attempts…) and filename generation, and you’re done.”
What about this, could you explain please how to secure the script? What security vulnerability you see here?