Jump to content

Need help to not resubmit info when refreshing


cobusbo

Recommended Posts

Hi I made a simple chat script with pagination in MySQL (yes I know I should change to MySQLi) but just bare with me please :) My script is working fine when I post messages, but I have a problem.. Each time I refresh my page my previous message gets reposted again. Is there maybe a way I can fix this problem?

<html>
<?php
define('TIMEZONE', 'Africa/Harare');
date_default_timezone_set(TIMEZONE);



// database connection info
$conn = mysql_connect('****','******','*****') or trigger_error("SQL", E_USER_ERROR);
$db = mysql_select_db('*****'',$conn) or trigger_error("SQL", E_USER_ERROR);


// find out how many rows are in the table 
$sql = "SELECT COUNT(*) FROM StringyChat";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
$r = mysql_fetch_row($result);
$numrows = $r[0];

// number of rows to show per page
$rowsperpage = 20;
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);

// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
   // cast var as int
   $currentpage = (int) $_GET['currentpage'];
} else {
   // default page num
   $currentpage = 1;
} // end if

// if current page is greater than total pages...
if ($currentpage > $totalpages) {
   // set current page to last page
   $currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
   // set current page to first page
   $currentpage = 1;
} // end if

// the offset of the list, based on current page 
$offset = ($currentpage - 1) * $rowsperpage;



// INSERT INTO DATABASE


$ip = $_SERVER["REMOTE_ADDR"];
$name = $_SERVER["HTTP_X_MXIT_USERID_R"];
$msg = $_POST['message'];
$time = date("U");
$mxitid = $_SERVER["HTTP_X_MXIT_USERID_R"];
if(!isset($mxitid, $name ))
{
	$mxitid = "DEFAULT";
	$name = "SYSOP";

}



$sqli = "INSERT INTO StringyChat (StringyChat_ip, StringyChat_name, StringyChat_message, StringyChat_time, mxit_id)
VALUES ('$ip', '$name', '$msg', '$time', '$mxitid')";
$result = mysql_query($sqli, $conn) or trigger_error("SQL", E_USER_ERROR);




// get the info from the db 
$sql = "SELECT StringyChat_time, StringyChat_name, StringyChat_message FROM StringyChat ORDER BY id DESC LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);



function filterBadWords($str)
{
	
	
    $result1 = mysql_query("SELECT word FROM StringyChat_WordBan") or die(mysql_error()); 
    $replacements = ":-x";
    
    while($row = mysql_fetch_assoc($result1))
    {
          $str = eregi_replace($row['word'], str_repeat(':-x', strlen($row['word'])), $str);
    }  
    
    return $str;
}



// while there are rows to be fetched...
while ($list = mysql_fetch_assoc($result)) 
//while (($pmsg = $list['StringyChat_message'] == $bwords) ? ":-x" : $list['StringyChat_message'])
 {
   // echo data
   //echo ($pmsg = ($list['StringyChat_message'] == $bwords) ? ":-x" : $list['StringyChat_message'])

   print '<span style="color:#828282">' . '(' . date( 'D H:i:s', $list['StringyChat_time'] )  . ') ' . '</span>' . '<b>' . $list['StringyChat_name'] . '</b>' . ' : ' . filterBadWords($list['StringyChat_message']) . '<br />';
} 








// end while

/******  build the pagination links ******/
// range of num links to show
$range = 3;

// if not on page 1, don't show back links
if ($currentpage > 1) {
   // show << link to go back to page 1
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
   // get previous page num
   $prevpage = $currentpage - 1;
   // show < link to go back to 1 page
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> ";
} // end if 

// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
   // if it's a valid page number...
   if (($x > 0) && ($x <= $totalpages)) {
      // if we're on current page...
      if ($x == $currentpage) {
         // 'highlight' it but don't make a link
         echo " [<b>$x</b>] ";
      // if not current page...
      } else {
         // make it a link
         echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
      } // end else
   } // end if 
} // end for

// if not on last page, show forward and last page links        
if ($currentpage != $totalpages) {
   // get next page
   $nextpage = $currentpage + 1;
    // echo forward link for next page 
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> ";
   // echo forward link for lastpage
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> ";
} // end if
/****** end build pagination links ******/
?><br>

