May 28, 2013

Working with forms, $_GET - $_POST form submit

php $_GET $_POST

This is an intro into php forms for beginners.
What's about this 2 functions? You can handle forms submits(you can't using just html)
First of all let's take an example:
<?php
echo $_GET['name'];
?>
The example above is a get request, to use it type into browser filename.php?name=thecodertips
It will echo out 'thecodertips' into the browser.
What's different between get and post? Get can be shown into url and post not. Get method should not be used when submitting passwords.
Post example:
<?php
echo $_POST['name'];
?>
How to go with post now? There must be a form to submit the request:
<html>
<body>
<form action="" method="post">
<input type="text" name="hi">
<input type="submit">
</form>
<?php
echo $_POST['hi'];
?>
The php code handles the input of the text box with the name 'hi', note! "Box name(name=) should be always same with the post/get name([''])
action="" tells the browse to which file it should submit the data
method="" can be get or post

So far so good, but how to check if user submitted anything or not?
We can use isset, empty.
<?php
// usage: empty, isset, !empty, !isset
if(isset($_GET['name'])){
echo 'your name is '.$_GET['name'];
}
else{
echo 'enter your name';
}
?>
Hope you liked this simple lesson on form handling.

2 comments:

  1. it is always nice to go to basic PHP from time to time as many programmers now are so used to frameworks and forget how low level programming works. If you know basic like basic PHP Forms, it helps you debugging problems in future

    ReplyDelete
  2. i heard about one more method request " $_REQUEST " what is difference between post get and request ?

    ReplyDelete