Thursday, February 11, 2010

Login ID Options


<HTML>
  <HEAD>
  <TITLE>Displaying Login ID Options</TITLE>
  </HEAD>
  <BODY>
  <Hl><CENTER>Generating Login IDs for Dave</CENTER></Hl>
  <?php
  $loginfo = array (
             FirstName => "Joe",
             LastName => "Howrod",
             Sex => "Male",
             Location => "Arizona",
             Age => "24",
             MusicChoice => "Pop",
             Hobby => "Dance",
             Occupation => "Author");
  echo "<H3>The information entered by JOe:<BR></H3>"
  foreach ($loginfo as $key => $val) {
     echo "<B>$key</B> => $val<BR>";
  }
  echo "<BR> ";
  echo "<H3>The login options are:<BR></H3>";
  $loginone = array_slice ($loginfo, 02);
  $logintwo = array_slice ($loginfo, 32);
  $loginthree = array_slice ($loginfo, 52);
  $loginfour = array_slice ($loginfo, 62);
  $loginfive = array_merge ($loginfour, "2001");
  echo "The first login option:<BR>";
  foreach ($loginone as $optionone) {
      echo "<B>$optionone</B>";
  }
  echo "<BR>";
  echo "The second login option:<BR>";
  foreach ($loginone as $optiontwo) {
      echo "<B>$optiontwo</B>";
  }
  echo "<BR>";
  echo "The third login option:<BR>";
  foreach ($loginthree as $optionthree) {
      echo "<B>$optionthree</B>";
  }
  echo "<BR>";
  echo "The fourth login option:<BR>";
  foreach ($loginfour as $optionfour) {
      echo "<B>$optionfour</B>";
  }
  echo "<BR>";
  echo "The fifth login option:<BR>";
  foreach ($loginfive as $optionfive) {
      echo "<B>$optionfive</B>";
  }
  echo "<BR>";
  ?>
  </BODY>
  </HTML>

Game

Game

