Forms + PHP = BFF

Posted: February 20, 2009

One great way to use PHP is to use web forms to get data from visitors to your site. You’re all probably familiar with the standard HTML forms:
<form method=“post” action=“page.php”>
Please enter your name: <input type=“text” name=“username” />
<input type=“submit” value=“Send” />
</form>

See those extra attributes in the form tag, method and action? Those are how you can send things to a PHP script on another page.

The action is obviously the page that you’re going to send the browser to. The PHP script will be able to get the data you send it. How it gets that data depends on that other part, the method.

So say you want to get that username on page.php, and do something with it. Since we know our form was sent as a ‘post’ form, we can access the data like this:

$_POST[‘username’];

That’s it. Now when a user enters their information on the form page, and the form takes them to page.php, you can set up a welcome message, like this:

echo “Welcome, ”;
echo $_POST[‘username’]”;

POST and GET

You can send a form more than one way. We used POST as a method for our last example. But you might also see forms with method=‘get’. What’s the difference?

Both POST and GET will send the same text data to the server. But GET actually sends the data in the URLs. Remember those content management systems with the confusing page urls?

index.php?action=blah&somethingelse=booger

Those are the GET variables. You access them in PHP very similarly to the POST:

$_GET[‘username’];

But the data is sent in the URL. So, you’re limited if you want to try and send large amounts of text. Also, urls with GET variables are somewhat less secure, because it’s easy to see what information is getting sent in the browser address bar. Not to mention, if you want to upload binary data, like a form to upload a picture.

So why don’t people use POST all the time? Well, sometimes you need a url you can bookmark and come back to with the variables already included. For example, Google’s search uses get data to send the search information. That way you can bookmark your search results and come back to them.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Yahoo! Buzz
  • Propeller
  • Twitter

One Response to “Forms + PHP = BFF”

  • Excellent blog! I really love how it is easy on my eyes as well as the data are well written. I am wondering how I could be notified whenever a new post has been made. I have subscribed to your rss feed which ought to do the trick! Have a nice day!

Leave a Reply