Search code examples
phpcssfwrite

Why can't I write a CSS stylesheet to a file with PHP?


<?php
    $cdata = $_GET['cdata'];
    $cfile = "./output/$ip/output.css";
    $cout = fopen($cfile, 'w') or die("1");
    fwrite($cout, $cdata) or die("Could not write to " . $cfile);
    echo("Wrote CSS to " . $cfile . " successfully.<br />");
    fclose($cout);
?>

When I execute this on my web server, it tells me that it was successful (or perchance I didn't catch the error), but it writes part of what I want it to. Here's what I tell it to write (passed in via url as $_GET['cdata']):

body{background: #000; color: #FFF;}

And this is what I get back from the file

body{background: 

Note that there is a space at the end, so I'm assuming the pound (#) is causing issues, but don't know why or how to fix it.

This isn't the entirety of my code, just a snippet, and where I think the error lies. I hope this is enough information, if not please ask and I'll try to throw whatever else in there. Thanks in advance.

SOLUTION

Since I was using jQuery's $.post() method to send the data, all I needed to do was wrap the data being sent with encodeURIComponent(), and that seems to have done the trick. Thanks @xbonez for pointing me in the right direction there.


Solution

  • You need to encode your url property, the # in the url is being treated as a hash and not being sent to the server. e.g.

     var args = 'cdata='+encodeURIComponent('body{background: #000; color: #FFF;}');