...

View Full Version : Server side validation



taffd
07-24-2007, 11:45 AM
Hi,
I built my site with dreamweaver, with mysql and php that was pre-installed by my hosting co., so I only have a basic grasp of php. I've been through various tutorials on the web and tried to fashion server side validation for my forms but haven't been able to make it work. The code may have even been correct and I've put it in the wrong place on the page, I just don't know.
Can anybody offer some help on this please.

You can contact me by replying to this thread or by email at rdaine@btinternet.com

Thank you in advance.

PS. My comments page (code shown below) has one text area, for comments. The specific validation I'm after is - If a user clicks submit without entering comment or if an attempt is made to enter code, I want the page to reload but without entering the input into the database. I have spent the past 24 hours playing with preg_match on a test page but regardless of whether the page reloads properly, the input is always submitted to the database.

_Aerospace_Eng_
07-24-2007, 11:49 AM
No one is going to contact you by email just for you to respond. I'll just post here though I'm not sure how much help you are expecting to receive when you haven't posted any of your code. If its one on one help you are after then you may want to post in the paid work offers forum because I doubt anyone is going to give you one on one help for nothing.

taffd
07-24-2007, 02:09 PM
Thank you for your reply.
As a newcomer to this forum I am unsure of the protocol. Please consider me suitably chastised.
I had intended to post my code when and if somebody responded positively and will do so later today.
I also hoped that any discussion relating to validation would be available to all here so that others could benefit. I posted my email address because I noted that others had done so.
If everybody wants paying for every piece of advice, I think I may be in the wrong forum.
Regards
Taffd

timgolding
07-24-2007, 02:20 PM
As _Aerospace_Eng_ suggest we can't help if we don't know what we are to help with

c_and13_
07-24-2007, 05:51 PM
everyones happy to help when we know what to help with...even if theyre just a noob like me....


dont feel bad, id have posted without code too - but now i know :p

taffd
07-24-2007, 06:42 PM
Okay folks, here is the code for my comments page. The page itself is available at http://www.myverdict.net/HTML/comments.php.
The code I am after is to validate the comment text area. I want users to be able to input only text, numbers 1-9 and some punctuation. ie. ? , . ' and carriage return. I understand it's something to do with pregmatch function and errors, but I have't been able to succeed. I have no examples of the code I've tried. (The long lines of ******** are to hide my conections).


<?php require_once('../Connections/***************************.php'); ?>
<?php



function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
$theValue = (!get_magic_quotes_gpc()) ? addslashes($theValue) : $theValue;

switch ($theType) {
case "text":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
break;
case "date":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue;
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "comments")) {
$insertSQL = sprintf("INSERT INTO comments (comment, `day`, `month`, `year`) VALUES (%s, %s, %s, %s)",
GetSQLValueString($_POST['comment'], "text"),
GetSQLValueString($_POST['day'], "int"),
GetSQLValueString($_POST['month'], "text"),
GetSQLValueString($_POST['year'], "int"));

mysql_select_db($database_*****************, $*********************);
$Result1 = mysql_query($insertSQL, $****************************) or die(mysql_error());

$insertGoTo = "comments.php";
if (isset($_SERVER['QUERY_STRING'])) {
$insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
$insertGoTo .= $_SERVER['QUERY_STRING'];
}
header(sprintf("Location: %s", $insertGoTo));
}

mysql_select_db($database_*********************, $************************);
$query_currentdate = "SELECT DAYNAME(NOW() ), DAYOFMONTH(NOW() ), MONTHNAME(NOW() ), YEAR(NOW() )";
$currentdate = mysql_query($query_currentdate, $******************************) or die(mysql_error());
$row_currentdate = mysql_fetch_assoc($currentdate);
$totalRows_currentdate = mysql_num_rows($currentdate);

