I have a little chatbox on my website and it has a simple php code I've put together to check for any undesired tags, and also a sort of psuedo bbcode for basic color and bold and stuff. It saves the chat to a datatable on my server. My problem is that any time a user has an apostrophe it won't go through. Even when commenting out the strip_tags. I thought about just finding them in the string and replacing them with some other key, but then it'd replace any instance of that key and when converting back to an apostrophe it could screw up the actual line of text (for example if users do a - symbol but I'm using that as the replacement for apostrophes, when converted back from - to apostrophe it'd mess their symbol up).
Any clear way to go about fixing this problem?
updateChat.php:
<html><body>
<?php
session_start();
if (!isset($_SESSION['loggedin'])) {
header('Location: index.html');
exit;
}
require_once 'dbconnection.php';
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$qry = ('SELECT ChatText FROM Chat LIMIT 20');
$res = mysqli_query($conn, $qry);
$submittext=$_POST["submittext"];
$user= $_SESSION['name'];
$posttext = "[b]" .$user. ":[/b] " .$submittext. "";
if(!empty($submittext)) {
if(!empty($user)){
if($submittext != strip_tags($submittext)) {
// contains HTML
}
else{
$sql="INSERT INTO Chat (ChatText) VALUES ('$posttext')";
if($conn->query($sql)===TRUE){}
}
}
}
?>
</body></html>
getChat.php:
<html><body>
<?php
require_once 'dbconnection.php';
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$chatarray = array();
$qry = ('SELECT ChatText FROM Chat');
$res = mysqli_query($conn, $qry);
if(mysqli_num_rows($res) > 0) // checking if there is any row in the resultset
{
while($row = mysqli_fetch_assoc($res)) // Iterate for each rows
{
$chatarray[] = $row['ChatText'];
}
}
foreach (array_reverse($chatarray) as $chat)
{
$newmessage = $chat;
$newmessage = nl2br($newmessage);
$newmessage = wordwrap($newmessage, 34, "\n", true);
$bbcode = array("[b]", "[/b]", "[red]", "[blue]", "[green]", "[purple]", "[/color]");
$htmlcode = array("<b>", "</b>", "<span style='color:red'>", "<span style='color:blue'>", "<span style='color:green'>", "<span style='color:purple'>", "</span>");
$newmessage = str_replace($bbcode, $htmlcode, $newmessage);
$btagfixes = "";
$stagfixes = "";
$numbold = substr_count($newmessage, "<b>");
$numboldclosed = substr_count($newmessage, "</b>");
if ($numbold > $numboldclosed)
{
$cnt = $numbold - $numboldclosed;
while ($cnt > 0)
{
$btagfixes .="</b>";
$cnt --;
}
}
$numspan = substr_count($newmessage, "<span");
$numspanclosed = substr_count($newmessage, "</span>");
if ($numspan > $numspanclosed)
{
$cnt = $numspan - $numspanclosed;
while ($cnt > 0)
{
$stagfixes .="</span>";
$cnt --;
}
}
echo "<span class='adv_chat_p'>";
echo $newmessage. "" .$btagfixes. "" .$stagfixes."</span></br></br>";
}
?>
</body></html>