How To Input In Php

In this blog post, we will learn how to take input in PHP from different sources, such as forms, query strings, and reading from files. PHP is a widely-used, open-source scripting language that is specifically designed for web development. Let’s dive into the different ways of taking input in PHP.

1. GET Method – Query Strings

The GET method is used to send data through the URL’s query string. The query string is the part of the URL after the ? symbol, which consists of key-value pairs.

For example, the following URL has a query string with two key-value pairs:

https://example.com/page.php?name=John&age=25

To access the values in the query string in PHP, we can use the $_GET superglobal array. Each key in the query string will have an associated value in the $_GET array.

Let’s say we want to access the values of ‘name’ and ‘age’ from the above example:

  $name = $_GET['name'];
  $age = $_GET['age'];

  echo "Name: " . $name . "<br>";
  echo "Age: " . $age;
  

The output will be:

Name: John
Age: 25

2. POST Method – Forms

The POST method is used to send data through an HTML form. Unlike the GET method, the data sent via POST is not visible in the URL.

Here’s an example of an HTML form using the POST method:

  <form action="process.php" method="post">
    Name: <input type="text" name="name"><br>
    Age: <input type="number" name="age"><br>
    <input type="submit" value="Submit">
  </form>
  

In the above form, when the user clicks the ‘Submit’ button, the form data will be sent to the ‘process.php’ file. In ‘process.php’, we can access the form values using the $_POST superglobal array.

Here’s how to retrieve the values of ‘name’ and ‘age’ in ‘process.php’:

  $name = $_POST['name'];
  $age = $_POST['age'];

  echo "Name: " . $name . "<br>";
  echo "Age: " . $age;
  

The output will be the same as in the GET method example:

Name: John
Age: 25

3. Reading from Files

In PHP, we can read data from a file using the built-in functions fopen(), fread(), and fclose(). Here’s how to read the content of a file called ‘input.txt’:

  $file = fopen("input.txt", "r") or die("Unable to open file!");
  $content = fread($file, filesize("input.txt"));
  fclose($file);

  echo "File content: " . $content;
  

If the ‘input.txt’ file contains the following text:

Hello, world!

The output will be:

File content: Hello, world!

Conclusion

In this blog post, we have discussed three different ways to take input in PHP: using the GET method (query strings), the POST method (forms), and reading from files. Now you should have a better understanding of how to work with input in PHP to create dynamic web applications. Happy coding!