PHP: Processing HTML Forms

Passing Data from an HTML Form to a PHP and then Validating and Sanitizing The User Data

  • Validating data - ensure data is in proper form
  • Sanitizing data - remove potential harmful characters from data

Example #1: POST method and PHP filter_input

Fahrenheit Temperature Analyser HTML User Input Form


	<h1>Temperature Analyser</h1>
				
	<form action="temp2.php" method="post">
				
		<p>Enter a fahrenheit temperature:  <input type="number" name="f" min=="-200" max="5000"></p>
		<p><input type="submit" value="Submit"></p>
		
	</form>
	

Fahrenheit Temperature Analyser PHP Page - Processing HTML User Input


	<h1>Temperature Analyzer</h1>

	<?php
		$f = substr(filter_input(INPUT_POST, 'f', FILTER_SANITIZE_NUMBER_INT),0,6);
		if ($f >= 1945)
			echo "<p>Gold, Magnesium, and Bronze melt at $f degrees fahrenheit and above.</p>";
		elseif ($f >= 1218)
			echo "<p>Aluminum melts at $f degrees fahrenheit (any fahrenheit 1218 degrees or higher).</p>";
		elseif ($f >= 212)
			echo "<p>Water boils at $f degrees fahrenheit (any fahrenheit 212 degrees or higher).</p>";
		elseif ($f >= 32)
			echo "<p>$f degrees fahrenheit above freezing.</p>";
		else
			echo "<p>Water freezes at $f degrees fahrenheit (any fahrenheit below 32 degrees).</p>";
	?>	
	

Run it now


Diagram of HTML user input to PHP data validation and sanitization process


Example #2: GET method and PHP filter_var

Fahrenheit Temperature Analyser HTML User Input Form


	<h1>Temperature Analyser</h1>
				
	<form action="temp4.php" method="get">
				
		<p>Enter a fahrenheit temperature:  <input type="number" name="f" min=="-200" max="5000"></p>
		<p><input type="submit" value="Submit"></p>
				
	</form>
	

Fahrenheit Temperaure Analyzer PHP Page - Processing HTML User Input



	<h1>Temperature Analyser</h1>

	<?php
		$f = substr(filter_var($_GET['f'], FILTER_SANITIZE_NUMBER_INT),0,6);
		if ($f >= 1945)
			echo "<p>Gold, Magnesium, and Bronze melt at $f degrees fahrenheit and above.</p>";
		elseif ($f >= 1218)
			echo "<p>Aluminum melts at $f degrees fahrenheit (any fahrenheit 1218 degrees or higher).</p>";
		elseif ($f >= 212)
			echo "<p>Water boils at $f degrees fahrenheit (any fahrenheit 212 degrees or higher).</p>";
		elseif ($f >= 32)
			echo "<p>$f degrees fahrenheit above freezing.</p>";
		else
			echo "<p>Water freezes at $f degrees fahrenheit (any fahrenheit below 32 degrees).</p>";
	?>	
	

Run it now