I am working on a project, where I have implemented a couple of graphs/charts using the Rgraph PHP library. In my script I do the following for the graphs:
- Calculate the graph points and draw the graph using the Rgraph
Draw()
method. - Create an image data variable using the
canvas.toDataURL()
method. - Pass this image data variable to the server using jQuery AJAX
$.post()
method. - Save the image to server via the PHP script.
Everything in this solution works great on my localhost, however on the development server, the AJAX request that passes the image data returns a 403 Error
.
I logged the data on both the client and server side to determine the issue. Client side logging confirms the imageData variable being passed looks correct. However server side logging confirms that the imageData variable being passed is what is causing the issue.
There was a very similar question posted last year about this, however they were unable to determine the root cause of this. Can anyone help point me in the right direction of resolving this?
I'm thinking this is a possible data encoding issue, but if this the case, why does it work on one server and not the other?
My Relevant Javascript:
radar.Set('chart.contextmenu', [
['Get PNG', RGraph.showPNG],
null,
['Cancel', function () {}]
]);
radar.Draw();
var imageData = radar.canvas.toDataURL("image/png");
console.log('imageData: ' + imageData);
console.log('filename: ' + 'tmpRadar<?php echo $us['UsersSurvey']['user_id']; ?>-<?php echo $survey['Survey']['id']; ?>.png');
$.post("/Surveys/save_chart", {
src : imageData,
filename: 'tmpRadar<?php echo $us['UsersSurvey']['user_id']; ?>-<?php echo $survey['Survey']['id']; ?>.png'
});
Client Side Logging:
imageData: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABLAAAAOECAYAAACxbcj6AAAgAElEQ…AgQIAAgVECAqxR49YsAQIECBAgQIAAAQIECBAgQKCfwP8CXHJ+WDHVMbcAAAAASUVORK5CYII=
filename: tmpRadar19-1.png
POST http://website.com/Surveys/save_chart 403 (Forbidden)
PHP Function called by AJAX:
public function save_chart() {
if($this->request->is('ajax')) {
$this->log('request data: '.print_r($this->request->data, true));
$filename = $this->request->data['filename'];
$src = $this->request->data['src'];
$src = substr($src, strpos($src, ",") + 1);
$decoded = base64_decode($src);
$fp = fopen(WWW_ROOT.'files/graphs/'.$filename,'wb');
if(fwrite($fp, $decoded)) {
fclose($fp);
return json_encode(array('success' => '1'));
} else {
fclose($fp);
return json_encode(array('success' => '0'));
}
}
}