PHP HTML Pass Value Through URL and Encode URL Values

From CoderLearner
Jump to: navigation, search

You need to pass value through URL

  • To get the value through the URL you need to use the $_GET method

URL special character

  • Use the urlencode() method to encode string for special character in URL(see example 2 for detail).

Example 1: student.php page

  • Pass the student name and class through the URL
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title></title>
	</head>
	<body>
		<a href="student_list.php?name=Paul&class=C">Paul Information</a>
	</body>
</html>

student_list.php page

  • Get the student name and class from the URL.
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>List</title>
	</head>
	<body>
		<?php 
			echo 'Student name: '
                                . $_GET['name']
                                . ' and student class: '
                                . $_GET['class']. '<br/>';
		?>
	</body>
</html>

display result

Student name: Paul and student class: C

Example 2: user.php page

  • Use the urlencode() method to encode the string for the URL special character.
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>All Users</title>
	</head>
	<body>
		<?php
		$user = array(
			 'Bob Kinita',
			 'Lily Chan',
			 'David Philip',
			 'Janny Joe'
		);

		foreach ($user as $u) {
			echo '<a href="user_list.php?name=' 
                           . urlencode($u) . '">' 
                           . $u . 'Information</a><br/>';
		}
		?>

	</body>
</html>

user_list.php page

<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>List User</title>
	</head>
	<body>
		<?php 
			echo 'Student name: '
                        . $_GET['name']. '<br/>';
		?>
	</body>
</html>

Try It