// FORM
<body>
<form name="StringyChat_form" method="POST" action="<? echo $_SERVER['REQUEST_URI']; ?>">
      <br>
      <input type="hidden" name="name" class="StringyChatFrm" value="<?php $name ?>" size="20" >
      <br>
      <i>Type your Message here...</i>:<br>
      <textarea name="message" class="StringyChatFrm" cols="20" rows="4"></textarea>
      <br>
      <input name="StringyChat_submit" class="StringyChatFrm" type="submit" value="Post Message">
    </form>
</body>


</html>

Link to comment
Share on other sites

there are two things to do to address re-submitting form data. the first one address preventing the data from being processed again. the second one is to make the 'user' experience better (i.e. prevent the browser from displaying any of the resubmit form data/expired page-form messages.)

 

1) each time you output the form, you need to produce a unique-random one-use 'token' that's put into a hidden form field and stored in a session variable. when the form is submitted, you test that the session variable exists, is not empty, and that it matches the value from the hidden form field to serve as a condition for even processing the form data. you clear the session variable in the form processing code, which causes the form processing code to skip processing any re-submission of the form data. this also helps to prevent a bot script/someone from requesting your form once and using it to keep submitting comments. they must actually receive your form with a new token value to be able to submit a comment.

 

2) after you have successfully processed the form data (inserted it into the database table), you need to do a header() redirect to the exact same url that the form submitted to. this will cause the last action in the browser for that url to be a GET request for the page and the browser won't attempt to resubmit the form data due to a refresh of the page or navigating to that url.

 

there are some things your current code needs to do that it isn't already doing. your form processing code needs to check that a post method form was submitted at all, so that the form processing code only runs if there is $_POST data and you need to validate that the required form fields are at least not empty. your current code will insert a row with an empty message field every time the page gets requested.

Link to comment
Share on other sites

there are two things to do to address re-submitting form data. the first one address preventing the data from being processed again. the second one is to make the 'user' experience better (i.e. prevent the browser from displaying any of the resubmit form data/expired page-form messages.)

 

1) each time you output the form, you need to produce a unique-random one-use 'token' that's put into a hidden form field and stored in a session variable. when the form is submitted, you test that the session variable exists, is not empty, and that it matches the value from the hidden form field to serve as a condition for even processing the form data. you clear the session variable in the form processing code, which causes the form processing code to skip processing any re-submission of the form data. this also helps to prevent a bot script/someone from requesting your form once and using it to keep submitting comments. they must actually receive your form with a new token value to be able to submit a comment.

 

2) after you have successfully processed the form data (inserted it into the database table), you need to do a header() redirect to the exact same url that the form submitted to. this will cause the last action in the browser for that url to be a GET request for the page and the browser won't attempt to resubmit the form data due to a refresh of the page or navigating to that url.

 

there are some things your current code needs to do that it isn't already doing. your form processing code needs to check that a post method form was submitted at all, so that the form processing code only runs if there is $_POST data and you need to validate that the required form fields are at least not empty. your current code will insert a row with an empty message field every time the page gets requested.

Ok So I went and added a session so my form as said above

<html>
<?php
define('TIMEZONE', 'Africa/Harare');
date_default_timezone_set(TIMEZONE);



// database connection info
$conn = mysql_connect('*****','**********','*********') or trigger_error("SQL", E_USER_ERROR);
$db = mysql_select_db('u506124311_cobus',$conn) or trigger_error("SQL", E_USER_ERROR);


// find out how many rows are in the table 
$sql = "SELECT COUNT(*) FROM StringyChat";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
$r = mysql_fetch_row($result);
$numrows = $r[0];

// number of rows to show per page
$rowsperpage = 20;
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);

// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
   // cast var as int
   $currentpage = (int) $_GET['currentpage'];
} else {
   // default page num
   $currentpage = 1;
} // end if

// if current page is greater than total pages...
if ($currentpage > $totalpages) {
   // set current page to last page
   $currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
   // set current page to first page
   $currentpage = 1;
} // end if