<?
function slotnumber()
{
srand(time());
for ($i=0; $i < 3; $i++)
{
$random =
(rand()%3);
$slot[]
= $random;
}
print("<td
width=\"33%\"><center>$slot[0]</td>");
print("<td
width=\"33%\"><center>$slot[1]</td>");
print("<td
width=\"33%\"><center>$slot[2]</td>");
if($slot[0]
== $slot[1]
&& $slot[0]
== $slot[2])
{
print("</td></tr>Winner!
-- Hit refresh on your browser to play again");
exit;
}
}
?>

<div align="center"><center>

<table border="1" width="50%">
<tr>
<?
slotnumber();
?>
</td>
</tr>
<tr>
<td width="100%" colspan="3" bgcolor="#008080"><form
method="POST"
action="example13.php3"><div
align="center"><center><p><input type="submit" value="Spin!"></p>
</center></div>
</form>
</td>
</tr>
</table>
</center></div>

Page counters

Creating a visible page counter

is something I'd like to explore next. I have a stats program which tells me how
many visitors I have already for each page that is essentially invisible, but I
have received a number of emails expressing interest in how to make a counter
using PHP that is visible. The code below inserted into a page counts the
visitors and display the results dynamically.

<?

if(file_exists("count.dat"))
{
$exist_file = fopen("count.dat",
"r");
$new_count = fgets($exist_file,
255);
$new_count++;
fclose($exist_file);
// to be invisible counter comment out next line;
print("$new_count people have visited this page");
$exist_count = fopen("count.dat", "w");
fputs($exist_count, $new_count);
fclose($exist_count);
}
else
{
$new_file = fopen("count.dat", "w");
fputs($new_file, "1");
fclose($new_file);
}
?>

23645
people have visited this page

To insert

the code to a page where you want the counter displayed you would use the
following code:

<? require("/path/to/count.dat");

?>


Making a hardcoded Admin Password gateway using PHP


hardcoded Admin Password gateway using PHP

First you will use a form to pass

the $pw variable to the php script. When entering passwords into forms it is a
good idea to use the "password" input box instead of the "text" one, so that as
you type there are asterisks in place of the input. Something like this will
work fine:

Using a hardcoded admin

pasword system

The HTML for the above form looks like:

<form method="

Arial;color:blue">POST"
action="example18.php3"
color:black">>
<div
color:red">align="left"
color:black">><p><
Arial;color:purple">font face="
Arial;color:blue">BankGothic Md BT
color:red">">Admin password?</font>
<input type="
Arial;color:blue">password"
name="pw"
blue" style="font-family:Arial;">14
color:red">"><input type="
Arial;color:blue">submit"
value="Submit"
color:black">></p>
</div><
Arial;color:purple">/form>

Now the php code to check the submitted password versus the hardcoded one is:

<?
$adminpass = "test123";
if ($pw == $adminpass)
{
print("Welcome to the administration area!");
}
else
{
print("Wrong password");
}
?>

Saturday, February 6, 2010

Handling HTML forms with PHP

Handling HTML forms with PHP

» Simple contact form

<html>

<body>

<form action="myform.php" method="post">

<p>Your Name: <input type="text" name="yourname" /><br />

E-mail: <input type="text" name="email" /></p>



<p>Do you like this website?

<input type="radio" name="likeit" value="Yes" checked="checked" /> Yes

<input type="radio" name="likeit" value="No" /> No

<input type="radio" name="likeit" value="Not sure" /> Not sure</p>



<p>Your comments:<br />

<textarea name="comments" rows="10" cols="40"></textarea></p>



<p><input type="submit" value="Send it!"></p>

</form>

</body>

</html>

See the example HTML code above? This is a simple HTML form with two input
fields, one radio box group and a text area for comments. Let's say we save this
code in a file called "test.html". When submitted data is sent to the "myform.php"
file using POST HTTP method.

All variables passed to the current script via the HTTP POST method are stored
in associative array $_POST. In other words, in PHP you can access data from
each field using$_POST['NAME'], where NAME is the actual field name. If you
submit the form above you would have access to a number of $_POST array values
inside the myform.php file:

Variable Holds value of

$_POST['yourname'] text field "yourname"

$_POST['email'] text field "email"

$_POST['likeit'] selected radio box group "likeit"

$_POST['comments'] textarea "comments"

With register_globals activated all form data is automatically stored in
variable $name (wherename is field name, for example $yourname or $email), but
this can lead to various security issues and should be avoided at all cost! This
feature is now officially depreciated and disabled by default.

Now, if you wanted to display submitted data you could simply echo all the
variables as shown below, but do not! Why? Read further.

<html>

<body>

Your name is: <?php echo $_POST['yourname']; ?><br />

Your e-mail: <?php echo $_POST['email']; ?><br />

<br />

Do you like this website? <?php echo $_POST['likeit']; ?><br />

<br />

Comments:<br />

<?php echo $_POST['comments']; ?>

</body>

</html>

If you saved this code in a file called "myform.php", filled the fields in the
test.html form and hit the Submit button, the myform.php output would look
something like this:

Your name is: John Doe

Your email: john@doe.com

Do you like this website? Yes

Comments:

This is my comment...

Quite simple, isn't it? But the most important thing is still missing! You need
to validatesubmitted data to protect your script (and thus your website and
server) from malicious code.

Let's say you display all data submitted with the form in a HTML file (like a
guestbook does for example). Now consider someone types this code instead of his
name:

<script>location.href('http://www.SPAM.com')</script>

If this is stored in a HTML file anyone who tried to view it would be redirected
tohttp://www.SPAM.com! And this is the least that can happen! Failure to
properly validate input data is the main reason for most vulnerabilities and
exploits in PHP scripts. You wouldn't want someone to hack your website, erase
all data and upload his/her own "u \/\/3R3 H4><0r3d!" homepage, would you?

Read this tutorial further to learn how to validate form inputs and protect
yourself from exploits.

Validating forms with PHP

So, how do you validate form data? The very least you should do is pass all
variables through PHP's htmlspecialchars() function. This function will replace
HTML chars like < and > to their HTML version &lt; and &gt;. Let's rewrite the
previous example:

<?php

$yourname = htmlspecialchars($_POST['yourname']);

$email = htmlspecialchars($_POST['email']);

$likeit = htmlspecialchars($_POST['likeit']);

$comments = htmlspecialchars($_POST['comments']);

?>

<html>

<body>

Your name is: <?php echo $yourname; ?><br />

Your e-mail: <?php echo $email; ?><br />

<br />

Do you like this website? <?php echo $likeit; ?><br />

<br />

Comments:<br />

<?php echo $comments; ?>

</body>

</html>

This is much safer now and prevents possible attackers from exploiting our code
by injecting HTML or Javascript code. Now if someone submitted the same code as
before...

<script>location.href('http://www.SPAM.com')</script>

... this would not be executed anymore, because it would be saved as HTML
escaped code rather than valid HTML code:

&lt;script&gt;location.href('http://www.SPAM.com')&lt;/script&gt;

