Friday, September 5, 2025
HomeLanguagesHow to get information sent via post method in PHP ?

How to get information sent via post method in PHP ?

In this article, we will learn to get information via the post method in PHP. In PHP, we can use the $_POST method as a superglobal variable that is operated to manage form data. After we click on submit button and the page will send the data through the post method. We can use the data after storing it in a variable according to our requirements.

Example 1: In this, first we fill the form details then it send by the post method to itself and it requests for the form data and we can save data in the variable and use according to the program. If we do not give the input in the form then it gives users the message as shown below.

PHP




<!DOCTYPE html>
<html>
  
<body>
    <form method="post" action=
        "<?php echo $_SERVER['PHP_SELF'];?>">
        Name : <input type="text" name="name">
        <br><br>
          
        Age : <input type="text" name="age">
        <br><br>
          
        <input type="submit">
    </form>
  
    <?php
      if ($_SERVER["REQUEST_METHOD"] == "POST") {
          $name = $_POST['name'];
          $age = $_POST['age'];
   
          if (empty($name)) 
              echo "Please enter name";
          elseif(empty($age))
              echo "Please enter age";
          else
              echo "$name is $age years old.";
      }
  ?>
</body>
  
</html>


Output:

Example 2: In this example, we can understand how to send the data to another file by using the POST method.

  • First, it is important to understand the file names are correctly written otherwise it does not send the data accurately.
  • As you can see in the gif below, URL is changed after we click the submit button indicating that the data from the index.html file is sent to post.php file through the POST method.

index.html




<!DOCTYPE html>
<html>
  
<body>
    <form method = "post" action = "post.php">
        Name : <input type = "text" name = "name">
        <br><br>
  
        Age : <input type = "text" name = "age">
        <br><br>
  
        <input type = "submit">
    </form>
</body>
  
</html>


post.php




<?php
  if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST['name'];
    $age = $_POST['age'];
  
    if (empty($name)) 
        echo "Please enter name";
    elseif(empty($age))
        echo "Please enter age";
    else
        echo "$name is $age years old.";
  }
?>


Output:

RELATED ARTICLES

Most Popular

Dominic
32267 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6635 POSTS0 COMMENTS
Nicole Veronica
11801 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11865 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7026 POSTS0 COMMENTS
Thapelo Manthata
6703 POSTS0 COMMENTS
Umr Jansen
6720 POSTS0 COMMENTS