// the offset of the list, based on current page 
$offset = ($currentpage - 1) * $rowsperpage;






$ip = $_SERVER["REMOTE_ADDR"];
$name = $_SERVER["HTTP_X_MXIT_USERID_R"];
$msg = $_POST['message'];
$time = date("U");
$mxitid = $_SERVER["HTTP_X_MXIT_USERID_R"];
if(!isset($mxitid, $name ))
{
	$mxitid = "DEFAULT";
	$name = "SYSOP";

}



$sqli = "INSERT INTO StringyChat (StringyChat_ip, StringyChat_name, StringyChat_message, StringyChat_time, mxit_id)
VALUES ('$ip', '$name', '$msg', '$time', '$mxitid')";
$result = mysql_query($sqli, $conn) or trigger_error("SQL", E_USER_ERROR);




// get the info from the db 
$sql = "SELECT StringyChat_time, StringyChat_name, StringyChat_message FROM StringyChat ORDER BY id DESC LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);



function filterBadWords($str)
{
	
	
    $result1 = mysql_query("SELECT word FROM StringyChat_WordBan") or die(mysql_error()); 
    $replacements = ":-x";
    
    while($row = mysql_fetch_assoc($result1))
    {
          $str = eregi_replace($row['word'], str_repeat(':-x', strlen($row['word'])), $str);
    }  
    
    return $str;
}



// while there are rows to be fetched...
while ($list = mysql_fetch_assoc($result)) 
//while (($pmsg = $list['StringyChat_message'] == $bwords) ? ":-x" : $list['StringyChat_message'])
 {
   // echo data
   //echo ($pmsg = ($list['StringyChat_message'] == $bwords) ? ":-x" : $list['StringyChat_message'])

   print '<span style="color:#828282">' . '(' . date( 'D H:i:s', $list['StringyChat_time'] )  . ') ' . '</span>' . '<b>' . $list['StringyChat_name'] . '</b>' . ' : ' . filterBadWords($list['StringyChat_message']) . '<br />';
} 








// end while

/******  build the pagination links ******/
// range of num links to show
$range = 3;

// if not on page 1, don't show back links
if ($currentpage > 1) {
   // show << link to go back to page 1
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
   // get previous page num
   $prevpage = $currentpage - 1;
   // show < link to go back to 1 page
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> ";
} // end if 

// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
   // if it's a valid page number...
   if (($x > 0) && ($x <= $totalpages)) {
      // if we're on current page...
      if ($x == $currentpage) {
         // 'highlight' it but don't make a link
         echo " [<b>$x</b>] ";
      // if not current page...
      } else {
         // make it a link
         echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
      } // end else
   } // end if 
} // end for

// if not on last page, show forward and last page links        
if ($currentpage != $totalpages) {
   // get next page
   $nextpage = $currentpage + 1;
    // echo forward link for next page 
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> ";
   // echo forward link for lastpage
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> ";
} // end if
/****** end build pagination links ******/
?><br>
<?php
        /*** begin the session ***/
        session_start();

        /*** create the form token ***/
        $form_token = uniqid();

        /*** add the form token to the session ***/
        $_SESSION['form_token'] = $form_token;
?>

<body>
<form name="StringyChat_form" method="POST" action="<? echo $_SERVER['REQUEST_URI']; ?>">
      <br>
      <input type="hidden" name="name" class="StringyChatFrm" value="<?php $name ?>" size="20" >
      <br>
      <i>Type your Message here...</i>:<br>
      <textarea name="message" class="StringyChatFrm" cols="20" rows="4"></textarea>
      <br>
<input type="hidden" name="form_token" value="<?php echo $form_token; ?>" /><br>

      <input name="StringyChat_submit" class="StringyChatFrm" type="submit" value="Post Message">
    </form>
</body>


</html>

But now I'm receiving the error

 

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/u506124311/public_html/ag/page.php:2)

 

Link to comment
Share on other sites

session_start() must be used before you send anything else to the browser. it must be the first thing in your code on the page.

Ok so I moved it to the top of my script but still the same message