Such code can now do no harm and is safe to be displayed on a page or inside an
e-mail. Sure, it may not look nice and tell you someone has been trying to mess
with your script, but the important thing is he/she had failed!

» What else to check?

If you know exactly what kind of data to expect you can make further steps to
ensure the user has entered what you want. We will cover a few samples like
validating e-mail address and URLs later.

Let's do two more things:

1. strip unnecessary characters from the data.

2. if quotes are escaped with a slash \ let's remove that.

Instead of writing the same code over and over again we can create a function
that will do all the checking for us. Here we will name it check_input and
simply call this function whenever we need to validate simple input data:

<?php

$yourname = check_input($_POST['yourname']);

$email = check_input($_POST['email']);

$likeit = check_input($_POST['likeit']);

$comments = check_input($_POST['comments']);

?>

<html>

<body>

Your name is: <?php echo $yourname; ?><br />

Your e-mail: <?php echo $email; ?><br />

<br />

Do you like this website? <?php echo $likeit; ?><br />

<br />

Comments:<br />

<?php echo $comments; ?>

</body>

</html>



<?php

function check_input($data)

{

$data = trim($data);

$data = stripslashes($data);

$data = htmlspecialchars($data);

return $data;

}

?>

Note the check_input function at the bottom. What it does is takes the data
passed to the function, strips unwanted characters (extra space, tab, newline)
from the beginning and end of the data using the PHP trim() function, strips any
quotes escaped with slashes and passes it through htmlspecialchars().

So now instead of typing the same code for each of our input fields we simply
check each $_POST variable with the check_input function and that's it.

Required and optional fields

So far we only worked with optional fields - in all previous examples the
scripts worked fine if you didn't enter any data. However, many times you want
to make input fields required.

This is an easy task, let's edit the check_input function from the previous page
to read:

function check_input($data, $problem='')

{

$data = trim($data);

$data = stripslashes($data);

$data = htmlspecialchars($data);

if ($problem && strlen($data) == 0)

{

die($problem);

}

return $data;

}

We've added an extra parameter to the form: $problem. By default $problem is
empty, but if you pass a value for $problem to the function and the length of
entered data is 0 the script will stop executing (die) displaying the text
passed as $problem parameter.

It's actually easier than it sounds. To validate data from field "yourname" we
used this so far:

$yourname = check_input($_POST['yourname']);

It still works. But if you want to make "yourname" required you now simply add
,"Error message" to the function call, like this:

$yourname = check_input($_POST['yourname'],"Enter your name!");

Now if the "yourname" fields is empty when the form is submitted, the script
will stop and display "Enter your name!" text.

As easy as that, for optional fields use

$test = check_input($_POST['test']);

and for required fields add a comma and an error message before ):

$test = check_input($_POST['test'], "My error message");

Here is the final code of our myform.php script where "Your name", and
"Comments" fields are required, but "Your e-mail" field is not. If the name is
missing you will get an error saying "Enter your name" and if the comments are
missing you will get "Write your comments" error message.

<?php

$yourname = check_input($_POST['yourname'], "Enter your name");

$email = check_input($_POST['email']);

$likeit = check_input($_POST['likeit']);

$comments = check_input($_POST['comments'], "Write your comments");

?>

<html>

<body>

Your name is: <?php echo $yourname; ?><br />

Your e-mail: <?php echo $email; ?><br />

<br />

Do you like this website? <?php echo $likeit; ?><br />

<br />

Comments:<br />

<?php echo $comments; ?>

</body>

</html>



<?php

function check_input($data, $problem='')

{

$data = trim($data);

$data = stripslashes($data);

$data = htmlspecialchars($data);

if ($problem && strlen($data) == 0)

{

die($problem);

}

return $data;

}

?>

The die() PHP function just displays the error text. If you want a more fancy
error page that fits your website design we can add a custom error reporting
function. In this example we will name it show_error:

<?php

$yourname = check_input($_POST['yourname'], "Enter your name");

$email = check_input($_POST['email']);

$likeit = check_input($_POST['likeit']);

$comments = check_input($_POST['comments'], "Write your comments");

?>

<html>

<body>

Your name is: <?php echo $yourname; ?><br />

Your e-mail: <?php echo $email; ?><br />

<br />

Do you like this website? <?php echo $likeit; ?><br />

<br />

Comments:<br />

<?php echo $comments; ?>

</body>

</html>



<?php

function check_input($data, $problem='')

{

$data = trim($data);

$data = stripslashes($data);

$data = htmlspecialchars($data);

if ($problem && strlen($data) == 0)

{

show_error($problem);

}

return $data;

}



