•
•
•
•
What is DaniWeb IT Discussion Community?
You're currently browsing the PHP section within the Web Development category of DaniWeb, a massive community of 392,094 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 3,867 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our PHP advertiser: Lunarpages PHP Web Hosting
Views: 1179 | Replies: 9 | Solved
![]() |
| |
•
•
Join Date: Jul 2007
Posts: 110
Reputation:
Rep Power: 2
Solved Threads: 1
Hello everbody,
Despite some serious googling, viewing previous posts here and consulting the php manual, I am still unable to validate my user input.
If I can get one simple form to validate, I will be able to adapt the script accordingly to any other, so any help you can give will be much appreciated.
Problem.
I have a comments page. I want the user to be able to submit a comment, which if it validates will then be stored in a database, called and displayed on the 'comments' page.
At present, with no validation attempted, everything works fine.
What I want to do is make sure the user enters only text and punctuation.
Examples I've seen use preg_match. The php manual, however states that as soon as a match is found, checking of the 'subject' string stops and preg_match_all should be used. Therefore if I used
then a question mark ? at the end of a sentence, would still validate.
I have also seen
This would seem to say 'If the regex does not match '$field_name', return true.
I don't want to put too much in this first post, so tell me, am I correct so far.
Despite some serious googling, viewing previous posts here and consulting the php manual, I am still unable to validate my user input.
If I can get one simple form to validate, I will be able to adapt the script accordingly to any other, so any help you can give will be much appreciated.
Problem.
I have a comments page. I want the user to be able to submit a comment, which if it validates will then be stored in a database, called and displayed on the 'comments' page.
At present, with no validation attempted, everything works fine.
What I want to do is make sure the user enters only text and punctuation.
Examples I've seen use preg_match. The php manual, however states that as soon as a match is found, checking of the 'subject' string stops and preg_match_all should be used. Therefore if I used
if(preg_match("/[^a-zA-Z0-9\.\ ]+$/",$field_name))
return TRUE;
else
return FALSE;I have also seen
if(!preg_match("/[^a-zA-Z0-9\.\ ]+$/",$field_name))
return TRUE;
else
return FALSE;I don't want to put too much in this first post, so tell me, am I correct so far.
•
•
Join Date: Jul 2007
Posts: 110
Reputation:
Rep Power: 2
Solved Threads: 1
Hello again,
Firstly I'll provide the existing code for my comments page. The page can be found here
Now, for the purposes of this question, I only wish to validate the comment text area of the form. I want to allow text, punctuation and a few special characters.
The code should start something like below.
As I understand the php manual, if I use preg_match, it would return true as soon as it found a match and would not check the whole of the subject string.
Am I correct so far.
Firstly I'll provide the existing code for my comments page. The page can be found here
<?php require_once('connection'); ?>
<?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_conn, $conn);
$Result1 = mysql_query($insertSQL, $conn) or die(mysql_error());
$insertGoTo = "comments.php";
if (isset($_SERVER['QUERY_STRING'])) {
$insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
$insertGoTo .= $_SERVER['QUERY_STRING'];
}
header(sprintf("Location: %s", $insertGoTo));
}
session_start(); ?>
<?php
mysql_select_db($database_conn, $conn);
$query_currentdate = "SELECT DAYNAME(NOW() ), DAYOFMONTH(NOW() ), MONTHNAME(NOW() ), YEAR(NOW() )";
$currentdate = mysql_query($query_currentdate, $taff2) or die(mysql_error());
$row_currentdate = mysql_fetch_assoc($currentdate);
$totalRows_currentdate = mysql_num_rows($currentdate);
mysql_select_db($database_conn, $conn);
$query_comments = "SELECT comment, `day`, `month`, `year` FROM comments";
$comments = mysql_query($query_comments, $conn) or die(mysql_error());
$row_comments = mysql_fetch_assoc($comments);
$totalRows_comments = mysql_num_rows($comments);
(Here is a section of code that checks if a user is logged in and if so, displays the comment form)
?><!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}
.style5 {
font-size: 12px;
}
.style6 {
color: #FF0000;
font-weight: bold;
}
-->
</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><a href="home.php" class="style5">Home</a> | <a href="music/about.php" class="style5">Music</a> | <a href="video/video_about.php" class="style5">Movie</a> | <a href="poetry/poems.php" class="style5">Poetry </a>| <a href="shortstory/shortstorylist.php" class="style5">Stories</a></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" -->
<p>Have you any comments regarding myverdict? Good idea? Bad Idea? Suggestions for the site? Please complete the box below.</p>
<p class="style6">You must be logged in to post a comment <br />
</p>
<?php if ($totalRows_userlogged > 0) { // Show if recordset not empty ?>
<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>
<?php } // Show if recordset not empty ?><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> </td>
</tr>
<tr>
<td> </td>
</tr>
</table>
<!-- InstanceEndEditable -->
</body>
<!-- InstanceEnd --></html>
<?php
mysql_free_result($currentdate);
mysql_free_result($comments);Now, for the purposes of this question, I only wish to validate the comment text area of the form. I want to allow text, punctuation and a few special characters.
The code should start something like below.
function check_field1($comment)
{
if(preg_match_all("/[^a-zA-Z0-9\.\-\,\'\£\$\ ]+$/",$comment))
return TRUE;
else
return FALSE;
}As I understand the php manual, if I use preg_match, it would return true as soon as it found a match and would not check the whole of the subject string.
Am I correct so far.
I dunno does the below make any difference?
php Syntax (Toggle Plain Text)
$string = 'This is a $gfd \' goo.d string £-$,'; if (preg_match("/[^A-Za-z0-9 .,-£$']/", $string)) { print 'string is NOT OK!'; } else { print 'string is OK!'; }
Last edited by iamthwee : Nov 18th, 2007 at 12:02 pm.
Member of: F-ugly code club
Join today don't delay!
Join today don't delay!
•
•
Join Date: Jul 2007
Posts: 110
Reputation:
Rep Power: 2
Solved Threads: 1
Thanks for your input Iamthwee, I've been experimenting with a form.php and an error.php page and I've just managed to make things start to work. Code so far
Next I've got to try sending the form to itself.
Will report back soon.
<?php
$comment=$_POST['comment'];
function check_field1($comment)
{
if(preg_match("/[^a-zA-Z0-9\$\£\,\.\'\(\)\ \R\?]+$/i",$comment))
return 0;
else
return 1;
}
$error=0; // check up variable
if(!check_field1($comment))
{
echo "Illegal input $comment in 'your comment'";
$error++; // $error=$error+1;
}
if($error == 0)
{
echo
"
The data you entred was correct, thank you!<p>
Your comment - $comment
";
}else{
echo "Number of errors: $error";
}
?>Next I've got to try sending the form to itself.
Will report back soon.
I mean have you tried my code?
You might also need to use the function:-
htmlspecialchars
http://ific.uv.es/informatica/manual...cialchars.html
along with n12br()
If you are echoing that out to a browser in html.
You might also need to use the function:-
htmlspecialchars
http://ific.uv.es/informatica/manual...cialchars.html
along with n12br()
If you are echoing that out to a browser in html.
Last edited by iamthwee : Nov 18th, 2007 at 1:19 pm.
Member of: F-ugly code club
Join today don't delay!
Join today don't delay!
•
•
Join Date: Jul 2007
Posts: 110
Reputation:
Rep Power: 2
Solved Threads: 1
Iamthwee,
No I haven't tried your code, though I can see no reason why it shouldn't be ok. As you can see by the code I posted, I've more or less grasped the syntax of preg_match.
While I can get it to work from one simple page to another(form and error pages), I am unable to adapt it to my comments page to do what I want.
ie. If the input is ok, I want it to be passed to my database. If not, I want the comment page, with form to be refreshed and an error message displayed, without the comment being input to the database.
Having posted my full comments page, I'm hoping that someone will be able to tell me how to adapt the code and where to put it, as everything I've tried so far hasn't worked.
No I haven't tried your code, though I can see no reason why it shouldn't be ok. As you can see by the code I posted, I've more or less grasped the syntax of preg_match.
While I can get it to work from one simple page to another(form and error pages), I am unable to adapt it to my comments page to do what I want.
ie. If the input is ok, I want it to be passed to my database. If not, I want the comment page, with form to be refreshed and an error message displayed, without the comment being input to the database.
Having posted my full comments page, I'm hoping that someone will be able to tell me how to adapt the code and where to put it, as everything I've tried so far hasn't worked.
Last edited by Taffd : Nov 18th, 2007 at 3:49 pm.
•
•
Join Date: Jul 2007
Posts: 110
Reputation:
Rep Power: 2
Solved Threads: 1
Despite various posts, in various forums, I am still unable to get my validation how I want it.
I've found the part of my page where I need to put the validation.
[code]$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "comments"))
Here is where I need to insert the validation code. First I need a function.
$comment=$_POST['comment'];
$redirecturl = "comments.php"
function check_field1($comment)
{
if(!preg_match("/[^a-zA-Z0-9\$\£\,\.\'\(\)\ \R\?]+$/i",$comment))
I'm not sure what I should put here
}
From here, if everything's ok, I want to enter the comment into the database
{
$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_conn, $conn);
$Result1 = mysql_query($insertSQL, $conn) or die(mysql_error());
$insertGoTo = "comments.php";
if (isset($_SERVER['QUERY_STRING'])) {
$insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
$insertGoTo .= $_SERVER['QUERY_STRING'];
}
header(sprintf("Location: %s", $insertGoTo));
}
If $comment doesn't validate, I want to return to the comment page, without inputting $comment into the database. For this, I believe I need something like
header ("Location: %s", $redirecturl);
exit;[/CODE]
Please can anybody suggest how to complete this
I've found the part of my page where I need to put the validation.
[code]$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "comments"))
Here is where I need to insert the validation code. First I need a function.
$comment=$_POST['comment'];
$redirecturl = "comments.php"
function check_field1($comment)
{
if(!preg_match("/[^a-zA-Z0-9\$\£\,\.\'\(\)\ \R\?]+$/i",$comment))
I'm not sure what I should put here
}
From here, if everything's ok, I want to enter the comment into the database
{
$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_conn, $conn);
$Result1 = mysql_query($insertSQL, $conn) or die(mysql_error());
$insertGoTo = "comments.php";
if (isset($_SERVER['QUERY_STRING'])) {
$insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
$insertGoTo .= $_SERVER['QUERY_STRING'];
}
header(sprintf("Location: %s", $insertGoTo));
}
If $comment doesn't validate, I want to return to the comment page, without inputting $comment into the database. For this, I believe I need something like
header ("Location: %s", $redirecturl);
exit;[/CODE]
Please can anybody suggest how to complete this
•
•
Join Date: Jul 2007
Posts: 110
Reputation:
Rep Power: 2
Solved Threads: 1
Thanks to all for your help, particularly iamthwee. Should have paid more attention to htmlspecialcharacters. Although I used htmlentities, the php manual description of htmlspecialcharacters would have given me one of the clues to my answer.
Although I will post a new thread showing the following code, I produce it here to finish off this thread.
I wanted to insert a form validation into a page written by dreamweaver. It only needed a simple regex to pick up the character "<", and redirect to the original form page if found. If not, I wanted the comment input to the database.
I'm not sure how elegant that is but it works.
Although I will post a new thread showing the following code, I produce it here to finish off this thread.
I wanted to insert a form validation into a page written by dreamweaver. It only needed a simple regex to pick up the character "<", and redirect to the original form page if found. If not, I wanted the comment input to the database.
$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "comments"))
{
$comment = htmlentities($_POST['comment']);
function check_field1($comment)
{
if (preg_match("/</", $comment))
{
return TRUE;
}
}
$error=0;
if(check_field1($comment))
{
$error++;
$insertGoTo = "comments.php";
if (isset($_SERVER['QUERY_STRING'])) {
$insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
$insertGoTo .= $_SERVER['QUERY_STRING'];
}
header(sprintf("Location: %s", $insertGoTo)); // $error=$error+1;
}
if($error == 0)
$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_connection, $connection);
$Result1 = mysql_query($insertSQL, $connection) or die(mysql_error());
$insertGoTo = "comments.php";
if (isset($_SERVER['QUERY_STRING'])) {
$insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
$insertGoTo .= $_SERVER['QUERY_STRING'];
}
header(sprintf("Location: %s", $insertGoTo));
}I'm not sure how elegant that is but it works.
![]() |
•
•
•
•
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
•
•
•
•
•
•
•
•
DaniWeb PHP Marketplace
Similar Threads
- Simple JavavScript needs email validation (JavaScript / DHTML / AJAX)
- PHP: Form Validation (PHP)
- uregnt need of form validation (JSP)
- sample code for form validation using ajax (JavaScript / DHTML / AJAX)
- .net validation/javascript conflict (ASP.NET)
- PHP Form Validation ??? (PHP)
- never learned by e.g. - its horrible form - help? (ColdFusion)
- help with creating form counter (PHP)
- form validation not working (JavaScript / DHTML / AJAX)
Other Threads in the PHP Forum
- Previous Thread: Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource
- Next Thread: checkbox array storage and retrieval



Hybrid Mode