<html>
<?php

        /*** begin the session ***/
        session_start();

        /*** create the form token ***/
        $form_token = uniqid();

        /*** add the form token to the session ***/
        $_SESSION['form_token'] = $form_token;



define('TIMEZONE', 'Africa/Harare');
date_default_timezone_set(TIMEZONE);



// database connection info
$conn = mysql_connect('********','********','*********') or trigger_error("SQL", E_USER_ERROR);
$db = mysql_select_db('u506124311_cobus',$conn) or trigger_error("SQL", E_USER_ERROR);


// find out how many rows are in the table 
$sql = "SELECT COUNT(*) FROM StringyChat";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
$r = mysql_fetch_row($result);
$numrows = $r[0];

// number of rows to show per page
$rowsperpage = 20;
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);

// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
   // cast var as int
   $currentpage = (int) $_GET['currentpage'];
} else {
   // default page num
   $currentpage = 1;
} // end if

// if current page is greater than total pages...
if ($currentpage > $totalpages) {
   // set current page to last page
   $currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
   // set current page to first page
   $currentpage = 1;
} // end if

// the offset of the list, based on current page 
$offset = ($currentpage - 1) * $rowsperpage;






$ip = $_SERVER["REMOTE_ADDR"];
$name = $_SERVER["HTTP_X_MXIT_USERID_R"];
$msg = $_POST['message'];
$time = date("U");
$mxitid = $_SERVER["HTTP_X_MXIT_USERID_R"];
if(!isset($mxitid, $name ))
{
	$mxitid = "DEFAULT";
	$name = "SYSOP";

}



$sqli = "INSERT INTO StringyChat (StringyChat_ip, StringyChat_name, StringyChat_message, StringyChat_time, mxit_id)
VALUES ('$ip', '$name', '$msg', '$time', '$mxitid')";
$result = mysql_query($sqli, $conn) or trigger_error("SQL", E_USER_ERROR);




// get the info from the db 
$sql = "SELECT StringyChat_time, StringyChat_name, StringyChat_message FROM StringyChat ORDER BY id DESC LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);



function filterBadWords($str)
{
	
	
    $result1 = mysql_query("SELECT word FROM StringyChat_WordBan") or die(mysql_error()); 
    $replacements = ":-x";
    
    while($row = mysql_fetch_assoc($result1))
    {
          $str = eregi_replace($row['word'], str_repeat(':-x', strlen($row['word'])), $str);
    }  
    
    return $str;
}



// while there are rows to be fetched...
while ($list = mysql_fetch_assoc($result)) 
//while (($pmsg = $list['StringyChat_message'] == $bwords) ? ":-x" : $list['StringyChat_message'])
 {
   // echo data
   //echo ($pmsg = ($list['StringyChat_message'] == $bwords) ? ":-x" : $list['StringyChat_message'])

   print '<span style="color:#828282">' . '(' . date( 'D H:i:s', $list['StringyChat_time'] )  . ') ' . '</span>' . '<b>' . $list['StringyChat_name'] . '</b>' . ' : ' . filterBadWords($list['StringyChat_message']) . '<br />';
} 








// end while

/******  build the pagination links ******/
// range of num links to show
$range = 3;

// if not on page 1, don't show back links
if ($currentpage > 1) {
   // show << link to go back to page 1
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
   // get previous page num
   $prevpage = $currentpage - 1;
   // show < link to go back to 1 page
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> ";
} // end if 

// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
   // if it's a valid page number...
   if (($x > 0) && ($x <= $totalpages)) {
      // if we're on current page...
      if ($x == $currentpage) {
         // 'highlight' it but don't make a link
         echo " [<b>$x</b>] ";
      // if not current page...
      } else {
         // make it a link
         echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
      } // end else
   } // end if 
} // end for

// if not on last page, show forward and last page links        
if ($currentpage != $totalpages) {
   // get next page
   $nextpage = $currentpage + 1;
    // echo forward link for next page 
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> ";
   // echo forward link for lastpage
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> ";
} // end if
/****** end build pagination links ******/
?><br>