function show_error($myError)

{

?>

<html>

<body>



<b>Please correct the following error:</b><br />

<?php echo $myError; ?>



</body>

</html>

<?php

exit();

}

?>

Now you can simply edit the HTML code inside show_error function as much as you
like and place this PHP code where you want the error message to appear:

<?php echo $myError; ?>

Note that we printed $myError directly without passing it through check_input
function. Why? Because this variable was declared inside the script so we can
control exactly what it is set to and it is not possible to change it from
outside the script (using either POST or GET parameters) and insert any
malicious code.

We end the show_error function with exit(); which tells PHP to stop executing
code after displaying the error.

Validating e-mail, URL and other special types with PHP

On this page we will show a few examples of how to validate e-mails, website
addresses (URLs) and some other special cases of input data.

» Validate e-mail address

There is no way to be 100% sure an e-mail address is actually working unless you
send an e-mail there. What you usually do is check if the e-mail address syntax
is valid. Here is a simple way to check if data entered into input field named
"email" is an e-mail address without any unnecessary complications and fancy
regular expressions:

$email = htmlspecialchars($_POST['email']);

if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email))

{

die("E-mail address not valid");

}

The above code would make the e-mail address required. To make it optional
simply replace

die("E-mail address not valid");

with this and the $email variable will simply be empty unless a valid address is
entered:

$email = '';



» Validate URL address

If you have an input field named "website" you can check for a valid URL address
like this:

$url = htmlspecialchars($_POST['website']);

if (!preg_match("/^(https?:\/\/+[\w\-]+\.[\w\-]+)/i",$url))

{

die("URL address not valid");

}

Similarly as before to make the URL optional just change:

die("URL address not valid");

to this code and $url will be empty if not valid:

$url = '';



» Other special cases

Some other special cases below if you ever need any. You may just skip it and go
to the next page of the tutorial.

Digits 0-9 only

This code will check if $age is a number:

if (preg_match("/\D/",$age))

{

die("Please enter numbers only for Age");

}

Letters a-z and A-Z only

This code will check if $text is made of letters a-z and A-Z only (no spaces,
digits or any other characters):

if (preg_match("/[^a-zA-Z]/",$text))

{

die("Please enter letters a-z and A-Z only!");

}

Anything but whitespace

This code will show an error if $text contains of any whitespace characters
(space, tab, newline):

if (preg_match("/\s/",$text))

{

die("Please do not enter any spaces, tabs or new lines!");

}



Sending form results to your e-mail address

Sending e-mails in PHP is quite trivial, all you need to do is use the mail()
function. The syntax is:

mail(RECIPIENT, SUBJECT, MESSAGE [, HEADERS]);

First three parameters are required, headers are optional. Here is an example to
make things more clear. If you want to send an e-mail with subject "Test e-mail"
and message "Hi, this is a test message!" to address "john@doe.com" the code
would look like:

mail("john@doe.com", "Test e-mail", "Hi, this is a test message!");

It is usually more practical to store recipient, subject and message in
variables then typing them directly inside mail(). This is especially true if
you have a long subject and message.

Also when you are sending e-mail don't forget to display a response confirming
the form has been submitted ("thank you" page).

<?php

$recipient = "you@yourdomain.com";

$subject = "This is a test e-mail";

$message = "Hi!



This is a test message (e-mail body).

This is a new line



Enough for now.

Best regards,



Test test

";



mail($recipient, $subject, $message);

?>

<html>

<body>

Your message was successfully sent!<br />

<br />

Thank you for contacting us!

</body>

</html>

Instead of printing the response HTML code you can create a separate thank you
page ("thank_you.html") and redirect the visitor after mail() by printing a
'Location:' header:

header('Location:thank_you.html');

...or use the full URL to thank_you.html:

header('Location:http://www.domain.com/thank_you.html');

So the above code would look like:

<?php

$recipient = "you@yourdomain.com";

$subject = "This is a test e-mail";

$message = "Hi!



This is a test message (e-mail body).

This is a new line



Enough for now.

Best regards,



Test test

";



mail($recipient, $subject, $message);



header('Location:thank_you.html');

?>

On the next page we will put everything we learned together and create the final
version of our contact form.

Final PHP contact form

Here we will put together all we learned in this PHP forms tutorial and create a
working PHP contact form.

» HTML form code

Let's use the form we started with this tutorial and just add a few more fields
to make it more interesting. In this example we will make fields "Your name",
"Subject", "E-mail" and "Comments" required, all others optional. We will mark
required field labels bold so the visitor knows which fields he/she has to fill
in.

