Introduction - php Passing Variables between Pages
In this tutorial about passing php variables, you will learn how to access PHP variables from one page to another.
This tutorial will illustrate how to collect information with a form; send that information to another webpage; encode that information into links, use session data to track data across the the user's entire visit and place cookies on the user's machine to be used by a php script for tracking and passing data.
The fact that you have made it to this webpage means that you have probably started coding a php script, everything is looking great and you are ready to send your collected data to another page or script to do some more work on that data. If your experience is anything like my early php coding experiences with passing variables - your "hello world" program with the echo function does not really offer much instruction on passing data to another webpage. Quickly frustrated because everything I found online assumed that passing variables is something the reader should already know, I decided to create this website and and document new coding techiniques as I learned them. I hope this tutorial helps you learn php.
Important Get The PHP Manual The php manual is an indispensable tool for a php developer. It gives examples of code and built-in functions that will help you grasp how php works. It can be found at php.net . For those running a Windows Operating system, it comes in an easy-to-use help program. You can download it here http://www.php.net/download-docs.php.
Passing $_POST to Another Page
Here is a simple example of how to pass a PHP variable from one page to another with the post method, and how to use the POST super global array to make your coding experiences more efficient and less time-consuming. We will start this lesson by creating php files.
First create a file named passing-vars.php .
Second create an HTML FORM on the passing-vars.php file to collect user data.
Third you create a file named catching-vars.php and then write some php code in it to handle the variables.
Explanations and How To
If you are new to this stuff, the explanations in the following list should help explain things.
Creating php files --
Obviously if you are going to write php scripts you will need to know how to create php files.
The good news is that creating php documents is arguably the easiest part!
Simply open a text editor like notepad and save your file as YourFile.php
You can also do this for "HTML," "ASP," and "TXT" files.
However, with the exception of text files, to display correctly you must place them into a web-server directory and open them with a web-browser.
What is Hosting ?-- A hosting account is space on a web-server that your website files reside on that is provided by a 3rd party company for a price.
If you don't want to pay a 3rd party you can set up your own server. Doing it yourself will require a level of expertise that is beyond the scope of this tutorial.
I strongly suggest installing a local test http server on your personal computer. Apache is used in these examples. Apache is generally easy to learn, it's free, and it has been around since about as long as the Internet itself. In fact, you may want to look at Installing Apache and Installing PHPfor instructions on setting up apache and php on your local machine.
FORM -- Forms are used to collect text data from Internet users. They are made up of text boxes and submit-buttons. Data collected with FORMS can vary greatly depending on website types.
Mrarrowhead.com for example has a FORM at the bottom of each page for collecting user feedback and comments about the website. When the Submit button is clicked, whatever text the user typed into the FORM'S input areas will be passed along to the web server which uses the value in the input box's -- name=variablename attribute to create global variables that live in the server as super-global-arrays, POST or GET. For now it is enough to know that those variables have a global scope, and are usually sent to the script that you have pointed your form to using the form tag's action="". The example form in this tutorial is pointing to a script called catching-var.php.
catching-var.php will process the data passed to it from the by the form we place on "passing-var.php."
Copy the HTML below, paste it into a text editor and then save the file as "passing-var.php"
Look closely at the "FORM TAG." The server KNOWS, so-to-speak, to handle this data as "POST" because the method=POST attribute was set in the form. If this attribute is omitted or not set, it defaults to "GET"
When submitted, the address bar will not contain the familiar
This is because the POST method, contrary to GET does not pass variable information in the address bar.
Although, it is noteworthy to mention that both of these methods CAN be employed simultaneously providing added advantages such as hiding some of the information passed while leaving some in plain sight. From a development point of view, the ability to change-up the variable-names and values in the address-bar is much faster than recreating the forms that send the data while testing.
Copy the PHP code below and paste it into a text editor and then save the file as "catching-var.php."
Open your web browser and navigate to passing-var.php. Insert some data into the form and submit it.
Now the catching-var.php script has access to the data sent over to it by the HTML FORM your created -- passing-vara.php . If all is working correctly, you should see the data that you entered in the output of catching-var.php.
That concludes the POST tutorial on learning how to pass variables from one page to another in php.
Next in line is the "GET "method. GET is teh DEFAULT methad used by HTML forms.
If you do not specify POST in your form's action attribute "action=post" then "GET" will be used.
Passing variables in php with $_GET
The "GET METHOD" allows you to see the variables along with the values stored in them in your web browser's address bar as they are passed to the another page. Additionally, paasing variables encoded into hyperlinks uses GET.
Let's Take a look at how this is done.
GET Anchor / Hyperlink Link Example
Get a Decent Text Editor
If you read the POST tutorial then you have already learned how to make php files with a text editor. If not, then need to go and get a good text editor. I suggest notepad++. It is chocked full of features for just about every kind of programming language you can think of; and the best thing about it is -- it is free. It will cost you nothing; not a dime! However, for those of you who can afford it, I strongly encourage you to make donations to the author of Notepad++ for giving us all such a great text editor. Also JUST FYI. I get nothing for promoting it. I plugged it because I honestly like it.
Now that you have a good text editor let's learn how to write php to handle variable sent with "GET."
First Complete the Following Steps:
Create two .php files -- passing-var.php and catching-var.php.
Place those files into a directory on your web server that is able to serve php scripts to the public.
On Apache it is usually called htdocs
Passing php variables in HYPERLINKS - GET
Using GET for passing variables from one page to another page in PHP can be more versatile than using "POST", especially when dealing with dynamic variable data and user input. "GET" is the method utilized automatically when variables are coded into hyperlinks.
First - Coding variables into hyperlinks.
When you follow this link to "catching-var.php" :
These variables ----- > name=Shaun&Lname=Morgan
will be available to catching-var.php via the the $_GET super global array -- $_GET['name']&$_GET['Lname']
Now place the following code at the top of the php script page - catching-var.php
Second - How to Use GET Method With HTML FORMS
You actually see "GET" variables all the time while you are browsing the Internet. They are the cryptic-looking text after the Question Mark "?" behind the web addresses in your navigation bar. They are strings of text that represent variable names and data that is paired up and then passed to another page for processing by a web script or some other programming language.
After testing the catching-var.php file, lets go back and do something a little different.
Instead of just accessing the GET variable lets do something useful with it.
Next we will code the data that was sent into yet another URL to be passed on to yet another page etcetera.
The resulting link would be:
You can also pass variables in the "action" attribute of the form tag like this:
Keep in mind that passing php variables in hyperlinks only works if the user clicks on the links.
Security Concerning the GET Method
The "get method" passes data in the URI. If you look at your web browser's address bar after submitting a "get method" form, you will notice that you can view all variables and values pairs that were written into the page's HTML forms and links. They can also be modified and resubmitted by the user which can make GET data insecure by itself.
Malicious input can be added to GET values in the web browser in an attempt to launch an injection attack against a web server. People who perpetrate injection attacks attempt to cause harm to remote machines by sending servers parameters often encoded into a web browser's address bar. PHP programmers should always watch out for this kind of attack and be proactive about stopping attackers before they compromise their websites.
Basic Security Tips
Use Functions likestriptags() to keep attackers from injecting unwanted HTML and other code into your web site. The striptags() php function removes HTML and other scripting tags from the content it processes.
Write code that tracks number of times a web attacker attempts submit a form. Throw an error and write soem code to deal with it when it is attempted toom any times
POST is slightly more secure than GET because a the variable values you are sending are not visible.
Example Passing Variables Using $_SESSION['']
What if I want to pass a certain set of variables several pages or every page on my website?
Do I have to keep coding $_POST or $_GET into the HTML on every page?
Answer: No - You can use Sessions Or Cookies Instead.
SESSIONS will allow you to pass php variables and values to every page a user visits on your web site.
Every time a person visits a site that uses php session_start() a new session is started.
The user is also assigned an unique SESSION id number
Sessions are valid until the session expires (the expiry value is set in the php.ini file), or until the user closes his or her browser.
SESSIONS are php super global arrays
The syntax for accessing session variables is -- $_SESSION['name of variables'].
Using Sessions can make passing variables between pages much easier.
$_SESSION['name of variables']is available to programmers anywhere on the server that he/she invokes the session_start(); php function.
Example of Form Tag and $_SESSION[''] Variables
First send the variable to a script
Move $_POST Variable Contents into $_SESSION Variable
Call: "session_start()": on testScript.php
Explanation of Example Script
First we use a form to send POST data to a php script -- testScript.php
Next testScript.php calls up the session_start() function, creating a session variable --- $_SESSION['name'] ---and sets it to the value found in $_POST['name']values. Now the $_SESSION['name'] variable can be accessed and used from any page on the server
Accessing $_SESSION Variable
You must call the "session_start()" function in php to gain access to the $_SESSION super global array.
How To Make Browser Go Back To Last Page With Php8/12/2014After submitting an HTML form or clicking a link encoded with variables and information, it is often desirable to the programmer that the user's browser be automatically redirected - to go back to the previous page. The simplest way I've found to accomplish this is by using a php built-in function called - header() and a PHP built-in variable called $_SERVER['HTTP_REFERER']
Binary Search User FunctionThe code in the example is for finding a given value in a sorted array.If the value is not found the function will return the position of the location where it the value should be.
Conditional Statements If Else & Switch CaseIf ElseIf else is the bread an butter of programming - so-to-speak. if-else and Case Switch are known as conditional operators; they create conditions or criteria that a block of code must meet in order to accomplish a certain task. Conditions make up the logic of a script.When writing scripts there is usually a need to compare something or make a decision, for e
Textarea Code Overflows and Runs Out Onto PageMy Decision to Use Textarea TagWhile working on a script for to edit content, I ran into few problems. First - because mrarrowhead is a website about building websites using php, I have had to battle with the best way to display the example code on my webpages.I tried using the HTML special chars & lt; and & gt; respectively but I found it much too time consuming and tedious trying to convert the HTML code ba
Convert Unix Timestamp to Readable Date Time PHPUser Functionstring function convert_timestamp(string $file_in, int $column,string $dateformatReturnsReturns a string representation of the file with one column convertedstring $file_inPath To the Fileint $co
How toPrint PHP ArraysThings to Consider AreArray Type- Single Array or Multidimensional Array?Class-Object Array?Raw Dump of Array Keys and Values?Array Data Precision Extraction Methods?Formatted Array Data - HTML tags - Str
Testing for Odd/Even Numbers - PHPExample - Banner Rotation PHP Script Odd/Even NumbersSimple Php Tutorial Creating Odd / Even Testing% modulus operator.$_SESSION['x'] % 2;In this example I will demonstrate a php script that I use to rotate two Ad banners.This results in a script that changes up the banner every time the user clicks
Using Cookie Variables in PHPSetting cookies in php is pretty straight forward. There is a php functionsetcookie();This function must be called before any anything else on the page or it will fail. There are two options to address this.Use ob_start to Buffer contentYou can either make sure that setcookie() is the first thing you call in your script - which is often just not a possibility.
Uzipping Files on Your Web ServerIf you are using a free hosting account with godaddy.com and many of the other Free hosts out there, you may have found that they don't offer you a lot of features. One feature that I could not find on Godaddy.com free hosting accounts was a utility that would unzip my files after I uploaded them to my server. I had a dating site software that I was trying to install after I uploaded the zip files to my hosting server.Thus, I wrote a PHP
Passing data from one form to another formTo pass php data from a form and then catch that data into another form one way to accomplish this task is to intermingle your php code into your HTML to dynamically capture variable values. This particular method is useful in a scenario where the user updates something via a post (it could be a text file or database) and then the user is returned to the page where the form is located to find various fields popula
JIT - Just in Time Compilers JIT refers to a special software that is found in web-browsers, and scripting engines such PHP's Zend. (My understanding of ZEND is that it produces byte-code and functions similar to other JIT compilers). For this discussion, without trying to be overly technical on what a JIT is or isn't -- JIT will simply mean software that turns scripts into executable code for whatever machine it is running on. The concepts of JIT and it's various
Store Image URL in DatabaseRetrieve Image with PHP Script Saving URL Text in Database Saving image filesystem paths, of an image file in the database is easier than saving the whole image. Storing whole images requires converting the image files into bit-streams then saved into the database as binary and then changing them back into th
Variable Variables in PHPi-1Every so often when you are writing a php file, we all run into a situation where we would like for the name of the string that is inside of your php variable to be converted into the actual name of another variable. After a fair amount of hunting around the internet and getting sent off into PHP code hunting limbo for a few hours, I suddenly remembered that this was something that I had found a solutio
Explanation of PHP Basic Syntax --New to PHPPhp is a language that is very much like writing c. The best feature of PHP versus c is that it is designed primarily to be used on WebPages -- allowing the author to intermingle their php code and the HTML on the same page. Being able to mix these two languages together provides a very flexible environment that allows the author to code some very nice dynamic content. PHP is called a server side scripting l
Dreamweaver - WISIWIGDreamweaver is a tool that arguably could be called the industry standard for web design.Dreamweaver, is an Adobe product that originally belonged to Macromedia. They sold out to Adobe a few years ago. I have been using Adobe/Macromedia Dreamweaver for about ten years. I am today using the Dreamweaver version that came packaged with Adobe CS 4. I started out with Dreamweaver 4. Since then Adobe has given this software a slightly different face and
Filezilla Ftp Client, FTP SERVER vs WsftpBy D.Shaun MorganWhile I was writing this article, about halfway through, I realized that it would be unfair to tell my readers about Filezilla without also mentioning another very good FTP client called WSftp. So, I backtracked and browsed over to ipswitch.com website to take a look at the latest version. The fact is, when I first started building websites, WSftp was actually the first FTP client that I used. I don't know if Fil
Notepad++Download Notepad Plus Plus Notepad plus plus is an open source, free text editor. It is an ideal choice for many programming and scripting languages. Example - How to write c++ with Notepad Plus PlusExample - How to write HTML with Notepad Plus Plus
Php file functions, Opening a file in php, reading a file in php, writing a file in phpIn this tutorial we will look at the most commonly used file functions used in php. The examples below should be pretty familiar to the seasoned php scripter, but they are useful nonetheless. We will end this tutorial with a php script and an html form that will read the contents of a file into a string variable and output it into a textfield for editing. You can try the script out be
PHP -- How to Protect My Email Form / Contact Form Against Spam BotsAuthor D.Shaun MorganRandom Name Fields to Stop SpambotRandom Name Fields to Stop SpambotExample Random Name Fields ScriptExample Message ScriptStopping Spam Bot With
How to get images out of mysql database with php and use them on my webpagesRetrieving Images From Mysql Database With phpAuthor D.Shaun MorganPHP Version - PHP 5xMysql Version - 5Tutorial OutlineDownload Test ScriptsCreating a Test Mysql DatabasePhp Script to
Making Money on the InternetSign up for this series of free money making articles Name Email Since you are reading this I am going to assume that you are looking to either start or improve a venture of starting or improving yo
Storing Images in Mysql DatabaseTutorial OutlineCreating a Test Mysql DatabaseExample php Database FunctionExplanation of Database FunctionPhp Script to Load Images in Mysql DatabaseExplanation of Image ScriptSee Also
Visual example of how PHP handles the super-global array variable "$_POST"Author D.Shaun MorganVersions and Skill LevelPHP Version - PHP 5xReader skill level - BeginnerXHTML 1.0 Transitional - interchangeable with HTML 4.0See AlsoHow can I pass a PHP variable from one page
Explanation of a Basic PHP FunctionWhat is a PHP function?In PHP a function represents a block of instructions that perform a task. A PHP Function allows the user to re-use blocks of script without having to rewrite all the code every time it's needed. This is useful for repetitive tasks that perform the same jobs over and over.PHP has a large number of built-in function
When learning PHP to build a website, one of the very first things that any newcomer, or beginner needs to learn is how to use HTML or XHTML ( will mean the same for this tutorial.) forms to collect information from users. Those data are usually email addresses, names, birthdays, and sometimes private information like credit card info, SSN, and home addresses. (The scripts in this tutorial are not meant for processing security sensitive data. It is only intended to teach you h
How to Install PHP 5.x.x.x on WindowsThis is beginner's how-to manual explaining how to quickly setup a PHP 5 installation on a Windows PC. You must have an Apache webserver installed and working on your personal computer.This tutorial was written primarily for configuring a test server.Below is a list of what you need before you start trying to install PHP.An Apache server installed and running (