I have a basic CMS where a user can update a database of articles and it uses a simple set of BBCodes for some extra features.
Basically, the user inputs the article information into a HTML form, and then on the click of a “Publish” button, an AJAX request is sent to a PHP script on the server which uses Regex to convert the BBCodes to HTML, and then stores the info in the database using MySQL.
My problem is an unfortunate one, in that it has come immediately after solving another, and it is very hard to debug since it is a server side script and I am getting no error messages echoed at all.
I was having trouble with the Regex, specifically with more complicated tags. I managed to get [link=URL]FOOBAR[/link] tags to correctly match and then replace them with FOOBAR. For some reason, however, this now made the script either hang or fail or something because I’m not getting anything updated into the database when it contains [link] tags.
For the purposes of debugging earlier when I wanted to get the SQL working, I had the PHP script echo the return value of the mysql_query() function which I believe is a “1” when it is successful, and a “0” when it fails. Now, however, it simply returns nothing… and the HTTPRequest receives a 0 length string back.
Here is the code:
$post = $_POST['post'];
$regex = Array('#(\r?\n)#', '#(\[(\/?)(b|i|u)\])#', '#\[link=(http://(www.)?.*?)\](.*?)\[/link\]#', '#(\[youtube\][http://www.youtube.com/watch?v=]?(\w+)[&\w+]?\[/youtube\])#', '#(\[img\](http://[www.]?[\w+])\[/img\])#');
$regReplace = Array('<br />', '<$2$3>', '<a href="$1">$3</a>', '<div class="media"><iframe title="YouTube video player" width="560" height="315" src="http://www.youtube.com/embed/$2" frameborder="0" allowfullscreen></iframe></div>',
'<div class="media"><img width="560" src="$2" /></div>');
$post = preg_replace($regex, $regReplace, $post);
echo mysql_query('INSERT INTO News VALUES (NULL, "'.Date('D jS M').'", "'.Date('G:i').'", "'.$_POST['heading'].'", "'.$post.'")');
I am aware that the IMG and Youtube regexs don’t work…
There are several issues here. The mentioned error stems from not escaping the quote in the parameter string with backslash + quote. Furthermore the SQL standard uses the single quote, so even if double quote is possible, it is better to use a single quote. And then there is a huge security leak, SQL injection, with which your site may be hacked (database and files displayed).
Look at prepared statements which also solves the quote escaping.