<body>
<form name="StringyChat_form" method="POST" action="<? echo $_SERVER['REQUEST_URI']; ?>">
      <br>
      <input type="hidden" name="name" class="StringyChatFrm" value="<?php $name ?>" size="20" >
      <br>
      <i>Type your Message here...</i>:<br>
      <textarea name="message" class="StringyChatFrm" cols="20" rows="4"></textarea>
      <br>
<input type="hidden" name="form_token" value="<?php echo $form_token; ?>" /><br>

      <input name="StringyChat_submit" class="StringyChatFrm" type="submit" value="Post Message">
    </form>
</body>


</html>

Link to comment
Share on other sites

Anything outside of the <?php ?> tags is considered output too.

 

The error will be triggered because of the <html> before the <?php

 

Modify your code so HTML is output after any business logic in your code.

Ok the error message is gone now but messages still get submitted with every refresh..

<?php        
/*** begin the session ***/
        session_start();

        /*** create the form token ***/
        $form_token = uniqid();

        /*** add the form token to the session ***/
        $_SESSION['form_token'] = $form_token;



define('TIMEZONE', 'Africa/Harare');
date_default_timezone_set(TIMEZONE);



// database connection info
$conn = mysql_connect('********','***********','***********') or trigger_error("SQL", E_USER_ERROR);
$db = mysql_select_db('u506124311_cobus',$conn) or trigger_error("SQL", E_USER_ERROR);


// find out how many rows are in the table 
$sql = "SELECT COUNT(*) FROM StringyChat";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
$r = mysql_fetch_row($result);
$numrows = $r[0];

// number of rows to show per page
$rowsperpage = 20;
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);

// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
   // cast var as int
   $currentpage = (int) $_GET['currentpage'];
} else {
   // default page num
   $currentpage = 1;
} // end if

// if current page is greater than total pages...
if ($currentpage > $totalpages) {
   // set current page to last page
   $currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
   // set current page to first page
   $currentpage = 1;
} // end if

// the offset of the list, based on current page 
$offset = ($currentpage - 1) * $rowsperpage;






$ip = $_SERVER["REMOTE_ADDR"];
$name = $_SERVER["HTTP_X_MXIT_USERID_R"];
$msg = $_POST['message'];
$time = date("U");
$mxitid = $_SERVER["HTTP_X_MXIT_USERID_R"];
if(!isset($mxitid, $name ))
{
	$mxitid = "DEFAULT";
	$name = "SYSOP";

}



$sqli = "INSERT INTO StringyChat (StringyChat_ip, StringyChat_name, StringyChat_message, StringyChat_time, mxit_id)
VALUES ('$ip', '$name', '$msg', '$time', '$mxitid')";
$result = mysql_query($sqli, $conn) or trigger_error("SQL", E_USER_ERROR);




// get the info from the db 
$sql = "SELECT StringyChat_time, StringyChat_name, StringyChat_message FROM StringyChat ORDER BY id DESC LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);



function filterBadWords($str)
{
	
	
    $result1 = mysql_query("SELECT word FROM StringyChat_WordBan") or die(mysql_error()); 
    $replacements = ":-x";
    
    while($row = mysql_fetch_assoc($result1))
    {
          $str = eregi_replace($row['word'], str_repeat(':-x', strlen($row['word'])), $str);
    }  
    
    return $str;
}



// while there are rows to be fetched...
while ($list = mysql_fetch_assoc($result)) 
//while (($pmsg = $list['StringyChat_message'] == $bwords) ? ":-x" : $list['StringyChat_message'])
 {
   // echo data
   //echo ($pmsg = ($list['StringyChat_message'] == $bwords) ? ":-x" : $list['StringyChat_message'])

   print '<span style="color:#828282">' . '(' . date( 'D H:i:s', $list['StringyChat_time'] )  . ') ' . '</span>' . '<b>' . $list['StringyChat_name'] . '</b>' . ' : ' . filterBadWords($list['StringyChat_message']) . '<br />';
} 








// end while

/******  build the pagination links ******/
// range of num links to show
$range = 3;

// if not on page 1, don't show back links
if ($currentpage > 1) {
   // show << link to go back to page 1
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
   // get previous page num
   $prevpage = $currentpage - 1;
   // show < link to go back to 1 page
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> ";
} // end if 

// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
   // if it's a valid page number...
   if (($x > 0) && ($x <= $totalpages)) {
      // if we're on current page...
      if ($x == $currentpage) {
         // 'highlight' it but don't make a link
         echo " [<b>$x</b>] ";
      // if not current page...
      } else {
         // make it a link
         echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
      } // end else
   } // end if 
} // end for

// if not on last page, show forward and last page links        
if ($currentpage != $totalpages) {
   // get next page
   $nextpage = $currentpage + 1;
    // echo forward link for next page 
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> ";
   // echo forward link for lastpage
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> ";
} // end if
/****** end build pagination links ******/
?><br>
<html>
<body>
<form name="StringyChat_form" method="POST" action="<? echo $_SERVER['REQUEST_URI']; ?>">
      <br>
      <input type="hidden" name="name" class="StringyChatFrm" value="<?php $name ?>" size="20" >
      <br>
      <i>Type your Message here...</i>:<br>
      <textarea name="message" class="StringyChatFrm" cols="20" rows="4"></textarea>
      <br>
<input type="hidden" name="form_token" value="<?php echo $form_token; ?>" /><br>

      <input name="StringyChat_submit" class="StringyChatFrm" type="submit" value="Post Message">
    </form>
</body>


</html>

Edited by cobusbo
Link to comment
Share on other sites

That is because you only generate a new token. You fail to even check to see if the token is valid when the form is submitted. You need to re-read mac_gyver post again.

 

Ok I checked the token but seems like I'm still doing something wrong

<?php
        /*** begin the session ***/
        session_start();

        /*** create the form token ***/
        $form_token = uniqid();

        /*** add the form token to the session ***/
        $_SESSION['form_token'] = $form_token;



define('TIMEZONE', 'Africa/Harare');
date_default_timezone_set(TIMEZONE);



// database connection info
$conn = mysql_connect('********','*********','***********') or trigger_error("SQL", E_USER_ERROR);
$db = mysql_select_db('u506124311_cobus',$conn) or trigger_error("SQL", E_USER_ERROR);


// find out how many rows are in the table 
$sql = "SELECT COUNT(*) FROM StringyChat";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
$r = mysql_fetch_row($result);
$numrows = $r[0];

// number of rows to show per page
$rowsperpage = 20;
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);

// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
   // cast var as int
   $currentpage = (int) $_GET['currentpage'];
} else {
   // default page num
   $currentpage = 1;
} // end if

// if current page is greater than total pages...
if ($currentpage > $totalpages) {
   // set current page to last page
   $currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
   // set current page to first page
   $currentpage = 1;
} // end if

// the offset of the list, based on current page 
$offset = ($currentpage - 1) * $rowsperpage;



   if(!isset($_POST['message'], $_POST['form_token'], $_SESSION['form_token']))
        {
                $message = 'Invalid Submission';
        }
        /*** check the form tokens match ***/
        elseif($_POST['form_token'] != $_SESSION['form_token'])
        {
                $message = 'Access denied';
        }




$ip = $_SERVER["REMOTE_ADDR"];
$name = $_SERVER["HTTP_X_MXIT_USERID_R"];
$msg = $_POST['message'];
$time = date("U");
$mxitid = $_SERVER["HTTP_X_MXIT_USERID_R"];
if(!isset($mxitid, $name ))
{
	$mxitid = "DEFAULT";
	$name = "SYSOP";

}



$sqli = "INSERT INTO StringyChat (StringyChat_ip, StringyChat_name, StringyChat_message, StringyChat_time, mxit_id)
VALUES ('$ip', '$name', '$msg', '$time', '$mxitid')";
$result = mysql_query($sqli, $conn) or trigger_error("SQL", E_USER_ERROR);




// get the info from the db 
$sql = "SELECT StringyChat_time, StringyChat_name, StringyChat_message FROM StringyChat ORDER BY id DESC LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);



function filterBadWords($str)
{
	
	
    $result1 = mysql_query("SELECT word FROM StringyChat_WordBan") or die(mysql_error()); 
    $replacements = ":-x";
    
    while($row = mysql_fetch_assoc($result1))
    {
          $str = eregi_replace($row['word'], str_repeat(':-x', strlen($row['word'])), $str);
    }  
    
    return $str;
}