mysql_select_db($database_**************************, $*************************);
$query_comments = "SELECT comment, `day`, `month`, `year` FROM comments";
$comments = mysql_query($query_comments, $********************) or die(mysql_error());
$row_comments = mysql_fetch_assoc($comments);
$totalRows_comments = mysql_num_rows($comments);
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><!-- InstanceBegin template="/Templates/master.dwt" codeOutsideHTMLIsLocked="false" -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<!-- InstanceBeginEditable name="doctitle" -->
<title>comments</title>
<!-- InstanceEndEditable --><!-- InstanceBeginEditable name="head" -->
<meta name="Description" content="Ask questions, put forward arguments, vote or change vote on issues that concern you, from international to local level. See what your politicians think." />
<style type="text/css">
<!--
.style2 {font-size: 10px}
-->
</style>
<script type="text/javascript">
<!--
function MM_findObj(n, d) { //v4.01
var p,i,x; if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_validateForm() { //v4.0
var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
if (val) { nm=val.name; if ((val=val.value)!="") {
if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
} else if (test!='R') { num = parseFloat(val);
if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
min=test.substring(8,p); max=test.substring(p+1);
if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
} } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
} if (errors) alert('The following error(s) occurred:\n'+errors);
document.MM_returnValue = (errors == '');
}
//-->
</script>
<!-- InstanceEndEditable -->
<style type="text/css">
<!--
body,td,th {font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 14px;
color: #000000;}
a:link {text-decoration: none;
color: #0000FF;}
a:visited {
text-decoration: none;
color: #0000FF;
}
a:hover {text-decoration: underline;
color: #0000FF;}
a:active {text-decoration: none;}
a {
font-size: 10px;
}
.style1 {
font-size: 10px;
font-weight: bold;
font-family: Verdana, Arial, Helvetica, sans-serif;
}
.butt {
font-family: Geneva, Arial, Helvetica, sans-serif;
font-size: 14px;
font-weight: normal;
color: #000000;
background-color: #CCCCFF;
}
.butt2 {
font-family: Geneva, Arial, Helvetica, sans-serif;
font-size: 10px;
font-weight: normal;
color: #000000;
background-color: #CCCCFF;
}
.style2 {
}
-->
</style>
</head>
<body bgcolor="#FFFFFF">
<table width="100%" border="0" cellpadding="2" cellspacing="1">
<td width="58%" valign="top"><img src="../Assets/images/logo1.jpg" alt="myverdict_logo" width="435" height="147" /></td>
<td width="42%"><!-- InstanceBeginEditable name="login" --><!-- InstanceEndEditable --></td>
</tr>
</table>
<table width="100%" border="0" cellspacing="1" cellpadding="2">
<!-- InstanceBeginEditable name="date/page_region" -->
<tr>
<td width="58%"><span class="style2"><?php echo $row_currentdate['DAYNAME(NOW() )']; ?>, <?php echo $row_currentdate['DAYOFMONTH(NOW() )']; ?> <?php echo $row_currentdate['MONTHNAME(NOW() )']; ?> <?php echo $row_currentdate['YEAR(NOW() )']; ?></span></td>
<td width="41%" align="left"><strong>Comments page </strong></td>
</tr>
<!-- InstanceEndEditable -->
</table>
<!-- InstanceBeginEditable name="EditRegion8" -->
<table width="100%" border="1" cellspacing="5" bordercolor="#FFFFFF">
<tr>
<td>&nbsp;</td>
</tr>
</table>

<!-- InstanceEndEditable -->
<table width="100%" border="0" cellspacing="10" cellpadding="2">

<tr>
<td width="140" valign="top"><table width="100%" border="0" cellspacing="1" cellpadding="2">
<tr>
<td><span class="style1">Navigation</span></td>
</tr>
<tr>
<td><a href="home.php">Home</a></td>
</tr>
<tr>
<td><a href="democracy/mypage.php">My page</a></td>
</tr>
<tr>
<td><a href="democracy.php">Questions</a></td>
</tr>
<tr>
<td><a href="about_us.php">About us</a></td>
</tr>
<tr>
<td><a href="comments.php">Comments</a></td>
</tr>
<tr>
<td><a href="democracy/mplogin.php">MP Login</a></td>
</tr>
<tr>
<td><a href="mailto:taffd@myverdict.net">Contact us</a></td>
</tr>
</table></td>
<td width="700" align="center" valign="top"><!-- InstanceBeginEditable name="content" -->Have you any comments regarding myVerdict? Good idea? Bad Idea? Suggestions for the site? Please complete the box below.<br />
<form action="<?php echo $editFormAction; ?>" method="post" name="comments" id="comments" onsubmit="MM_validateForm('comment','','R');return document.MM_returnValue">
<label>
<textarea name="comment" cols="53" rows="3" id="comment"></textarea>
</label>
<label>
<input name="Submit" type="submit" class="butt" value="Submit" />
<input name="day" type="hidden" id="day" value="<?php echo $row_currentdate['DAYOFMONTH(NOW() )']; ?>" />
</label>
<input name="month" type="hidden" id="month" value="<?php echo $row_currentdate['MONTHNAME(NOW() )'];
?>" />
<input name="year" type="hidden" id="year" value="<?php echo $row_currentdate['YEAR(NOW() )']; ?>" />
<input type="hidden" name="MM_insert" value="comments" />
</form>
<br /><table width="100%" border="1" cellpadding="2" cellspacing="1" bordercolor="#FFFFFF">
<tr>
<td width="75%" align="center" bordercolor="#000000" bgcolor="#CCCCFF" class="style1">Comments</td>
<td width="25%" align="center" bordercolor="#000000" bgcolor="#CCCCFF" class="style1">Date Submitted </td>
</tr>
<?php do { ?><?php if ($totalRows_comments > 0) { // Show if recordset not empty ?><tr>
<td bordercolor="#000000" class="style2"><div align="justify"><?php $text = $row_comments['comment'];
$text = str_replace("\n", "<br>", $text);
echo $text;
?>
</div>
</div></td>
<td align="center" bordercolor="#000000" class="style2"> <?php echo $row_comments['day']; ?> <?php echo $row_comments['month']; ?> <?php echo $row_comments['year']; ?></td>
</tr>
<?php } // Show if recordset not empty ?>
<?php } while ($row_comments = mysql_fetch_assoc($comments)); ?>
</table>


<!-- InstanceEndEditable --></td>
<td width="140" align="left" valign="top"><!-- InstanceBeginEditable name="content2" -->
<p class="style2"><strong>Tip.</strong><br />
We suggest you write in plain English. Not everybody understands webspeak. </p>
<!-- InstanceEndEditable --></td>
</tr>
</table>
<!-- InstanceBeginEditable name="content3" -->
<table width="100%" border="1" cellpadding="2" cellspacing="1" bordercolor="#FFFFFF">
<tr>
<td>&nbsp;</td>
</tr>
<tr>
<td>&nbsp;</td>
</tr>
</table>
<!-- InstanceEndEditable -->
</body>
<!-- InstanceEnd --></html>
<?php
mysql_free_result($currentdate);

mysql_free_result($comments);
?>

timgolding
07-24-2007, 07:30 PM
ok i think regular expressions is a good way to do this although I find them difficult to implement. If you are going to tackle it this way a good place to start would be to search for regular expressions with your search engine. There are other functions that may help if you want to avoid implementing a regex

taffd
07-24-2007, 08:40 PM
Dear TimGolding,
Did you post this to tell me you don't know how to do it and I should work it out myself?
Your strapline - 'You can not say you know how to do something, until you can teach it to someone else.' - and your answer, lead me to believe that you posted your answer to advertise your websites. You should proofread your homepage, by the way.

timgolding
07-25-2007, 02:34 PM
I was asking a question? Are you going to peruse the regex in which case i can't help or should i dig up some functions.

By the way i couldn't care less about that free webs page at the moment. Infact i'll remove it

You should encapsulate your code with PHP tags as stated in the forum rules.

taffd
07-25-2007, 02:48 PM
My apologies Tim. There was no need for what I said. I'm just frustrated.

The specific validation I'm after is - If a user clicks submit without entering comment or if an attempt is made to enter code, I want the page to reload but without entering the input into the database. I have spent the past 24 hours playing with preg_match on a test page but regardless of whether the page reloads properly, the input is always submitted to the database.

timgolding
07-25-2007, 03:18 PM
Np i didn't make myself clear anyway.

So you want to prevent users entering

a: ) nothing

b: ) codes of any kind

??????????

If so then you may be able to just completely strip the codes out with strip_tags() (http://uk.php.net/manual/en/function.strip-tags.php)
This literally does what it says on the box and completely strips out any HTML tags. Codes of other sorts e.g. PHP won't be a problem unless you are using eval to evaluate a string as PHP code ( something i strongly discourage). If you use this method then it even wouldn't matter if it got inserted to the database because the codes would have been removed.

As for the validating for no input I suggest just checking if the submitted data is null


$text=$_POST['text_area_name'];
$text=strip_tags($text);
if ($text==NULL || $text="")
{
// refresh page
}else
{
// update DB
}



If this is not suitable and you are adiment it has to just check for codes and refresh rather than just strip them out i may be able to dig up some character filtering functions.

taffd
07-25-2007, 05:14 PM
Thanks Tim,
Tried putting all of that code in a test page. Page does'nt load. I've obviously done something wrong.
Using - $text=$_POST['text_area_name'];
$text=strip_tags($text); - on its own, still put everything in the database, ( I tested with <?php.. rubbish...?>), but didn't output it. I'll play around with the other bit and get back to you.
Regards

timgolding
07-25-2007, 05:23 PM
did you get a error message? Its probably a formatting problem. I didn't get to test these codes. Well let us know how you get on.

taffd
07-25-2007, 07:16 PM
No, I just get a blank page. I took all the code out again and tried inputting a simple 'echo "hello" ' code line. It went into the database but didn't output. Yet talk about security suggests this is one of the ways hackers infiltrate a site. I remain perplexed.

oracleguy
07-25-2007, 07:22 PM
ok i think regular expressions is a good way to do this although I find them difficult to implement.

Slightly off topic but if you like using regular expressions but have trouble developing the patterns, there is a good website here (http://regexlib.com/) that I've used before when I just needed a pattern quickly. They have patterns for a lot of standard stuff.

taffd
07-25-2007, 10:13 PM
Thanks Tim. Will study the site and report back tomorrow.
Taffd



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum