Creating a News System with PHP - Part 1 - Validating the Form
(Page 2 of 4 )
Ok, so we have a form where we can enter in our news. Now, we need to take the news and put it into our text file. Before we do that though, we need to check the password that was entered and check if it is correct. Now, when I deal with forms, I always access the form variables via the $HTTP_POST_VARS array. Some people don't do this, but you will see throughout all my examples that I do. First, let's check if the form has been submitted:
<?php if($HTTP_POST_VARS['submit']) { echo "The form has been submitted"; } ?> |
Ok, obviously that doesn't actually do anything with the submitted form, but it does check to see if it was submitted. Now, we can add some other code to actually process the form. First thing we need to do is check that password and see if it is correct.
<?php if($HTTP_POST_VARS['submit']) { if($HTTP_POST_VARS['password'] == 'mysecretpassword') { echo "The form has been submitted"; } else { echo "Bad Password"; } } ?> |
Now, this isn't the most secure way to do things. But, for simplicity that is the way we are going to do it for now. The next step is to validate that we actually have data in the other two fields. Another couple of if statements should take care of that bit.
<?php if($HTTP_POST_VARS['submit']) { if($HTTP_POST_VARS['password'] == 'mysecretpassword') { if(!$HTTP_POST_VARS['name']) { echo "You must enter a name"; exit; } if(!$HTTP_POST_VARS['news']) { echo "You must enter some news"; exit; } echo "The form has been submitted"; } else { echo "Bad Password"; } } ?> |
Ok, one last thing we need to do to validate the form. When we store the data in the file, we are going to store each entry on one line. I plan to separate each piece of information with a pipe symbol ( | ). We need to make sure that none of the data already contains a pipe symbol, or our whole storage system will fail. In order to do that, we will use the strstr function. This function will return false if what we are looking for is not found in the string. If it returns anything, it will evaluate as true and we will know that a pipe symbol exists in the data we are checking.
<?php if($HTTP_POST_VARS['submit']) { if($HTTP_POST_VARS['password'] == 'pass') { if(!$HTTP_POST_VARS['name']) { echo "You must enter a name"; exit; } if(!$HTTP_POST_VARS['news']) { echo "You must enter some news"; exit; } if(strstr($HTTP_POST_VARS['name'],"|")) { echo "Name cannot contain the pipe symbol - |"; exit; } if(strstr($HTTP_POST_VARS['news'],"|")) { echo "News cannot contain the pipe symbol - |"; exit; } } else { echo "Bad Password"; } } ?> |
Next: Storing the Form Data >>
More Miscellaneous Articles
More By Matt Wade