// while there are rows to be fetched...
while ($list = mysql_fetch_assoc($result)) 
//while (($pmsg = $list['StringyChat_message'] == $bwords) ? ":-x" : $list['StringyChat_message'])
 {
   // echo data
   //echo ($pmsg = ($list['StringyChat_message'] == $bwords) ? ":-x" : $list['StringyChat_message'])

   print '<span style="color:#828282">' . '(' . date( 'D H:i:s', $list['StringyChat_time'] )  . ') ' . '</span>' . '<b>' . $list['StringyChat_name'] . '</b>' . ' : ' . filterBadWords($list['StringyChat_message']) . '<br />';
} 

else
        {

                /*** unset the form token in the session ***/
                unset( $_SESSION['form_token']);
        }






// end while

/******  build the pagination links ******/
// range of num links to show
$range = 3;

// if not on page 1, don't show back links
if ($currentpage > 1) {
   // show << link to go back to page 1
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
   // get previous page num
   $prevpage = $currentpage - 1;
   // show < link to go back to 1 page
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> ";
} // end if 

// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
   // if it's a valid page number...
   if (($x > 0) && ($x <= $totalpages)) {
      // if we're on current page...
      if ($x == $currentpage) {
         // 'highlight' it but don't make a link
         echo " [<b>$x</b>] ";
      // if not current page...
      } else {
         // make it a link
         echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
      } // end else
   } // end if 
} // end for

// if not on last page, show forward and last page links        
if ($currentpage != $totalpages) {
   // get next page
   $nextpage = $currentpage + 1;
    // echo forward link for next page 
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> ";
   // echo forward link for lastpage
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> ";
} // end if
/****** end build pagination links ******/
?><br>
<html>
<body>
<form name="StringyChat_form" method="POST" action="<? echo $_SERVER['REQUEST_URI']; ?>">
      <br>
      <input type="hidden" name="name" class="StringyChatFrm" value="<?php $name ?>" size="20" >
      <br>
      <i>Type your Message here...</i>:<br>
      <textarea name="message" class="StringyChatFrm" cols="20" rows="4"></textarea>
      <br>
<input type="hidden" name="form_token" value="<?php echo $form_token; ?>" /><br>

      <input name="StringyChat_submit" class="StringyChatFrm" type="submit" value="Post Message">
    </form>
</body>


</html>

I'm getting error

 

Parse error: syntax error, unexpected T_ELSE in /home/u506124311/public_html/ag/page.php on line 124

 

Link to comment
Share on other sites

I would change this area

if(!isset($_POST['message'], $_POST['form_token'], $_SESSION['form_token']))
        {
                $message = 'Invalid Submission';
        }
        /*** check the form tokens match ***/
        elseif($_POST['form_token'] != $_SESSION['form_token'])
        {
                $message = 'Access denied';
        }

to something like

$message = 'Invalid Submission';
if(isset($_POST['message']) && isset($_POST['form_token']) && isset($_SESSION['form_token'])) {

    if($_POST['form_token'] == $_SESSION['form_token']){

        if(trim($_POST['message']) != ''){
        $message = trim($_POST['message']);
        }else{
        $message = 'Empty Submission';
        }
        
    }else{
        $message = 'Access denied';
    }
        
}
Link to comment
Share on other sites

Now that you have a variable $message, that's what you should be using and check for the sql insert.

 

remove $msg = $_POST['message'];

//Do check and only insert if is a good message.
if($message != 'Invalid Submission' || $message != 'Empty Submission' || $message != 'Access denied'){

//should be making inserts safe
$message = mysql_real_escape_string($message);

$sqli = "INSERT INTO StringyChat (StringyChat_ip, StringyChat_name, StringyChat_message, StringyChat_time, mxit_id)
VALUES ('$ip', '$name', '$message', '$time', '$mxitid')";
$result = mysql_query($sqli, $conn) or trigger_error("SQL", E_USER_ERROR);
}
Edited by QuickOldCar
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.