How to Generate URL-encoded Query String using PHP

Setting up our Data

First, are going to set up the data that we are gonna be using as a sample to build our url-encoded query string. Create a new file, name it as index.php and paste the codes below.
  1. <?php
  2.         $data = array(
  3.                 'id' => 1,
  4.                 'firstname' => 'neovic',
  5.                 'lastname' => 'devierte',
  6.                 'address' => 'silay city'
  7.         );
  8.  
  9.         print_r($data);
  10.  
  11.         $url_encoded = http_build_query($data);
  12.  
  13.         echo "
  14.                 <br><br>
  15.                 <a href='goto.php?".$url_encoded."'>Send to URL</a>
  16.         ";
  17. ?>

Creating our Goto Page

Next, we create the goto page where we retrieve our url-encoded query string. Create a new file, name it as goto.php and paste the codes below.
  1. <?php
  2.         echo "
  3.                 <h4>Displaying the URL Encoded Data</h4>
  4.                 <p>ID: ".$_GET['id']."</p>
  5.                 <p>Firstname: ".$_GET['firstname']."</p>
  6.                 <p>Lastname: ".$_GET['lastname']."</p>
  7.                 <p>Address: ".$_GET['address']."</p>
  8.         ";
  9. ?>
Note: http_build query will work on PHP v5 or higher. That ends this tutorial. Happy Coding :)

Add new comment