PHP Usage

Now that we've understood how php is coding is done. Let's get started with PHP usage in websites.

$_GET

An HTTP GET request (often just called a GET request) is what is sent from your browser to the server when you type a URL or click on a link.

When I perform a search for 'learn PHP' here's the URL that I'm sent to:

https://somesite.com/?q=learn+PHP 

The important part here is everything after the question mark ( ? ): that portion of the URL is called the query string, and it holds the data. The data is in key-value form, with the key coming first, then an equal sign, and then the value (which has been URL-encoded).

Let's look at an example:

<?php
if( isset($_GET["name"]) ) { ?>
   <p>
   Hello,
   <?php echo $_GET["name"] ?>!</p>
<?php } else { ?>
   <form action="./" method="GET">
      <p>Please write your name below:</p>
      <p>
         <input type="text" name="name" />
      </p>
      <p>
         <button type="submit">Submit</button>
      </p>
   </form>
<?php } ?>
Demo of above code

Please write your name below:

$_POST

A lot of what you've just learned about using GET requests is very applicable to POST requests. In fact, to make our previous example work with POST instead of GET, there's only three changes to make. That's changing every instance of 'GET' to 'POST':

In this code example, You'll notice that when we click the Submit button, the page refreshes, but the URL doesn't change.

<?php
if( isset($_POST["name"]) ) { ?>
   <p>
   Hello,
   <?php echo $_POST["name"] ?>!</p>
<?php } else { ?>
   <form action="./" method="POST">
      <p>Please write your name below:</p>
      <p>
         <input type="text" name="name" />
      </p>
      <p>
         <button type="submit">Submit</button>
      </p>
   </form>
<?php } ?>
Demo of above code

Please write your name below:


comments powered by Disqus