Use $_POST for POST form data and $_GET for query-string data. Check whether a value exists, validate it for its intended use, and escape it when inserting it into HTML.
$name = trim($_POST['name'] ?? '');
if ($name === '') {
echo 'Name is required.';
} else {
echo 'Hello ' . htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
}
This is the recommended starting pattern. The detailed examples below are retained for explanation, comparison and related variations.
We often have to pass values of variables between pages in our site. These are required in many different ways. Some time we collect some value from a database and want to retain the value for the particular user throughout the site as the user moves between pages. There are different ways for passing such values of the variables. It can be passed within a site or even outside the site. We will discuss some of the ways with their possible uses.
| Uses | Method | Reason |
|---|---|---|
| Login form with Userid and password | POST | Id and password should not be visible in query string |
| Sending Product id | GET | The url can be bookmarked for future uses. |
| Feedback form | Post | Several data can be posted |
| Favorite buying pattern of User | Cookies | Data stored in user computer |
| User Login status | Session | Secured data is maintained at server end |
<?php
$php_variable = "hello world"; // Declaring PHP variable
echo "<script>var js_variable = \"$php_variable\";</script>"; // Passing to JavaScript variable
?>
<script>
document.write(js_variable); // JavaScript output
</script>
Declaring variables
Transfer variables between pages and between sites
Cookies to store Infomation
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| Rohit | 01-10-2009 |
| thanks a lot for such good material of php. | |
| shakil | 04-02-2010 |
| I want , How to pass Javascript variable value to PHP Variable | |
| smo | 04-02-2010 |
| Without reloading the page we can't pass JavaScript variable to PHP script. We can use Ajax to do that. | |
| Alieu | 19-11-2010 |
| I want a script that will allow me to pass values in php variables on to a different form | |
| Roshan | 10-05-2011 |
| I just want to play the variable between php and javascript. | |
| Harsh karwal | 04-09-2012 |
| hi, i am a fresher in PHP and trying to learn it. i need a code for display data on another page when some one submit his details like his name, his mbl no., his age etc.. in a form and after click on submit button the same data is display. | |
| Mano | 27-04-2013 |
| i have fill the value in textbox when click the button value are pass to new screen .How to pass the value? | |
| smo123 | 29-04-2013 |
| You can pass data from child window to parent window and same way you can try by reversing. | |