PHP Form Handling With Examples

PHP Form method is used to sending data from browser to server. Two types of methods are there GET and POST. $_GET and $_POST are used to receive value from the form method. $_GET and $_POST are the global variables so declare it with uppercase otherwise this will not work.

Syntax of GET Method:


Syntax of POST Method:


Note: by default form method is get. If any users do not declare method attribute in the form tag then value send by getting method automatically.
If any users declare form method attribute value post and receive value in the server using $_GET variable then it does not work same as vice versa.

Get and Post method both are same and used for the same purpose but there has some difference.

Html/Text Response:
Sending any kind of data from the form all go as a string type.



Send JSON Response through Form
JSON is another way to use for exchange data format between web client and server. Enabling HTML forms to submit JSON directly simplifies implementation as it enables backend services to operate by accepting a single input format that is what’s more able to encode richer structure than other form encodings (where the structure has traditional had to be emulated). Form’s type attribute value set application/json to transmit JSON data from the form.



By default input type is text. Value send from the form by method and json_encode is a function which exchanges PHP server data into JSON format.

Sending image:


Upload any kind of file through form need set enctype attribute value with multipart/form-data. It means multi-type file can upload from Form.
Next always use post method in form because get method only sends 1kb data.
Next file value receives always in the server via $_FILES[] global array whatever form method in form, Which has 5 parameters name size type tmp_name and error.
Name index return name value of the uploaded file.
Size index returns size value of the uploaded file in bytes.
Type index return uploaded file type value like image/jpg for jpg extension file, application/pdf for pdf file, application/docx for document file, plain/text for text file etc.
Tmp_name index returns the uploaded file location. In server, there has a tmp folder initially where all the uploaded files are stored temporarily.
Error index return by default 0 otherwise if the size or any other index value return any error then error index return 1 or 2

Want Upload pdf file then only change the condition of above example

File Download:

Show image file by tag
For pdf or document file use <a> tag
Or for others file use their HTML tags to display the original fin the browser. Like use <audio> tag for mp3 file , <video> tag for video file etc.