Skip to content
Fix Code Error

PHP Pass variable to next page

March 13, 2021 by Code Error
Posted By: Anonymous

It seems pretty simple but I can’t find a good way to do it.

Say in the first page I create a variable

$myVariable = "Some text";

And the form’s action for that page is “Page2.php”. So in Page2.php, how can I have access to that variable? I know I can do it with sessions but I think it’s too much for a simple string, and I do only need to pass a simple string (a file name).

How can I achieve this?

Thanks!

Solution

HTML / HTTP is stateless, in other words, what you did / saw on the previous page, is completely unconnected with the current page. Except if you use something like sessions, cookies or GET / POST variables. Sessions and cookies are quite easy to use, with session being by far more secure than cookies. More secure, but not completely secure.

Session:

//On page 1
$_SESSION['varname'] = $var_value;

//On page 2
$var_value = $_SESSION['varname'];

Remember to run the session_start(); statement on both these pages before you try to access the $_SESSION array, and also before any output is sent to the browser.

Cookie:

//One page 1
$_COOKIE['varname'] = $var_value;

//On page 2
$var_value = $_COOKIE['varname'];

The big difference between sessions and cookies is that the value of the variable will be stored on the server if you’re using sessions, and on the client if you’re using cookies. I can’t think of any good reason to use cookies instead of sessions, except if you want data to persist between sessions, but even then it’s perhaps better to store it in a DB, and retrieve it based on a username or id.

GET and POST

You can add the variable in the link to the next page:

<a href="page2.php?varname=<?php echo $var_value ?>">Page2</a>

This will create a GET variable.

Another way is to include a hidden field in a form that submits to page two:

<form method="get" action="page2.php">
    <input type="hidden" name="varname" value="var_value">
    <input type="submit">
</form>

And then on page two:

//Using GET
$var_value = $_GET['varname'];

//Using POST
$var_value = $_POST['varname'];

//Using GET, POST or COOKIE.
$var_value = $_REQUEST['varname'];

Just change the method for the form to post if you want to do it via post. Both are equally insecure, although GET is easier to hack.

The fact that each new request is, except for session data, a totally new instance of the script caught me when I first started coding in PHP. Once you get used to it, it’s quite simple though.

Answered By: Anonymous

Related Articles

  • How to write dynamic variable in Ansible playbook
  • ORACLE APEX SQL ACCORDING TO THE FORTNIGHT OF THE…
  • useEffect Error: Minified React error #321 (GTM…
  • Stateless vs Stateful
  • Do sessions really violate RESTfulness?
  • Adding Dynamic Input Fields With VueJs
  • Reference — What does this symbol mean in PHP?
  • laravel vuejs/axios put request Formdata is empty
  • Vue.js page transition fade effect with vue-router
  • binding backbone form view UIto model change to…
  • Adding a UserCreationForm to html in Django
  • How do you use script variables in psql?
  • javax.faces.application.ViewExpiredException: View…
  • How find a file with part of his name in PowerShell
  • rails and backbone working together
  • Created variable inside for loop can't be accessed…
  • How to submit Polymer forms to PHP and display response
  • Form field border-radius is not working only on the…
  • Why the value of input file missing when I input the…
  • Trying to integrate Ant Design using Sass and…
  • Import Python Script Into Another?
  • Problems Installing CRA & NextJS from NPM…
  • Avoid creating new session on each axios request laravel
  • Understanding PrimeFaces process/update and JSF…
  • What's the difference between binding to [[var]] and…
  • How to dispatch a Redux action with a timeout?
  • What are the undocumented features and limitations…
  • How can I find the product GUID of an installed MSI setup?
  • Why is Ember throwing "Uncaught Error: Assertion…
  • How to have Aurelia child routers with their own…
  • How can I check for "undefined" in JavaScript?
  • Pass variables between two PHP pages without using a…
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • What is the proper way to render an async function?
  • Backbone and jQuery Mobile : same header on all pages
  • jQuery Mobile: document ready vs. page events
  • What should I do if the current ASP.NET session is null?
  • Collapse a vector of function calls in to one line,…
  • How can I pass modelformset_factory validation in Django?
  • Check if text input field is empty or includes a number
  • Why is creating a new array instead of emptying the…
  • How to use Servlets and Ajax?
  • Smart way to truncate long strings
  • Getting the closest string match
  • "Thinking in AngularJS" if I have a jQuery background?
  • Why do we need middleware for async flow in Redux?
  • How to solve Internal Server Error in Next.Js?
  • commandButton/commandLink/ajax action/listener…
  • PHP parse/syntax errors; and how to solve them
  • Getting started with Haskell
  • The definitive guide to form-based website authentication
  • Secure hash and salt for PHP passwords
  • dynamically plot multiple variables in shiny dashboard R
  • How to access to form variables created by reflection c#
  • Angular: Can't find Promise, Map, Set and Iterator
  • Django - update inline formset not updating
  • Set value to vaadin combobox(polymer)
  • Logging best practices
  • Differences between action and actionListener
  • How to dynamically add and remove form fields in Angular 2
  • How can I pass a wct test while rearranging children…
  • Why does C++ code for testing the Collatz conjecture…
  • CSS not applied to Polymer 2 web component in Chrome
  • vaadin combobox load wrong custom style
  • What is your most productive shortcut with Vim?
  • Send email with PHP from html form on submit with…
  • How to read through or navigate through a json object?
  • How do I count unique visitors to my site?
  • Vue-Router returns "Cannot redefine property: $router" error
  • Cannot find control with name: formControlName in…
  • NEXT.JS with persist redux showing unexpected behaviour
  • Trouble with Next js + Express deployment using Zeit Now
  • How to prevent scrolling the whole page?
  • How to add methods or data on current Vue instance?
  • Triggering text area by clicking related select/checkbox
  • Vuejs Property or method is not defined on the…
  • data.table vs dplyr: can one do something well the…
  • TypeScript metadata reflection references other…
  • Cookies vs. sessions
  • display other inputs based on the value of another…
  • Ukkonen's suffix tree algorithm in plain English
  • How do I compare sequential characters in two…
  • delete map[key] in go?
  • Upload video files via PHP and save them in…
  • Best practice multi language website
  • How would I be able to multiple select and pass data…
  • nextjs get back to page before 404 from page after 404
  • How to use java.net.URLConnection to fire and handle…
  • RESTful Authentication
  • Javascript Uncaught TypeError: Cannot read property…
  • Multiple submit buttons in the same form calling…
  • How to build next.js production?
  • How does PHP 'foreach' actually work?
  • How Spring Security Filter Chain works
  • IOException: The process cannot access the file…
  • Reference - What does this regex mean?
  • How to deploy next.js on AWS Elastic Beanstalk?
  • How do you parse and process HTML/XML in PHP?
  • What are sessions? How do they work?

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How to change the status bar color in Android?

Next Post:

How to call a JavaScript function from PHP?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error