What ways can I improve this Chat-like script?

Discussions of secure PHP coding. Security in software is important, so don't be afraid to ask. And when answering: be anal. Nitpick. No security vulnerability is too small.

Moderator: General Moderators

Post Reply
DogGonMad
Forum Newbie
Posts: 2
Joined: Sat Apr 02, 2011 2:59 pm

What ways can I improve this Chat-like script?

Post by DogGonMad »

This I built entirely from my knowledge of PHP and poking through the manual, what ways can I improve this to prevent exploits?
Sorry if I'm sounding stupid, I'm very new to PHP and I'm trying to get this set up for a Flash that I am making and don't want things to be exploited Server-Side, Client-Side I can deal with if needed, but it is the server that will be handling all the information, ect.

Code: Select all

<?php
	mysql_connect(localhost,whatzhot_chat,XXXXX);

	@mysql_select_db(whatzhot_chat);
	if ($_REQUEST["reset"] == 1)
	{
		mysql_query("TRUNCATE TABLE `log` ");
		mysql_query("ALTER TABLE `log` AUTO_INCREMENT = 1");
		echo "Database reset...";
	}
	else
	{
		if($_REQUEST["request_current_index"])
		{
			echo mysql_numrows(mysql_query("SELECT * FROM log"));
		}
		else
		{
			if($_REQUEST["message"] && $_REQUEST["user_id"])
			{
				mysql_query("INSERT INTO log VALUES ('','" . gmdate("m-d-Y H:i:s") . "','" . filter_var ($_REQUEST["user_id"], FILTER_SANITIZE_NUMBER_INT) . "','". filter_var (mb_convert_encoding($_REQUEST["message"], 'HTML-ENTITIES', "UTF-8"), FILTER_SANITIZE_STRING) . "')");			
			}
			else
			{
				if($_REQUEST["message"] || $_REQUEST["user_id"])
				{
					echo "Error: Either message or user_id passed, not both. <br />";
				}
			}
			$result=mysql_query("SELECT * FROM log");
			$db_entries=mysql_numrows($result);
			if($_REQUEST["from_index"])
			{
				$index_number = $_REQUEST["from_index"];
				if($index_number > $db_entries || $index_number < 0)
				{
					$index_number = $db_entries;
				}
			}
			else
			{
				$index_number = 1;
			}
			for($i = $index_number; $i <= $db_entries ; $i++)
			{
				echo mysql_result($result,$i - 1,"id") . " " . mysql_result($result,$i - 1,"timestamp") . " " . mysql_result($result,$i - 1,"user_id") . " " . mysql_result($result,$i - 1,"message") . "<br />";
			}
		}
	}
	mysql_close();
?>
I will set up another user for resetting the Database, but for the moment, I'm just developing the core aspect.
User avatar
Mordred
DevNet Resident
Posts: 1579
Joined: Sun Sep 03, 2006 5:19 am
Location: Sofia, Bulgaria

Re: What ways can I improve this Chat-like script?

Post by Mordred »

filter_var is not an adequate protection against SQL injection, use mysql_real_escape_string()
DogGonMad
Forum Newbie
Posts: 2
Joined: Sat Apr 02, 2011 2:59 pm

Re: What ways can I improve this Chat-like script?

Post by DogGonMad »

Thanks, anything else to suggest anyone? Not necessarily from a security standpoint, that is.
Post Reply