Copy the HTML code below it into a plain text file and save it as contact.htm

<html>

<body>



<p>Required fields are <b>bold</b></p>



<form action="contact.php" method="post">

<p><b>Your Name:</b> <input type="text" name="yourname" /><br />

<b>Subject:</b> <input type="text" name="subject" /><br />

<b>E-mail:</b> <input type="text" name="email" /><br />

Website: <input type="text" name="website"></p>



<p>Do you like this website?

<input type="radio" name="likeit" value="Yes" checked="checked" /> Yes

<input type="radio" name="likeit" value="No" /> No

<input type="radio" name="likeit" value="Not sure" /> Not sure</p>



<p>How did you find us?

<select name="how">

<option value=""> -- Please select -- </option>

<option>Google</option>

<option>Yahoo</option>

<option>Link from a website</option>

<option>Word of mouth</option>

<option>Other</option>

</select>



<p><b>Your comments:</b><br />

<textarea name="comments" rows="10" cols="40"></textarea></p>



<p><input type="submit" value="Send it!"></p>



<p> </p>

<p>Powered by <a href="http://myphpform.com">PHP form</a></p>



</form>



</body>

</html>



» Thank you page

We could include the response in the PHP script (as shown before), but keeping
it in an outside file makes the script itself less complicated and the response
page easier to edit and customize.

Copy the HTML code below it into a plain text file and save it as thanks.htm

<html>

<body>



<p><b>Your message was sent</b></p>



<p>Your message was successfully sent!

Thank you for contacting us, we will reply

to your inquiry as soon as possible!</p>



</body>

</html>



» PHP form script

This script is just a summary of topics covered in this tutorial. Included are
some comments to explain what is happening. Copy the PHP code below it into a
plain text file and save it ascontact.php

Change the default "you@domain.com" recipient address inside the code to your
own e-mail address (the one you wish to receive form results to)!

<?php

/* Set e-mail recipient */

$myemail = "you@domain.com";



/* Check all form inputs using check_input function */

$yourname = check_input($_POST['yourname'], "Enter your name");

$subject = check_input($_POST['subject'], "Write a subject");

$email = check_input($_POST['email']);

$website = check_input($_POST['website']);

$likeit = check_input($_POST['likeit']);

$how_find = check_input($_POST['how']);

$comments = check_input($_POST['comments'], "Write your comments");



/* If e-mail is not valid show error message */

if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email))

{

show_error("E-mail address not valid");

}



/* If URL is not valid set $website to empty */

if (!preg_match("/^(https?:\/\/+[\w\-]+\.[\w\-]+)/i", $website))

{

$website = '';

}



/* Let's prepare the message for the e-mail */

$message = "Hello!



Your contact form has been submitted by:



Name: $yourname

E-mail: $email

URL: $website



Like the website? $likeit

How did he/she find it? $how_find



Comments:

$comments



End of message

";



/* Send the message using mail() function */

mail($myemail, $subject, $message);



/* Redirect visitor to the thank you page */

header('Location: thanks.htm');

exit();



/* Functions we used */

function check_input($data, $problem='')

{

$data = trim($data);

$data = stripslashes($data);

$data = htmlspecialchars($data);

if ($problem && strlen($data) == 0)

{

show_error($problem);

}

return $data;

}



function show_error($myError)

{

?>

<html>

<body>



<b>Please correct the following error:</b><br />

<?php echo $myError; ?>



</body>

</html>

<?php

exit();

}

?>



» Getting it to work

Once you have all the three files (contact.htm, thanks.htm and contact.php)
upload them to your server (check with your host and make sure it supports
PHP!), open contact.htm in your browser and give it a try.

Not receiving e-mails from your form? See PHP form not working.

Congratulations! Your PHP contact form is now up and running!

Monday, February 1, 2010

PHP

Hypertext Preprocessor (PHP) is a widely used, general-purpose scripting language that was originally designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document. As a general-purpose programming language, PHP code is processed by an interpreter application in command-line mode performing desired operating system operations and producing program output on its standard output channel. It may also function as a graphical application. PHP is available as a processor for most modern web servers and as standalone interpreter on most operating systems and computing platforms.
PHP was originally created by Rasmus Lerdorf in 1995[1] and has been in continuous development ever since. The main implementation of PHP is now produced by The PHP Group and serves as the de facto standard for PHP as there is no formal specification.[3] PHP is free software released under the PHP License, which is incompatible with the GNU General Public License (GPL) because restrictions exist regarding the use of the term PHP.[4]