Click to See Complete Forum and Search --> : [RESOLVED] Verifying before accessing form?
Blue1974
Apr 25th, 2010, 11:18 AM
I'm trying to use a verification before a user can access a form to help limit the amount of spam. I'm really lost on this one.
From what I've read in some of the other posts this method doesn't sound very effective but it's what I'm working with.
The code I have below generates the image that the user types to verify. I'm not sure why it's not first in the code but the description says to put it after the last else statement in the code.
}else{
echo "</select><br />";
$new_string;
$im = ImageCreate(144, 30);
$white = ImageColorAllocate($im, 255, 255, 255);
$black = ImageColorAllocate($im, 0, 0, 0);
srand((double)microtime()*1000000);
$string = md5(rand(0,9999));
$new_string = substr($string, 17, 5);
ImageFill($im, 0, 0, $black);
ImageString($im, 5, 50, 5, $new_string, $white);
ImagePNG($im, "verify.png");
echo " <img src=\"verify.png\" ><br />";
ImageDestroy($im);
echo "Please type the numbers from the image into the input box below <br />";
echo "<input type=\"hidden\" type=\"text\" name=\"new_string\" value=\"$random\">";
echo "<input name=\"random\" type=\"text\" value=\"\" ><font size=\"2\"><br />";
?>
<input type="submit" name="select" value="Select">
<input type="submit" name="insert" value="New Record">
<input type="submit" name="delete" value="Delete Record">
</form>
<?
}
?>
The $random variable holds the text which the end user typed which should match what was in the image generated. If they don't type anything and try to proceed they are reminded to type the image in the text box. If it's wrong then they keep rentering until correct. The characters in the image are regenerated with a different string on each try.
I'm not sure how this part of the code is suppose to work. The way it is now they are asked to retype the code before they have even entered it for the first time.
<?PHP
include "connect.php";
$random = trim($_POST[random]);
if ($_POST[new_string]!=$random){
echo "You must type the code from the black box";
} else {
if ($_POST[new_string]->is_valid) {
echo "You got it!";
} else {
echo "Please re-type the numbers from the image into the input box. <br />";
echo ImagePNG($im, "verify.png");
}
}
if($_POST['insert']){
//Create a form to enter new record to add to database.
echo "<form name =\"new\" action\"form5.php\" method=\"post\">
Insert data into boxes below:<br />
ISBN:<input type=\"text\" name=\"isbn\"><br />
Author:<input type=\"text\" name=\"author\"><br />
Title:<input type=\"text\" name=\"title\"><br />
Price:<input type=\"text\" name=\"price\"><br />
<input type=\"submit\" name=\"new\" value=\"Enter\">
</form>";
kows
Apr 25th, 2010, 01:14 PM
the code you posted didn't make much sense to me, either -- so I rewrote it.
the form (form.php):
<?php
//start a session
session_start();
//pessimistic start -- always show the form
$showform = true;
//have they submitted?
if($_SERVER['REQUEST_METHOD'] == "POST"){
//did they type the captcha correctly?
if($_SESSION['captcha'] == $_POST['captcha']){
//don't show the form
$showform = false;
echo "you entered the captcha correctly";
}else{
echo "you did not enter the captcha correctly";
}
}
//show the form
if($showform):
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<img src="image.php" /><br />
<input type="text" name="captcha" />
<br /><br />
<input type="submit" value="Submit" />
</form>
<?php endif; ?>
and the captcha image (image.php):
<?php
//start a session
session_start();
header("Content-type: image/png");
//hash the current time (md5 is 32 bit [32 characters long])
$hash = md5(time());
//length of string
$l = 5;
//get 5 random characters from this hash
$captcha = substr($hash, mt_rand(1, 25), $l);
$_SESSION['captcha'] = $captcha;
//dimensions
$w = 150;
$h = 30;
//font for imageString (1 - 5)
$font = 5;
//create a blank image
$image = imageCreate($w, $h);
//create colors
$colors = array();
$colors['fore'] = imageColorAllocate($image, mt_rand(0, 200), mt_rand(0, 200), mt_rand(200, 255));
$colors['text'] = imageColorAllocate($image, 0, 0, 0);
//image background
imageFill($image, 0, 0, $colors['fore']);
//number of vertical lines
$lines = 10;
//draw a bunch of vertical lines
for($i = 0; $i < 10; $i++){
$offsetX = $i * ($w / $lines);
imageLine($image, $offsetX, 0, $offsetX, $h, $colors['text']);
}
//font sizes
$fh = imageFontHeight($font);
$fw = imageFontWidth($font);
//width of a quadrant
$qw = ($w / $l);
//height of a quadrant
$qh = $h - $fh;
//draw the text one character at a time
for($i = 0; $i < $l; $i++){
$offsetX = $i * $qw;
imageString($image, $font, mt_rand($offsetX, $offsetX + $qw - $fw), mt_rand(0, $qh), $captcha[$i], $colors['text']);
}
//display, then destroy the image
imagePNG($image);
imageDestroy($image);
?>
hopefully my comments can help you understand what's going on -- if not, ask.
I would suggest creating these files and then running it to see how it works, too.
Blue1974
Apr 25th, 2010, 09:15 PM
Thanks, but what you've done has gone beyond me to even ask at this point.
Did you think th code I posted was too simple or not strong enough a deterrent to protect the form?
I'm guessing the code which I gave you that didn't make sense was the part that I tried to do. Since I didn't know what I was doing. The part of about generating the image was authentic though and was given to me to work with. It actually did generated an image with a sequence of characters.
It was explained to me that this line:
$new_string = substr($string, 17, 5);
pulled 5 characters from a string of random characters starting at the 17th character.
I can't remember what md5() referred to but the only line in my text that references it just says: Improving the crypt(), hash(), and md5() functionality, as well as improving the OpenSSL extension.
I have no idea what they are talking about.
I guess what your doing on this line is the same as line I printed above:
//get 5 random characters from this hash
$captcha = substr($hash, mt_rand(1, 25), $l);
You didn't like the method that was used in the example I posted?
I didn't have these lines of code in what I posted:
//start a session
session_start();
//pessimistic start -- always show the form
$showform = true;
Could I get by without these and just if your session_start() refers to connecting to the database or do I put my include statement above that?
Also, what did you mean by pessimistic start in your comment for that line of code?
kows
Apr 25th, 2010, 10:51 PM
session_start() is a function that starts a session. sessions are used for storing values temporarily on the server side (rather than on the client side using cookies), which is perfect for a captcha system.
the variable $showform is a boolean value just used to either show or hide the form. we have a "pessimistic start" because we have a negative outlook. this means that we don't initially think that the user has filled out the form properly, so we will always show the form until we decide that the form has been submitted correctly and should thus be hidden. the alternative to this would be to have an optimistic start -- assuming that the user has filled out the form properly until we discover that they have not. this is bad 1) because you should never trust input from your users, and 2) because it requires a bit of extra code, and programmers are lazy.
the code in your example that created the image was fine; no, I didn't like the way it was written though. I dislike seeing HTML emitted by echo/print, and I dislike having a lot of logical code alongside my mark-up. the code you're using is also useless for actual verification of a human user (which is the point of captcha in the first place). you can't create a captcha that has the secret code in a hidden input field. the point of captcha is to stop bots from submitting forms that send emails automatically; a bot could easily read your hidden captcha field and still submit your form. a bot could not do the same to my example, though I'm sure a well-written script that could read through a simple image could crack it.
the MD5() function creates a 32-bit, unique one way hash out of a string. this is commonly used for password encryption and often used as a hash to verify that you have downloaded an original file. yes, I was basically doing the same thing that they were, but instead of using a fixed value (they used 17), I used a random index to start my string. this could possibly provide a more "random" captcha.
it's possible that the code that didn't make sense was the part that you had created -- but it looked messy and I thought it would be better if I gave you a better written example to grasp the ideas of what's happening. the image creation is much more complex, sure -- but the form is much more simple and should be easier for you to grasp than their example (in my opinion).
let me know if you might have anymore questions!
BrianS
May 4th, 2010, 03:38 PM
You want a very easy way to verify as well as being effective?
Just use something like this:
"What is the first word in this sentence" __________
Simple, easy, and effective. If by chance it get's botted, just change it to something else. They will get tired of changing the bot before you get tired of changing a word.
TheBigB
May 4th, 2010, 06:22 PM
They will get tired of changing the bot before you get tired of changing a word.
You'd need an infinite source of little quizzes like those to prevent botting.
Manually setting a word each time is not really useful.
In 10 seconds a bot can flood an entire website.
But even if you use a dynamic word with a finite source a botter could build a list for that; call it a word cache.
Resulting that at some point the bot knows all the words.
If you don't think there are people who have the time to do this, I can assure you there are.
Blue1974
May 5th, 2010, 09:45 PM
Kows, the code I had was for demonstration. It doesn't sound like it would actually keep anyone or anything from getting through but it showed me that when $random which was the image string and user input which was new_string didn't match that you couldn't proceed.
I've got a session example not quite like your code. The only thing I've added to it is the form you helped me create. My auth.php page is where the session starts where I put my form at the bottom. If you aren't logged in then you are redirected to the auth.php page where you are asked to enter your user name and password. I haven't been able to access the mylogin.php so I'm not sure why I can't get the login form to display, just a white screen.
If it was working correctly, the line if (!$_SESSION['user'] || !$_SESSION['pass']) { acts like a gatekeeper if not not session user or not session password you keep getting sent back until you fill in the form properly in mylogin.php and then you are sent back to auth.php and would be allowed to pass to the form at the bottom. I was wondering if I have this set right to display the a form if the session variables are found to exist. I tried not to use the echo the whole form like is done in the mylogin.php.
I'm not sure if the problem is in auth.php or in mylogin.php. Do you see what is preventing the page from displaying? If I understand it correctly, I believe I should be seeing the loggin form from mylogin.php which is where I've been when I couldn't get past the gatekeeper in auth.php where the session started?
<?PHP
include "config_mylogin.php";
// Start the login session
session_start();
if (!$_SESSION['user'] || !$_SESSION['pass']) {
// What to do if the user hasn't logged in
// We'll just redirect them to the login page.
header('Location: mylogin.php');
die();
} else {
// If the session variables exist, check to see
// if the user has access.
//$db = mysql_connect('$database') or die ("Couldn't select the database");
$result = mysql_query("SELECT count(user_id) from users WHERE
userpass = '$_SESSION[pass]' AND username='$_SESSION[user]'") or die("Couldn't query the user-database.");
$num = mysql_result($result, 0);
if (!$num) {
// If the credentials didn't match,
// redirect the user to the login screen.
header('Location: mylogin.php');
die();
}
// All output text below this line will be displayed
// to the users that are authenticated.
?>
<html>
<head>
<style type = "text/css">
form fieldset {
margin-bottom: 8px;
background-color: beige;
}
form legend {
padding: 0 5px;
font-weight: bold;
}
form label {
display: inline-block;
line-height: 1.5em;
vertical-align: top;
color: green;
}
form fieldset ul {
margin: 0px;
padding: 0;
}
form fieldset li {
clear: both;
list-style: none;
padding: 5px;
margin: 0;
}
label {
width: 120px;
}
form span {color: red}
</style>
</head>
<body>
<p><span>*</span>Indicates required information</p>
<form>
<fieldset id='address'>
<legend>Contact</legend>
<ul class="form">
<li>
<label for="firstName">First name:<span>*</span></label>
<input type="text" id="firstName" name="firstName" tabindex="1" />
</li>
<li>
<label for="lastName">Last name:<span>*</span></label>
<input type="text" id="lastName" name="lastName" tabindex="2" />
</li>
<li>
<label for="email">Email:<span>*</span></label>
<input type="text" id="email" name="email" tabindex="3" />
</li>
<li>
<label for="dayPhone">Day phone:<span>*</span></label>
<input type="text" id="dayPhone" name="dayPhone" tabindex="4" />
</li>
<li>
<label for="nightPhone">Night phone:<span>*</span></label>
<input type="text" id="nightPhone" name="nightPhone" tabindex="5" />
</li>
<li>
<label for="cellPhone">Cell phone</label>
<input type="text" id="cellPhone" name="cellPhone" tabindex="6" />
</li>
</ul>
</fieldset>
<fieldset id="contact">
<legend>Address</legend>
<ul class="form">
<li>
<label for="address">Address1:<span>*</span></label>
<input type="text" id="address1" name="address1" tabindex="7" />
</li>
<li>
<label for="address2">Address2:</label>
<input type="text" id="address2" name="address2" tabindex="8" />
</li>
<li>
<label for="city">City:<span>*</span></label>
<input type="text" id="city" name="city" tabindex="9">
</li>
<li>
<label for="state">State:<span>*</span></label>
<input type="text" id="state" name="state" value="" maxlength="2" tabindex="10">
</li>
<li>
<label for="zip">Zip Code:<span>*</span></label>
<input type="text" id="zip" name="zip" maxlength="10" tabindex="11">
</li>
</ul>
</fieldset>
<fieldset id='feedback'>
<legend>Feedback</legend>
<label for="comments">Comments:</label>
<textarea id="comments" name="comments" rows="5" cols="50"></textarea>
</ul>
</fieldset>
<div id="buttons">
<input type="submit" name="submit" value="Submit Form">
<input type="reset" name="reset" class="reset" value="Reset">
</div>
</form>
</body>
</html>
<?PHP
}
?>
<?PHP
require ("config_mylogin.php");
// Add slashes to the username, and make a md5 checksum of the password.
$_POST['user'] = addslashes($_POST['user']);
$_POST['pass'] = md5($_POST['pass']);
$result = mysql_query("SELECT count(user_id) FROM users WHERE
userpass = '$_POST[pass]' AND username = '$_POST[user]'") or die ("Couldn't query the user-database.");
$num = mysql_result($result, 0);
if (!$num) {
// When the query didn't return anything,
// display the login form.
echo "
<head>
<style type = \"text/css\">
@import \"your_style_sheet.css\";
</style>
</head>
<body>
<div id = \"Layer1\">
<center>
<div id = \"Layer2\">
<table>
<tr align = \"right\">
<td colspan = \"2\">
<center><img src = \"your_image.jpg\"</center>
<form action = '$_SERVER[PHP_SELF]' method = 'post'>
<tr>
<td align = \"right\">
<font face = \"arial, helvectica\">User Login</font>
<td>
<tr>
<td align = \"right\">
<font face = \"arial, helvectica\">
Username:</font>
<td>
<font face = \"arial, helvectica\">
<input type = 'text' name = 'user'></font>
<tr>
<td align = \"right\">
<font face = \"arial, helvectica\">
<input type = 'password' name = 'pass'></font>
<tr>
<td>
<td>
<input type = 'submit' value = ' Login '>
</tr>
</table>
</center>
</form>
</div>
</div>
</body>";
} else {
// Start the login session
session_start();
// We've already added slashes and MD5'd the password
$_SESSION['user'] = $_POST['user'];
$_SESSION['pass'] = $_POST['pass'];
// All output text below this line will be displayed
// to the users that are authenticated. Since no text
// has been output yet, you could also use redirect
// the user to the next page using the header() function.
// header("Location: page2.php");
}
?>
kows
May 5th, 2010, 11:47 PM
yes, the if statement you pointed out is simply checking to make sure the session variables are set, and if not, it's redirecting to the other page. however, if nothing is showing up on this page, then it looks like you just have a syntax error and the script is dying before it gets to echo anything.
the one problem you might be having is that you're always querying the database to see if the submitted username/password match something in the database. but, what if the user hasn't even submitted the form? you don't even need to query the database if the user hasn't submitted the form. this should only produce warnings (if anything) because you're just looking for indexes in an array that just aren't set, but it's a good thing to note. you can check whether or not a form has been submitted by checking the value of the REQUEST_METHOD. like below:
if($_SERVER['REQUEST_METHOD'] == "POST"){
//the form has been submitted
}else{
//the form has not been submitted
}
I understand what you're doing is just a test and all, but you should still have some sort of verification that the form was even submitted before you try working with submitted data.
also, do you have the PHP directive display_errors on, and is error_reporting set appropriately (these are php.ini settings)? and try running the script without that long/ugly echo statement. and make sure it's including that file properly.
Blue1974
May 7th, 2010, 10:35 PM
ok Kows, I got my login form to display, thanks for your help. Once I get enter the session variables I think I'm set to be re-directed to my main form. I go to a blank screen so I'm not sure what is happening. Does the code on my form page look acceptable to display the form or is there more code that should be added to make it functional? What else should I be looking for for errors?
<?PHP
ini_set('display_errors', 'On');
error_reporting(E_ALL);
include "auth.php";
?>
<html>
<head>
<style type = "text/css">
form fieldset {
margin-bottom: 8px;
......
......
<input type="reset" name="reset" class="reset" value="Reset">
</div>
</form>
</body>
</html>
<?PHP
}
?>
kows
May 8th, 2010, 10:34 AM
if that's your script then you're going to have a syntax error. you have a closing curly brace ("}") at the end of the script but what you posted doesn't have any opening braces. you might be better off posting all of the code, unless there is only HTML missing.
are you not getting any errors? are you simply being shown a blank page? if so, then some of your actual logic -must- be missing. what's in the included file (auth.php)?
Blue1974
May 8th, 2010, 01:53 PM
Ok thanks, I've added the brace. Previous, no error messages but with the brace I'm getting an error statement.
Warning: mysql_connect() [function.mysql-connect]: Unknown MySQL server host '$database' (3) in /home/public_html/formproject/auth.php on line 18
Couldn't select the database.
The line 18 is this one:
$db = mysql_connect('$database') or die ("Couldn't select the database");
The auth.php looks like this:
<?PHP
include "config_mylogin.php";
// Start the login session
session_start();
if (!$_SESSION['user_name'] || !$_SESSION['pass']) {
// What to do if the user hasn't logged in
// We'll just redirect them to the login page.
header('Location: mylogin.php');
die();
} else {
// If the session variables exist, check to see
// if the user has access.
$db = mysql_connect('$database') or die ("Couldn't select the database");
$result = mysql_query("SELECT count(user_id) from users WHERE
pass = '$_SESSION[pass]' AND user_name='$_SESSION[user_name]'") or die("Couldn't query the user-database.");
$num = mysql_result($result, 0);
if (!$num) {
// If the credentials didn't match,
// redirect the user to the login screen.
header('Location: mylogin.php');
die();
}
}
// All output text below this line will be displayed
// to the users that are authenticated.
?>
TheBigB
May 8th, 2010, 04:24 PM
The function mysql_connect() (http://php.net/mysql_connect) basically requires 3 parameters.
First one is the host. If you're using xampp or something similar to work in a local environment it usually is "localhost".
Next one is the username. Default is "root".
And the last one is password, which usually is an empty string.
To select the database we use mysql_select_db() (http://php.net/manual/en/function.mysql-select-db.php).
It generally takes only one parameter - the database - when using a single persistent connection.
So the correct method to connect to the database would be.
mysql_connect("localhost", "root", "");
mysql_select_db($database)
There was also another little problem in your code.
mysql_connect('$database')
When you are only using a variable you don't need to enclose it in quotes.
So you would use the following
mysql_connect($database) // Notice that the quotes are gone
On another note, when encapsulating a variable inside a string you have to use double quotes "
When using single quotes it takes the text literally.
So the following would also work, but is not really necessary.
mysql_connect("$database")
For some more reference regarding mysql in php I recommend this short tutorial by dclamp.
http://www.vbforums.com/showthread.php?t=514989
Also take a look at a couple of other mysql functions in the PHP reference (http://php.net/manual/en/ref.mysql.php); experiment a little ;)
Blue1974
May 9th, 2010, 10:32 AM
Thanks for pointing these errors out.
So then this is the proper format?
$db = mysql_connect("localhost", "root", ""); or die ("Couldn't select the database");
mysql_select_db($database)
The format to connect in my connect file looks like this. So wouldn't I use the same commands?
$db = mysql_connect("localhost", "$dbuser", "$dbpass") or die("Couldn't connect to the database.");
mysql_select_db("$database") or die("Couldn't select the database");
I've experimented with it and wouldn't it make sense to set it up like this. It's not working since I get the error couldn't connect to the database.
<?PHP
include "config_mylogin.php";
// Start the login session
session_start();
if (!$_SESSION['user_name'] || !$_SESSION['pass']) {
// What to do if the user hasn't logged in
// We'll just redirect them to the login page.
header('Location: mylogin.php');
die();
} else {
// If the session variables exist, check to see
// if the user has access.
$dbuser = trim($_SESSION['user_name']);
$dbpass = trim($_SESSION['pass']);
$db = mysql_connect("localhost", "$dbuser", "$dbpass") or die("Couldn't connect to the database.");
mysql_select_db("$database") or die("Couldn't select the database");
$result = mysql_query("SELECT count(user_id) from users WHERE
pass = '$_SESSION[pass]' AND user_name='$_SESSION[user_name]'") or die("Couldn't query the user-database.");
$num = mysql_result($result, 0);
if (!$num) {
// If the credentials didn't match,
// redirect the user to the login screen.
header('Location: mylogin.php');
die();
}
}
// All output text below this line will be displayed
// to the users that are authenticated.
?>
TheBigB
May 9th, 2010, 11:00 AM
I'm not sure what behavior 'die()' has after setting a header, but I'd prefer to use 'exit()'.
You had the following:
$db = mysql_connect("localhost",$user,$password)
Which is correct if you assign your username and password to those variables.
If you are unsure what the username and password are use "root" and "" as I mentioned in the other post.
The problem here probably is the SQL.
"SELECT count(user_id) from users WHERE
pass = '$_SESSION[pass]' AND user_name='$_SESSION[user_name]'"
The '=' operator in SQL is solely for numerical comparison. When comparing with strings you want to use the 'LIKE' operator.
Also you can't encapsulate an associative array value. So you cant call $_SESSION[user_name] inside a string.
Instead you can assign them to individual variables which you already did.
So basically we can do the following:
"SELECT count(user_id) from users WHERE
pass LIKE '$dbpass' AND user_name LIKE '$dbuser'"
kows
May 9th, 2010, 11:36 AM
I'm not sure what behavior 'die()' has after setting a header, but I'd prefer to use 'exit()'.
die() (http://ca.php.net/manual/en/function.die.php) and exit() (http://ca.php.net/manual/en/function.exit.php) are equivalent. it doesn't matter which is used.
If you are unsure what the username and password are use "root" and "" as I mentioned in the other post.
it's bad practice to install MySQL with a blank root password; to suggest that it's "normal" for this to happen is a little silly.
The '=' operator in SQL is solely for numerical comparison. When comparing with strings you want to use the 'LIKE' operator.
this is completely wrong. the equal-to operator ("=") checks if something is equal to something else (case sensitive). the like operator ("LIKE") checks if something is similar to something else based on an expression (case insensitive, and allows for wildcards). it's wrong to suggest that the equals operator should only be used for numerals.
Also you can't encapsulate an associative array value. So you cant call $_SESSION[user_name] inside a string. Instead you can assign them to individual variables which you already did.
So basically we can do the following:
"SELECT count(user_id) from users WHERE
pass LIKE '$dbpass' AND user_name LIKE '$dbuser'"
this is also wrong. his string works perfectly fine as is; there is no reason to change it at all other than preference.
------
Blue1974:
your username and password for the database are not going to be set in your sessions. the sessions hold the username and password for the current user. $dbuser and $dbpass should be set to something other than your session variables. when you installed MySQL, you should have been able to set up an administrator account and password -- this is the username and password you would use to connect to your local MySQL server.
does the config_mylogin.php file not include your database's connection information? if not, what is in that file? generally, you should have a file that connects to the database that you simply include so that you don't need to have the connection information in every single file. even if this isn't the case, I'd still be interested in seeing what that file holds.
if your connection to the database is the issue (and config_mylogin.php contains that stuff), then this is the code you should be modifying for now. don't bother duplicating that code and putting it into this other file.
TheBigB
May 9th, 2010, 12:21 PM
Well that is embarrassing :blush::o
Never noticed exit produces the same results as die.
As for the LIKE thing, I've never encountered a situation yet where that was a problem.
That's what you get from trial-and-error learning :rolleyes:
it's bad practice to install MySQL with a blank root password; to suggest that it's "normal" for this to happen is a little silly.
When you work in a local development environment such as xampp those are the defaults and most people usually can't be bothered to change it in that case.
But I could've been clearer on that.
this is also wrong. his string works perfectly fine as is; there is no reason to change it at all other than preference.
I didn't know that was syntactically possible, but now that I think of it it actually makes sense.
Thanks for correcting me ;)
Blue1974
May 9th, 2010, 08:20 PM
thanks for the discussion about the correctness of the syntax.
kows, yes I've got the user_name and password set up for the mysql account.
It looks like this with my login information removed for the post.
<?PHP
$dbuser = 'my_user_id';
$dbpass = 'password';
$database = 'database_name';
$db = mysql_connect("localhost", "$dbuser", "$dbpass") or die("Couldn't connect to the database.");
mysql_select_db("$database") or die("Couldn't select the database");
?>
yes as far as I know my config_mylogin.php file has all the necessary information to connect to the database. I created the table for the user_id information and also a table for the form for the data I want to insert from the main form which.
So, your saying I don't want to repeat the connection process in this line where I was having the problem earlier?
$db = mysql_connect($database) or die ("Couldn't select the database");
I erased the variables and went back to how it was previous but still with the error on that line.
I would want to add the line of code underneath that references selecting the database?
mysql_select_db($database)
Is this what I was missing?
I added that code in so it looks like this now:
$db = mysql_connect($database) or die ("Couldn't select the database");
mysql_select_db($database)
Now the error is saying:
Parse error: syntax error, unexpected T_VARIABLE in /home/public_html/formproject/auth.php on line 21
Which is this line:
$result = mysql_query("SELECT count(user_id) from users WHERE
pass = '$_SESSION[pass]' AND user_name='$_SESSION[user_name]'") or die("Couldn't query the user-database.");
kows
May 9th, 2010, 10:37 PM
you do not want to add anything relating to database connection (mysql_connect, mysql_select_db) to any files other than the config_mylogin.php script.
I'm having way too much trouble following all of this and the changes you're making. please post all of the files that you have currently (with the filenames), so that I can actually see what you're doing. we'll go from there, and it'll be a lot easier. you're missing a semi-colon on the line with mysql_select_db(), though, but I don't have any idea if that's your problem out of context.
Blue1974
May 10th, 2010, 12:21 PM
Ok, I've got the login form displaying. Once I submit I get a blank page but no error messages. I should be directed to my main form. I did take out the statements that related to the database connection that you mentioned in the prevous post in the auth.php.
*UPDATE on this: I just tried loading the page again and after login I was directed to the main form. I'm not sure why it wasn't working earlier. Those two lines of code you told me to remove must have been the problem. THANK YOU! It's great to see it working!!!!!!!!!!!!!!!!!!!!!!!!!!!
That file looks like this now:
<?PHP
include "config_mylogin.php";
// Start the login session
session_start();
if (!$_SESSION['user_name'] || !$_SESSION['pass']) {
// What to do if the user hasn't logged in
// We'll just redirect them to the login page.
header('Location: mylogin.php');
die();
} else {
$result = mysql_query("SELECT count(user_id) from users WHERE
pass = '$_SESSION[pass]' AND user_name='$_SESSION[user_name]'") or die("Couldn't query the user-database.");
$num = mysql_result($result, 0);
if (!$num) {
// If the credentials didn't match,
// redirect the user to the login screen.
header('Location: mylogin.php');
die();
}
}
// All output text below this line will be displayed
// to the users that are authenticated.
?>
The page with the main form looks like this:
<?PHP
ini_set('display_errors', 'On');
error_reporting(E_ALL);
include "auth.php";
{
?>
<html>
<head>
<style type = "text/css">
form fieldset {
margin-bottom: 8px;
background-color: beige;
}
form legend {
padding: 0 5px;
font-weight: bold;
}
form label {
display: inline-block;
line-height: 1.5em;
vertical-align: top;
color: green;
}
form fieldset ul {
margin: 0px;
padding: 0;
}
form fieldset li {
clear: both;
list-style: none;
padding: 5px;
margin: 0;
}
label {
width: 120px;
}
form span {color: red}
</style>
<title>Form</title>
</head>
<body>
<h1>FormProject</h1>
<p><span>*</span>Indicates required information</p>
<form name='information' action ='' method='post'>
<fieldset id='address'>
<legend>Contact</legend>
<ul class="form">
<li>
<label for="firstName">First name:<span>*</span></label>
<input type="text" id="firstName" name="firstName" tabindex="1" />
</li>
<li>
<label for="lastName">Last name:<span>*</span></label>
<input type="text" id="lastName" name="lastName" tabindex="2" />
</li>
<li>
<label for="email">Email:<span>*</span></label>
<input type="text" id="email" name="email" tabindex="3" />
</li>
<li>
<label for="dayPhone">Day phone:<span>*</span></label>
<input type="text" id="dayPhone" name="dayPhone" tabindex="4" />
</li>
<li>
<label for="nightPhone">Night phone:<span>*</span></label>
<input type="text" id="nightPhone" name="nightPhone" tabindex="5" />
</li>
<li>
<label for="cellPhone">Cell phone</label>
<input type="text" id="cellPhone" name="cellPhone" tabindex="6" />
</li>
</ul>
</fieldset>
<fieldset id="contact">
<legend>Address</legend>
<ul class="form">
<li>
<label for="address">Address1:<span>*</span></label>
<input type="text" id="address1" name="address1" tabindex="7" />
</li>
<li>
<label for="address2">Address2:</label>
<input type="text" id="address2" name="address2" tabindex="8" />
</li>
<li>
<label for="city">City:<span>*</span></label>
<input type="text" id="city" name="city" tabindex="9">
</li>
<li>
<label for="state">State:<span>*</span></label>
<input type="text" id="state" name="state" value="" maxlength="2" tabindex="10">
</li>
<li>
<label for="zip">Zip Code:<span>*</span></label>
<input type="text" id="zip" name="zip" maxlength="10" tabindex="11">
</li>
</ul>
</fieldset>
<fieldset id='feedback'>
<legend>Feedback</legend>
<label for="comments">Comments:</label>
<textarea id="comments" name="comments" rows="5" cols="50"></textarea>
</ul>
</fieldset>
<div id="buttons">
<input type="submit" name="submit" value="Submit Form">
<input type="reset" name="reset" class="reset" value="Reset">
</div>
</form>
</body>
</html>
<?PHP
}
?>
kows
May 10th, 2010, 12:37 PM
is this all working properly now? or is there anything else you're having trouble with now?
Blue1974
May 11th, 2010, 06:05 PM
I tried to collect the the information variables and to display error messages if a required field is missing. If there is an error when I submit is the action to reload the page and display an error message at the top? The variables I'm using are displaying when I'm directed to the form. Do I have any of this right?
<?PHP
ini_set('display_errors', 'On');
error_reporting(E_ALL);
include "auth.php";
{
?>
<html>
<head>
<style type = "text/css">
form fieldset {
margin-bottom: 8px;
background-color: beige;
}
form legend {
padding: 0 5px;
font-weight: bold;
}
form label {
display: inline-block;
line-height: 1.5em;
vertical-align: top;
color: green;
}
form fieldset ul {
margin: 0px;
padding: 0;
}
form fieldset li {
clear: both;
list-style: none;
padding: 5px;
margin: 0;
}
label {
width: 120px;
}
form span {color: red}
</style>
<title>form</title>
</head>
<body>
<h1>Form Project</h1>
<?PHP
echo $_SESSION['message'];
$_SESSION['message'] = "";
?>
<a href=\"form.php\">Back</a>
<p><span>*</span>Indicates required information</p>
<form name='information' action ='form.php' method='post'>
<fieldset id='address'>
<legend>Contact</legend>
<ul class="form">
<li>
<label for="firstName">First name:<span>*</span></label>
<input type="text" value="$_SESSION['firstName']" id="firstName" name="firstName" tabindex="1" />
</li>
<li>
<label for="lastName">Last name:<span>*</span></label>
<input type="text" value="$_SESSION['lastName']" id="lastName" name="lastName" tabindex="2" />
</li>
<li>
<label for="email">Email:<span>*</span></label>
<input type="text" value="$_SESSION['email']" id="email" name="email" tabindex="3" />
</li>
<li>
<label for="dayPhone">Day phone:<span>*</span></label>
<input type="text" value="$_SESSION['dayPhone']" id="dayPhone" name="dayPhone" tabindex="4" />
</li>
<li>
<label for="nightPhone">Night phone:<span>*</span></label>
<input type="text" value="$_SESSION['nightPhone']" id="nightPhone" name="nightPhone" tabindex="5" />
</li>
<li>
<label for="cellPhone">Cell phone</label>
<input type="text" value="$_SESSION['cellPhone']" id="cellPhone" name="cellPhone" tabindex="6" />
</li>
</ul>
</fieldset>
<fieldset id="contact">
<legend>Address</legend>
<ul class="form">
<li>
<label for="address">Address1:<span>*</span></label>
<input type="text" value="$_SESSION['address1']" id="address1" name="address1" tabindex="7" />
</li>
<li>
<label for="address2">Address2:</label>
<input type="text" value="$_SESSION['address2']" id="address2" name="address2" tabindex="8" />
</li>
<li>
<label for="city">City:<span>*</span></label>
<input type="text" value="$_SESSION['city']" id="city" name="city" tabindex="9">
</li>
<li>
<label for="state">State:<span>*</span></label>
<input type="text" value="$_SESSION['state']" id="state" name="state" value="" maxlength="2" tabindex="10">
</li>
<li>
<label for="zip">Zip Code:<span>*</span></label>
<input type="text" value="$_SESSION['zip']" id="zip" name="zip" maxlength="10" tabindex="11">
</li>
</ul>
</fieldset>
<fieldset id='feedback'>
<legend>Feedback</legend>
<label for="comments">Comments:</label>
<textarea value="$_SESSION['comments']" id="comments" name="comments" rows="5" cols="50"></textarea>
</ul>
</fieldset>
<div id="buttons">
<input type="submit" name="submit" value="Submit Form">
<input type="reset" name="reset" class="reset" value="Reset">
</div>
</form>
</body>
</html>
<?PHP
if(!$_POST['firstName']){
$_SESSION['message'] .= "Please enter a first name. <br />";
$firstName = trim($_POST["firstName"]);
}
if(!$_POST['lastName']){
$_SESSION['message'] .= "Please enter a last name. <br />";
}
$lastName = trim($_POST["lastName"]);
if(!$_POST['email']){
$_SESSION['message'] .= "Please enter email. <br />";
}
$email = trim($_POST["email"]);
if(!$_POST['dayPhone']){
$_SESSION['message'] .= "Please enter day phone. <br />";
}
$dayPhone = trim($_POST["dayPhone"]);
if(!$_POST['nightPhone']){
$_SESSION['message'] .= "Please enter night phone. <br />";
}
$nightPhone = trim($_POST["nightPhone"]);
if(!$_POST['adddress1']){
$_SESSION['message'] .= "Please enter main address. <br />";
}
$address1 = trim($_POST["address1"]);
if(!$_POST['city']){
$_SESSION['message'] .= "Please enter city. <br />";
}
$city = trim($_POST["city"]);
if(!$_POST['state']){
$_SESSION['message'] .= "Please enter state. <br />";
}
$state = trim($_POST["state"]);
if(!$_POST['zip']){
$_SESSION['message'] .= "Please enter zipcode. <br />";
}
$zip = trim($_POST["zip"]);
$cellPhone = trim($_POST["cellPhone"]);
$address2 = trim($_POST["address2"]);
$comments = trim($_POST["comments"]);
}
?>
kows
May 11th, 2010, 06:26 PM
the logic to create the message doesn't need to be stored in a session (you're resetting it every page load), and this logic should be located when the script is loaded (and not after anything is printed). you should also be checking to make sure the form has been submitted before doing any of that stuff. like so:
<?php
// the form is always shown unless it was submitted and there were no errors
$showform = true;
if($_SERVER['REQUEST_METHOD'] == "POST"){
$message = "";
if(!$_POST['firstName']){
$message .= "Please enter a first name. <br />";
}
$firstName = trim($_POST["firstName"]);
if(!$_POST['lastName']){
$message .= "Please enter a last name. <br />";
}
$lastName = trim($_POST["lastName"]);
if(!$_POST['email']){
$message .= "Please enter email. <br />";
}
$email = trim($_POST["email"]);
if(!$_POST['dayPhone']){
$message .= "Please enter day phone. <br />";
}
$dayPhone = trim($_POST["dayPhone"]);
if(!$_POST['nightPhone']){
$message .= "Please enter night phone. <br />";
}
$nightPhone = trim($_POST["nightPhone"]);
if(!$_POST['adddress1']){
$message .= "Please enter main address. <br />";
}
$address1 = trim($_POST["address1"]);
if(!$_POST['city']){
$message .= "Please enter city. <br />";
}
$city = trim($_POST["city"]);
if(!$_POST['state']){
$message .= "Please enter state. <br />";
}
$state = trim($_POST["state"]);
if(!$_POST['zip']){
$message .= "Please enter zipcode. <br />";
}
$zip = trim($_POST["zip"]);
$cellPhone = trim($_POST["cellPhone"]);
$address2 = trim($_POST["address2"]);
$comments = trim($_POST["comments"]);
/* this is my code from here on */
if(!$messages){
$showform = false; // no errors occurred
}
/* end my code */
}
if($showform):
?>
<!-- your form would go here -->
<?php else: ?>
<!-- your "success" stuff would go here -->
<?php endif; ?>
I've added a flag variable called $showform that determines whether or not to show the form. if the form was valid (no errors), we set $showform to false so that we can display some sort of "success" message. otherwise, the form is shown like normal. we use $message instead of $_SESSION['message'] because, as I mentioned before, there is no reason to store this message in a session. you can simply use a variable as you process the form.
please let me know if none of this makes sense!
Blue1974
May 11th, 2010, 10:09 PM
Ok, so I don't need to have those session variables within the form. I noticed earlier when I was displaying the form they were showing up in the input fields. I knew something was wrong; I'll get those out of there. So your saying, the variables are created before we fill out the form and once the form is submitted the variables are filled in with their respective values? Where as, what I was attempting to do was create the variables after the form was already displayed and filled out. Do I have that right? Your saying, the successful statements are those when the if statements are true and the form wasn't filled out properly in those fields. The successful or true statment will give the error messages and send the user back to fill out the form once again or repopulate it.
So this is where I would display the message and send user back to fill out requred fields?
<?PHP
echo $['message'];
$['message'] = "";
?>
<a href=\"form.php\">Back</a>
<?PHP
endif;
}
?>
kows
May 11th, 2010, 10:37 PM
umm. the code you posted makes no sense (very bad syntax!), so you better check it the next time you post that! however, you're not completely understanding the concept of the form structure I created. the "sending back" is handled automatically with the $showform variable. the form is shown over and over again until it is submitted successfully -- there is no need for a link or whatever else. all you have to do (which I did not do) is display $message somewhere when the form is being shown ($showform is true), so like this or something:
<?php
/* validation code I placed in my earlier example goes here */
if($showform):
?>
<h1>my form</h1>
<?php
// if there are error messages, display them!
if($message){
echo $message;
}
?>
<form action="form.php" method="post">
<!-- your form -->
</form>
<?php else: ?>
<h1>successfully submitted!</h1>
<p>we'll get back to you.</p>
<?php endif; ?>
make more sense?
Blue1974
May 13th, 2010, 03:25 PM
Ok, either you show the form again or you continue and the form was submitted successfully. I think what I wasn't understanding is when the error messages get displayed when the fields aren't filled out properly? I've got the error messages stored in the $message variables. If no messages the form is submitted and you get the successs message otherwise the form is re-displayed. So would the error message appear at the top of the page and then the form underneath?
When I started I tried to put the form before the if statments checking for values. It just seeme like I was trying to check for something that didn't exist yet.
The way it is now. When in error the form is redisplayed but without filling in the fields with the previous values. How do you retain the values from the previous form to fill the values back in on the new form?
I tried it like this:
$firstName = mysql_real_escape_string($_POST['firstName']);
to store the field information.
and then when the form re-displays I tried to display values:
<label for="firstName">First name:<span>*</span></label>
<input type="text" id="firstName" value="<?PHP echo $firstName; ?>" name="firstName" tabindex="1" />
I tried to combine the auth.php where the session was started the form.php and combine the two files into one. I've also added the captcha. It works perfectly, the way you showed me but I'm kind of lost with the error messages. If there is an error we just display the form again but the user doesn't know what they did wrong.
When you get to the statement:
if($showform):
This is where I should have the my error statement and then put everything in a brackets, maybe starting like this:
<?PHP
if($showform) {
echo $message
?>
<html>
<head>
</head>
<body>
<h1>Form Project</h1>
<p><span>*</span>Indicates required information</p>
<form name='information' action ='form.php' method='POST'>
<fieldset id='address'>
<legend>Contact</legend>
<ul class="form">
<li>
<label for="firstName">First name:<span>*</span></label>
<input type="text" id="firstName" value="<?PHP echo $firstName; ?>" name="firstName" tabindex="1" />
</li>
...................
...................
I'm sure your thoroughly confused about what I just posted?
kows
May 13th, 2010, 04:09 PM
your error message should be displayed with the actual form. you're breaking the structure of valid HTML if you just echo out an error message as the first thing on the page. look at the example in my last post if you want to know what I mean. I check if $showform is true, and then echo some HTML (in this case, my <h1>). then, I check if $message is empty or not. if it is not empty, I display $message. then I display my actual form. the comments in my last post's example should be sufficient to show you how it should be structured.
as for displaying the old form submission's values again, what you're doing should be okay. however, you don't really need to use mysql_real_escape_string() for it. that's really only a function you should be using when you're placing data into the database. instead, you should be using htmlentities() to make sure that the value is displayed correctly (for example, double quotes in your string cannot be escaped in HTML, but they can be replaced with the equivalent HTML entity). so, you would do something like:
if(isset($_POST['firstName'])){
$firstName = htmlentities($_POST['firstName']);
}
but, if you plan on inserting $firstName into a database later as well, you might want to have two separate variables. I usually do something similar to the following, using arrays rather than just regular variables (I don't like repeating code, so I prefer to loop through things):
$mysql_safe = array(); // stores database-safe values
$html_safe = array() // stores html-safe values
foreach($_POST as $key => $value){
$mysql_safe[$key] = mysql_real_escape_string($value);
$html_safe[$key] = htmlentities($value);
}
then, in my form later on, I'd use the $html_safe array:
<input type="text" name="firstName" value="<?php if(isset($html_safe['firstName'])) echo $html_safe['firstName']; ?>" />
let me know if that doesn't make sense. remember that you don't have to use arrays, though.
Blue1974
May 13th, 2010, 09:35 PM
Sorry, I missed your directions in the other post. I think I've got the error messages in the right place now. I was getting them to display but they were all displaying even the one's that weren't suppose to be. I've had the code arranged quite few different ways, so it's not even displaying the error messages now. I'm not comfortable with the array but I tried to use what you put up. I know I'm just poking around in the dark. I don't know if I put the brackets in the right place or if I'm even implementing it in the right way. Right now, no matter how I fill out the form or not at all I get the message "Query 1 Failed!
BACK"
<?PHP
include "config_mylogin.php";
// Start the login session
session_start();
if (!$_SESSION['user_name'] || !$_SESSION['pass']) {
// What to do if the user hasn't logged in
// We'll just redirect them to the login page.
header('Location: mylogin.php');
die();
} else {
$result = mysql_query("SELECT count(user_id) from users WHERE
pass = '$_SESSION[pass]' AND user_name='$_SESSION[user_name]'") or die("Couldn't query the user-database.");
$num = mysql_result($result, 0);
if (!$num) {
// If the credentials didn't match,
// redirect the user to the login screen.
header('Location: mylogin.php');
die();
}
}
// All output text below this line will be displayed
// to the users that are authenticated.
// the form is always shown unless it was submitted and there were no errors
$showform = true;
if($_SERVER['REQUEST_METHOD'] == "POST"){
$mysql_safe = array(); // stores database-safe values
$html_safe = array(); // stores html-safe values
foreach($_POST as $key => $value){
$mysql_safe[$key] = mysql_real_escape_string($value);
$html_safe[$key] = htmlentities($value);
$message = "";
if(!isset($_POST['firstName'])){
$message .= "Please enter a first name. <br />";
}
$firstName = htmlentities($_POST['firstName']);
if(!isset($_POST['lastName'])){
$message .= "Please enter a last name. <br />";
}
$lastName = htmlentities($_POST['lastName']);
if(!isset($_POST['email'])){
$message .= "Please enter email. <br />";
}
$email = htmlentities($_POST['email']);
if(!isset($_POST['dayPhone'])){
$message .= "Please enter day phone. <br />";
}
$dayPhone = htmlentities($_POST['dayPhone']);
if(!isset($_POST['nightPhone'])){
$message .= "Please enter night phone. <br />";
}
$nightPhone = htmlentities($_POST['nightPhone']);
if(!isset($_POST['address1'])){
$message .= "Please enter main address. <br />";
}
$address1 = htmlentities($_POST['address1']);
if(!isset($_POST['city'])){
$message .= "Please enter city. <br />";
}
$city = htmlentities($_POST['city']);
if(!isset($_POST['state'])){
$message .= "Please enter state. <br />";
}
$state = htmlentities($_POST['state']);
if(!isset($_POST['zip'])){
$message .= "Please enter zipcode. <br />";
}
$zip = htmlentities($_POST['zip']);
$cellPhone = htmlentities($_POST['cellPhone']);
$address2 = htmlentities($_POST['address2']);
$comments = htmlentities($_POST['comments']);
}
/*Check to see if any errors occurred*/
if(!$message){
$showform = false; // no errors occurred
}
}
/*Display form */
if($showform):
?>
<html>
<head>
<style type = "text/css">
form fieldset {
margin-bottom: 8px;
background-color: beige;
}
form legend {
padding: 0 5px;
font-weight: bold;
}
form label {
display: inline-block;
line-height: 1.5em;
vertical-align: top;
color: green;
}
form fieldset ul {
margin: 0px;
padding: 0;
}
form fieldset li {
clear: both;
list-style: none;
padding: 5px;
margin: 0;
}
label {
width: 120px;
}
form span {color: red}
</style>
<title>form</title>
</head>
<body>
<h1>Form Project</h1>
<?php
// if there are error messages, display them!
if($message){
echo $message;
}
?>
<p><span>*</span>Indicates required information</p>
<form name='information' action ='form.php' method='POST' />
<fieldset id='address'>
<legend>Contact</legend>
<ul class="form">
<li>
<label for="firstName">First name:<span>*</span></label>
<input type="text" id="firstName" value="<?php if(isset($html_safe['firstName'])) echo $html_safe['firstName']; ?>" name="firstName" tabindex="1" />
</li>
<li>
<label for="lastName">Last name:<span>*</span></label>
<input type="text" id="lastName" value="<?php if(isset($html_safe['lastName'])) echo $html_safe['lastName']; ?>" name="lastName" tabindex="2" />
</li>
<li>
<label for="email">Email:<span>*</span></label>
<input type="text" id="email" value="<?php if(isset($html_safe['email'])) echo $html_safe['email']; ?>" name="email" tabindex="3" />
</li>
<li>
<label for="dayPhone">Day phone:<span>*</span></label>
<input type="text" id="dayPhone" value="<?php if(isset($html_safe['dayPhone'])) echo $html_safe['dayPhone']; ?>" name="dayPhone" tabindex="4" />
</li>
<li>
<label for="nightPhone">Night phone:<span>*</span></label>
<input type="text" id="nightPhone" value="<?php if(isset($html_safe['nightPhone'])) echo $html_safe['nightPhone']; ?>" name="nightPhone" tabindex="5" />
</li>
<li>
<label for="cellPhone">Cell phone</label>
<input type="text" id="cellPhone" value="<?php if(isset($html_safe['cellPhone'])) echo $html_safe['cellPhone']; ?>" name="cellPhone" tabindex="6" />
</li>
</ul>
</fieldset>
<fieldset id="contact">
<legend>Address</legend>
<ul class="form">
<li>
<label for="address">Address1:<span>*</span></label>
<input type="text" id="address1" value="<?php if(isset($html_safe['address1'])) echo $html_safe['address1']; ?>" name="address1" tabindex="7" />
</li>
<li>
<label for="address2">Address2:</label>
<input type="text" id="address2" value="<?php if(isset($html_safe['address2'])) echo $html_safe['address2']; ?>" name="address2" tabindex="8" />
</li>
<li>
<label for="city">City:<span>*</span></label>
<input type="text" id="city" value="<?php if(isset($html_safe['city'])) echo $html_safe['city']; ?>" name="city" tabindex="9" />
</li>
<li>
<label for="state">State:<span>*</span></label>
<input type="text" id="state" value="<?php if(isset($html_safe['state'])) echo $html_safe['state']; ?>" name="state" maxlength="2" tabindex="10" />
</li>
<li>
<label for="zip">Zip Code:<span>*</span></label>
<input type="text" id="zip" value="<?php if(isset($html_safe['zip'])) echo $html_safe['zip']; ?>" name="zip" maxlength="10" tabindex="11" />
</li>
</ul>
</fieldset>
<fieldset id='feedback'>
<legend>Feedback</legend>
<label for="comments">Comments:</label>
<textarea id="comments" value="comments" name="comments" rows="5" cols="50"></textarea>
</ul>
</fieldset>
<?php
/*Put in the Captcha for verification*/
$new_string;
$im = ImageCreate(144, 30);
$white = ImageColorAllocate($im, 255, 255, 255);
$black = ImageColorAllocate($im, 0, 0, 0);
srand((double)microtime()*1000000);
$string = md5(rand(0,9999));
$new_string = substr($string, 17, 5);
ImageFill($im, 0, 0, $black);
ImageString($im, 5, 50, 5, $new_string, $white);
ImagePNG($im, "verify.png");
echo " <img src=\"verify.png\" ><br />";
ImageDestroy($im);
echo "Please type the numbers from the image into the input box below. <br/>";
echo "<form name=\"information\" action=\"form.php\" method=\"post\">";
echo "<input type=\"hidden\" type=\"text\" name=\"new_string\" value=\"$new_string\">";
echo "<input type=\"text\" value=\"\" input name=\"random\"><font size=\"2\"><br /><br />";
echo "</select>";
?>
<div id="buttons">
<input type="submit" name="submit" value="Submit Form">
<input type="reset" name="reset" class="reset" value="Reset">
</div>
</form>
</body>
</html>
<?PHP
else:
if($_POST['submit']){
foreach($_POST as $key => $value) {
$query_1 = "INSERT into information values ('$mysql_safe[$key]')";
}
// $query_1 = "INSERT into information values('$_POST[firstName]','$_POST[lastName]','$_POST[address1]',$_POST[address2]', '$_POST[city]', '$_POST[state]', '$_POST[zip]', '$_POST[dayPhone]', '$_POST[nightPhone], '_POST[cellPhone]', '_POST[email]', '_POST[comments]')";
$result_1 = mysql_query($query_1) or die ("Query 1 Failed!<br /><a href=\"form.php\">BACK</a>");
if($query_1){
echo "Added -- " . mysql_affected_rows() . " fields to database";
}
}
?>
<h1>Successfully Submitted!</h1>
<p>We'll get back to you.</p>
<?PHP
endif;
?>
kows
May 13th, 2010, 10:51 PM
er.. you have all of your IF statements for validation inside of the foreach() loop I created. take them out. they are separate. you should also be away that because you're using the $html_safe and $mysql_safe arrays, you don't need to create the variables like $firstName and $lastName any longer -- you just need the code that checks if they're value. HOWEVER, you're only checking if they are set. $_POST['firstName'] will be set no matter what -- you want to check if it's EMPTY. change your function calls to empty() instead of !isset() (that's right, no more exclamation point). I apologize for not catching that previously!
the way you created the value attributes with the $html_safe array looks perfect.
however, you have a problem with the captcha stuff you're using. you are creating a new form (within your form), and you shouldn't be. get rid of the <form> tag near the captcha, and there should not be that </select> there either.
next, after your "else:" where you have the "success" message -- you don't need to check if $_POST['submit'] is set because you would never get to this point in the script if $showform was not true. $showform is only ever true when the form is valid. so, get rid of that if statement. next, the query you're creating there is doing nothing. you can't loop through the $_POST array and recreate the same variable over and over with just one value -- especially when you're not even telling the database what value you are inserting. there seems to be no point in trying to tell you the "easy" way of doing this with an array, so instead just recreate your original $query_1 by hand with the $mysql_safe values.
it's also sort of bad practice to insert into a database without specifying which fields you're inserting. if you ever change this database table, then your script may not work properly. you can specify the fields you're inserting and the other they will appear in by formatting your query like this:
INSERT INTO table (field1, field2, ...) VALUES('value1', 'value2', ...);
I hope that makes sense! keep trying!
Blue1974
May 14th, 2010, 10:50 PM
kows, if you get a chance, this is what I came up with if I followed your directions correctly. There is something wrong with the captcha. Sometimes it seems to work and other times it doesn't. More specifically, if you just plain don't type in the code I was able to submit to the database and if I would mistype it I would get the error query1 failed. I don't think I'm suppose to be entering the else to get that message.
Shouldn't this code stop the submission is the capthca in incorrect?
$random = trim($_POST[random]);
if ($_POST[new_string]!=$random) {
echo "You must type the code that's in the box.<br />";
echo "<a href=\"final.php\">BACK</a>";
}
<?PHP
include "config_mylogin.php";
// Start the login session
session_start();
if (!$_SESSION['user_name'] || !$_SESSION['pass']) {
// What to do if the user hasn't logged in
// We'll just redirect them to the login page.
header('Location: mylogin.php');
die();
} else {
$result = mysql_query("SELECT count(user_id) from users WHERE
pass = '$_SESSION[pass]' AND user_name='$_SESSION[user_name]'") or die("Couldn't query the user-database.");
$num = mysql_result($result, 0);
if (!$num) {
// If the credentials didn't match,
// redirect the user to the login screen.
header('Location: mylogin.php');
die();
}
}
// All output text below this line will be displayed
// to the users that are authenticated.
// the form is always shown unless it was submitted and there were no errors
$showform = true;
if($_SERVER['REQUEST_METHOD'] == "POST"){
$mysql_safe = array(); // stores database-safe values
$html_safe = array(); // stores html-safe values
foreach($_POST as $key => $value){
$mysql_safe[$key] = mysql_real_escape_string($value);
$html_safe[$key] = htmlentities($value);
}
$message = "";
if(empty($_POST['firstName'])){
$message .= "Please enter a first name. <br />";
}
if(empty($_POST['lastName'])){
$message .= "Please enter a last name. <br />";
}
if(empty($_POST['email'])){
$message .= "Please enter email. <br />";
}
if(empty($_POST['dayPhone'])){
$message .= "Please enter day phone. <br />";
}
if(empty($_POST['nightPhone'])){
$message .= "Please enter night phone. <br />";
}
if(empty($_POST['address1'])){
$message .= "Please enter main address. <br />";
}
if(empty($_POST['city'])){
$message .= "Please enter city. <br />";
}
if(empty($_POST['state'])){
$message .= "Please enter state. <br />";
}
if(empty($_POST['zip'])){
}
/*Check to see if any errors occurred*/
if(!$message){
$showform = false; // no errors occurred
}
}
/*Display form */
if($showform):
?>
<html>
<head>
<style type = "text/css">
form fieldset {
margin-bottom: 8px;
background-color: beige;
}
form legend {
padding: 0 5px;
font-weight: bold;
}
form label {
display: inline-block;
line-height: 1.5em;
vertical-align: top;
color: green;
}
form fieldset ul {
margin: 0px;
padding: 0;
}
form fieldset li {
clear: both;
list-style: none;
padding: 5px;
margin: 0;
}
label {
width: 120px;
}
form span {color: red}
</style>
<title>form</title>
</head>
<body>
<h1>Form Project</h1>
<?php
// if there are error messages, display them!
if($message){
echo $message;
}
?>
<p><span>*</span>Indicates required information</p>
<form name='information' action ='form.php' method='POST' />
<fieldset id='address'>
<legend>Contact</legend>
<ul class="form">
<li>
<label for="firstName">First name:<span>*</span></label>
<input type="text" id="firstName" value="<?php if(isset($html_safe['firstName'])) echo $html_safe['firstName']; ?>" name="firstName" tabindex="1" />
</li>
<li>
<label for="lastName">Last name:<span>*</span></label>
<input type="text" id="lastName" value="<?php if(isset($html_safe['lastName'])) echo $html_safe['lastName']; ?>" name="lastName" tabindex="2" />
</li>
<li>
<label for="email">Email:<span>*</span></label>
<input type="text" id="email" value="<?php if(isset($html_safe['email'])) echo $html_safe['email']; ?>" name="email" tabindex="3" />
</li>
<li>
<label for="dayPhone">Day phone:<span>*</span></label>
<input type="text" id="dayPhone" value="<?php if(isset($html_safe['dayPhone'])) echo $html_safe['dayPhone']; ?>" name="dayPhone" tabindex="4" />
</li>
<li>
<label for="nightPhone">Night phone:<span>*</span></label>
<input type="text" id="nightPhone" value="<?php if(isset($html_safe['nightPhone'])) echo $html_safe['nightPhone']; ?>" name="nightPhone" tabindex="5" />
</li>
<li>
<label for="cellPhone">Cell phone</label>
<input type="text" id="cellPhone" value="<?php if(isset($html_safe['cellPhone'])) echo $html_safe['cellPhone']; ?>" name="cellPhone" tabindex="6" />
</li>
</ul>
</fieldset>
<fieldset id="contact">
<legend>Address</legend>
<ul class="form">
<li>
<label for="address">Address1:<span>*</span></label>
<input type="text" id="address1" value="<?php if(isset($html_safe['address1'])) echo $html_safe['address1']; ?>" name="address1" tabindex="7" />
</li>
<li>
<label for="address2">Address2:</label>
<input type="text" id="address2" value="<?php if(isset($html_safe['address2'])) echo $html_safe['address2']; ?>" name="address2" tabindex="8" />
</li>
<li>
<label for="city">City:<span>*</span></label>
<input type="text" id="city" value="<?php if(isset($html_safe['city'])) echo $html_safe['city']; ?>" name="city" tabindex="9" />
</li>
<li>
<label for="state">State:<span>*</span></label>
<input type="text" id="state" value="<?php if(isset($html_safe['state'])) echo $html_safe['state']; ?>" name="state" maxlength="2" tabindex="10" />
</li>
<li>
<label for="zip">Zip Code:<span>*</span></label>
<input type="text" id="zip" value="<?php if(isset($html_safe['zip'])) echo $html_safe['zip']; ?>" name="zip" maxlength="10" tabindex="11" />
</li>
</ul>
</fieldset>
<fieldset id='feedback'>
<legend>Feedback</legend>
<label for="comments">Comments:</label>
<textarea id="comments" value="comments" name="comments" rows="5" cols="50"></textarea>
</ul>
</fieldset>
<?php
/*Put in the Captcha for verification*/
$new_string;
$im = ImageCreate(144, 30);
$white = ImageColorAllocate($im, 255, 255, 255);
$black = ImageColorAllocate($im, 0, 0, 0);
srand((double)microtime()*1000000);
$string = md5(rand(0,9999));
$new_string = substr($string, 17, 5);
ImageFill($im, 0, 0, $black);
ImageString($im, 5, 50, 5, $new_string, $white);
ImagePNG($im, "verify.png");
echo " <img src=\"verify.png\" ><br />";
ImageDestroy($im);
echo "Please type the numbers from the image into the input box below. <br/>";
echo "<input type=\"hidden\" type=\"text\" name=\"new_string\" value=\"$new_string\">";
echo "<input type=\"text\" value=\"\" input name=\"random\"><font size=\"2\"><br /><br />";
$random = trim($_POST[random]);
if ($_POST[new_string]!=$random) {
echo "You must type the code that's in the box.<br />";
echo "<a href=\"form.php\">BACK</a>";
}
?>
<div id="buttons">
<input type="submit" name="submit" value="Submit Form">
<input type="reset" name="reset" class="reset" value="Reset">
</div>
</form>
</body>
</html>
<?PHP
else:
$query_1 = "INSERT INTO information (fname, lname, address1, address2, city, state, zip, dphone, nphone, cphone, email, comments) VALUES ('$html_safe[firstName]', '$html_safe[lastName]', '$html_safe[address1]', '$html_safe[address2]', '$html_safe[city]', '$html_safe[state]', '$html_safe[zip]', '$html_safe[dayPhone]', '$html_safe[nightPhone]', '$html_safe[cellPhone]', '$html_safe[email]', '$html_safe[comments]')";
$result_1 = mysql_query($query_1) or die ("Query 1 Failed!<br /><a href=\"form.php\">BACK</a>");
if($query_1){
echo "Added -- " . mysql_affected_rows() . " record to database";
}
?>
<h1>Successfully Submitted!</h1>
<p>We'll get back to you.</p>
<?PHP
endif;
?>
kows
May 14th, 2010, 11:39 PM
no. whether or not the form is valid is based solely on $showform's value. all validation logic should be done at the top of the script. so instead of having that random piece of logic in the middle of the script, it should also be at the top of the script with the rest of your form validation (which means some of your other captcha code must go at the top of the script as well -- at least the first part that defines $random, but that should be placed right below $showform = true). instead of echoing anything, it should add onto $message, because this is our variable that holds error messages.
basically, structured like so (very loose, just so you have an idea of where things should go):
/* some captcha code */
$random = ...
if($_SERVER['REQUEST_METHOD'] == "POST"){
/* some validation */
if($_POST['captchafield'] != $random){
$message = "captcha is wrong";
}
if(!$message){
$showform = false;
}
}
hope that helps.
Blue1974
May 15th, 2010, 01:08 PM
I think I put things in place as you described? I was trying to check the captcha image generated against the one typed in but for some reason the captcha being displayed isn't the one in the image?
<?PHP
include "config_mylogin.php";
// Start the login session
session_start();
if (!$_SESSION['user_name'] || !$_SESSION['pass']) {
// What to do if the user hasn't logged in
// We'll just redirect them to the login page.
header('Location: mylogin.php');
die();
} else {
$result = mysql_query("SELECT count(user_id) from users WHERE
pass = '$_SESSION[pass]' AND user_name='$_SESSION[user_name]'") or die("Couldn't query the user-database.");
$num = mysql_result($result, 0);
if (!$num) {
// If the credentials didn't match,
// redirect the user to the login screen.
header('Location: mylogin.php');
die();
}
}
// All output text below this line will be displayed
// to the users that are authenticated.
// the form is always shown unless it was submitted and there were no errors
$showform = true;
$random = trim($_POST[random]);
if($_SERVER['REQUEST_METHOD'] == "POST"){
$mysql_safe = array(); // stores database-safe values
$html_safe = array(); // stores html-safe values
foreach($_POST as $key => $value){
$mysql_safe[$key] = mysql_real_escape_string($value);
$html_safe[$key] = htmlentities($value);
}
$message = "";
if(empty($_POST['firstName'])){
$message .= "Please enter a first name. <br />";
}
if(empty($_POST['lastName'])){
$message .= "Please enter a last name. <br />";
}
if(empty($_POST['email'])){
$message .= "Please enter email. <br />";
}
if(empty($_POST['dayPhone'])){
$message .= "Please enter day phone. <br />";
}
if(empty($_POST['nightPhone'])){
$message .= "Please enter night phone. <br />";
}
if(empty($_POST['address1'])){
$message .= "Please enter main address. <br />";
}
if(empty($_POST['city'])){
$message .= "Please enter city. <br />";
}
if(empty($_POST['state'])){
$message .= "Please enter state. <br />";
}
if(empty($_POST['zip'])){
$message .= "Please enter zip. <br />";
}
if($_POST['new_string'] != $random){
$message .= "captcha is wrong";
echo "random = " . $_POST[random] . " new_string = " . $_POST[new_string]; //test to see if getting variables
}
/*Check to see if any errors occurred*/
if(!$message){
$showform = false; // no errors occurred
}
}
/*Display form */
if($showform):
?>
<html>
<head>
<style type = "text/css">
form fieldset {
margin-bottom: 8px;
background-color: beige;
}
form legend {
padding: 0 5px;
font-weight: bold;
}
form label {
display: inline-block;
line-height: 1.5em;
vertical-align: top;
color: green;
}
form fieldset ul {
margin: 0px;
padding: 0;
}
form fieldset li {
clear: both;
list-style: none;
padding: 5px;
margin: 0;
}
label {
width: 120px;
}
form span {color: red}
</style>
<title>form</title>
</head>
<body>
<h1>Form Project</h1>
<?php
// if there are error messages, display them!
if($message){
echo $message;
}
?>
<p><span>*</span>Indicates required information</p>
<form name='information' action ='form.php' method='POST' />
<fieldset id='address'>
<legend>Contact</legend>
<ul class="form">
<li>
<label for="firstName">First name:<span>*</span></label>
<input type="text" id="firstName" value="<?php if(isset($html_safe['firstName'])) echo $html_safe['firstName']; ?>" name="firstName" tabindex="1" />
</li>
<li>
<label for="lastName">Last name:<span>*</span></label>
<input type="text" id="lastName" value="<?php if(isset($html_safe['lastName'])) echo $html_safe['lastName']; ?>" name="lastName" tabindex="2" />
</li>
<li>
<label for="email">Email:<span>*</span></label>
<input type="text" id="email" value="<?php if(isset($html_safe['email'])) echo $html_safe['email']; ?>" name="email" tabindex="3" />
</li>
<li>
<label for="dayPhone">Day phone:<span>*</span></label>
<input type="text" id="dayPhone" value="<?php if(isset($html_safe['dayPhone'])) echo $html_safe['dayPhone']; ?>" name="dayPhone" tabindex="4" />
</li>
<li>
<label for="nightPhone">Night phone:<span>*</span></label>
<input type="text" id="nightPhone" value="<?php if(isset($html_safe['nightPhone'])) echo $html_safe['nightPhone']; ?>" name="nightPhone" tabindex="5" />
</li>
<li>
<label for="cellPhone">Cell phone</label>
<input type="text" id="cellPhone" value="<?php if(isset($html_safe['cellPhone'])) echo $html_safe['cellPhone']; ?>" name="cellPhone" tabindex="6" />
</li>
</ul>
</fieldset>
<fieldset id="contact">
<legend>Address</legend>
<ul class="form">
<li>
<label for="address">Address1:<span>*</span></label>
<input type="text" id="address1" value="<?php if(isset($html_safe['address1'])) echo $html_safe['address1']; ?>" name="address1" tabindex="7" />
</li>
<li>
<label for="address2">Address2:</label>
<input type="text" id="address2" value="<?php if(isset($html_safe['address2'])) echo $html_safe['address2']; ?>" name="address2" tabindex="8" />
</li>
<li>
<label for="city">City:<span>*</span></label>
<input type="text" id="city" value="<?php if(isset($html_safe['city'])) echo $html_safe['city']; ?>" name="city" tabindex="9" />
</li>
<li>
<label for="state">State:<span>*</span></label>
<input type="text" id="state" value="<?php if(isset($html_safe['state'])) echo $html_safe['state']; ?>" name="state" maxlength="2" tabindex="10" />
</li>
<li>
<label for="zip">Zip Code:<span>*</span></label>
<input type="text" id="zip" value="<?php if(isset($html_safe['zip'])) echo $html_safe['zip']; ?>" name="zip" maxlength="10" tabindex="11" />
</li>
</ul>
</fieldset>
<fieldset id='feedback'>
<legend>Feedback</legend>
<label for="comments">Comments:</label>
<textarea id="comments" value="comments" name="comments" rows="5" cols="50"></textarea>
</ul>
</fieldset>
<?php
/*Put in the Captcha for verification*/
$new_string;
$im = ImageCreate(144, 30);
$white = ImageColorAllocate($im, 255, 255, 255);
$black = ImageColorAllocate($im, 0, 0, 0);
srand((double)microtime()*1000000);
$string = md5(rand(0,9999));
$new_string = substr($string, 17, 5);
ImageFill($im, 0, 0, $black);
ImageString($im, 5, 50, 5, $new_string, $white);
ImagePNG($im, "verify.png");
echo " <img src=\"verify.png\" ><br />";
ImageDestroy($im);
echo "Please type the numbers from the image into the input box below. <br/>";
echo "<input type=\"hidden\" type=\"text\" name=\"new_string\" value=\"$new_string\">";
echo "<input type=\"text\" value=\"\" input name=\"random\"><font size=\"2\"><br /><br />";
?>
<div id="buttons">
<input type="submit" name="submit" value="Submit Form">
<input type="reset" name="reset" class="reset" value="Reset">
</div>
</form>
</body>
</html>
<?PHP
else:
$query_1 = "INSERT INTO information (fname, lname, address1, address2, city, state, zip, dphone, nphone, cphone, email, comments) VALUES ('$html_safe[firstName]', '$html_safe[lastName]', '$html_safe[address1]', '$html_safe[address2]', '$html_safe[city]', '$html_safe[state]', '$html_safe[zip]', '$html_safe[dayPhone]', '$html_safe[nightPhone]', '$html_safe[cellPhone]', '$html_safe[email]', '$html_safe[comments]')";
$result_1 = mysql_query($query_1) or die ("Query 1 Failed!<br /><a href=\"form.php\">BACK</a>");
if($query_1){
echo "Added -- " . mysql_affected_rows() . " record to database";
}
?>
<h1>Successfully Submitted!</h1>
<p>We'll get back to you.</p>
<?PHP
endif;
?>
kows
May 15th, 2010, 02:56 PM
you could just be getting a cached version of the image. you can do a hard refresh to forcibly refresh all items on the page (CTRL + F5) to see if that is the problem, and to remedy it you could add an always-changing query string to the <img> tag's source attribute, like so:
echo ' <img src="verify.png?' . time() . '" ><br />';
in this case, I'm adding a query string with the current Unix timestamp. this will make it so that the browser will always request a new version of the image, even if it was cached previously, because it's technically a completely new request.
Blue1974
May 16th, 2010, 08:23 PM
I think the situation you described is what was happening. I would type in the captcha and deliberately get it wrong. I would get the captcha is wrong message and the old image would still be the image in to be typed in again. I would type it in the but new_string variable had changed but the imaga didn't so even though I was typing in the correct letters in the captcha I wasn't seeing the new_string that should have been in the captcha.
I tried your code and that seemed to solve the problem. I'm just wondering why it didn't behave like this when I worked with the captcha before. Does it have to do with adding the sessions to this example?
kows
May 16th, 2010, 09:00 PM
that's doubtful. it's just the way the browser caches things.
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.