PHP Super Globals
Superglobals are built-in variables in PHP that are always available in all scopes. Available in all scopes mean these variables can be accessed from any part of your application/project. These are the super global variables we have in PHP at the time of this writing:
1. $GLOBALS
Any variable assigned to this super global is accessible in any PHP script in your application. For example, let’s assume we have 2 php files like so:
index.php
1 2 3 4 5 |
<?php $name = "Prosper"; $GLOBALS['name'] = $name; |
claim.php
1 2 3 4 5 |
<?php echo $GLOBALS['name']; // returns Prosper |
2. $_ENV
An associative array of variables passed to the current script via the environment method.
Essentially, there are some variables that you want access to in your development environment, test or production environment. This superglobal helps you to return environment variables from the web server.
For example, you can insert values into the $_ENV array like so:
1 2 3 4 5 6 |
<?php $_ENV['DATABASE_URL'] = 'app.database.herokuapp.com' echo "my database url is ". $_ENV['DATABASE_URL']; // returns app.database.herokuapp.com |
You can also just try to print out the values in $_ENV array.
1 2 3 |
<?php print_r($_ENV); |
On my localhost machine where I actually use Vagrant and Laravel Homestead. I actually see something like so:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
"APP_DEBUG" => "true" "APP_KEY" => "xxxxxxxxxx" "DB_HOST" => "localhost" "DB_DATABASE" => "prego" "DB_USERNAME" => "homestead" "DB_PASSWORD" => "secret" "CACHE_DRIVER" => "file" "SESSION_DRIVER" => "file" "QUEUE_DRIVER" => "sync" "MAIL_DRIVER" => "smtp" "MAIL_HOST" => "mailtrap.io" "MAIL_PORT" => "2525" "MAIL_USERNAME" => "null" "MAIL_PASSWORD" => "null" "MAIL_ENCRYPTION" => "null" "CLOUDINARY_API_KEY" => "xxxxxxxxx" "CLOUDINARY_API_SECRET" => "xxxxxxxxxxx" "CLOUDINARY_CLOUD_NAME" => "xxxxxxxxxxxx" |
They are there because I defined them when I was setting up my application.
3. $_SERVER
$_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server. There are predefined keys and values in this array already, they all provide very useful information about your web application, scripts and web server.
Go ahead and run this in a php script
1 2 3 |
<?php print_r($_SERVER); |
I ran this on a tutorial project I developed here on goodheads called Prego. This is the result:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
"APP_ENV" => "local" "USER" => "vagrant" "HOME" => "/home/vagrant" "FCGI_ROLE" => "RESPONDER" "QUERY_STRING" => "" "REQUEST_METHOD" => "GET" "CONTENT_TYPE" => "" "CONTENT_LENGTH" => "" "SCRIPT_FILENAME" => "/home/vagrant/source/lara-workspace/prego/public/index.php" "SCRIPT_NAME" => "/index.php" "REQUEST_URI" => "/post" "DOCUMENT_URI" => "/index.php" "DOCUMENT_ROOT" => "/home/vagrant/source/lara-workspace/prego/public" "SERVER_PROTOCOL" => "HTTP/1.1" "GATEWAY_INTERFACE" => "CGI/1.1" "SERVER_SOFTWARE" => "nginx/1.8.0" "REMOTE_ADDR" => "192.168.1.1" "REMOTE_PORT" => "59904" "SERVER_ADDR" => "192.168.1.109" "SERVER_PORT" => "80" "SERVER_NAME" => "prego.dev" "REDIRECT_STATUS" => "200" "HTTP_HOST" => "prego.dev" "HTTP_CONNECTION" => "keep-alive" "HTTP_CACHE_CONTROL" => "max-age=0" "HTTP_ACCEPT" => "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8" "HTTP_UPGRADE_INSECURE_REQUESTS" => "1" "HTTP_USER_AGENT" => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36" "HTTP_ACCEPT_ENCODING" => "gzip, deflate, sdch" "HTTP_ACCEPT_LANGUAGE" => "en-GB,en;q=0.8,en-US;q=0.6,it;q=0.4,nb;q=0.2" "HTTP_COOKIE" => "XSRF-TOKEN=eyJpdiI6Ijg4MHlMNjd5REh4RCtsVloxMVNyRnc9PSIsInZhbHVlIjoiVEx3TlE4Y0E4TXpDU2doNDJzbmJISlNLblk1akxKZzZ4a2Z6XC9pcHhGcWxvSVMyWGUzbTdsbVA5R2pKUXdDeHZpY1B0XC90cUdMemxlaWt1UW83blBlUT09IiwibWFjIjoiMDAxZTg1ZWVjMGMzOWUxOGYwNzUwMDRmZjViMDZhZDk1MTBhZmY5OTY3M2RlMzcxMDNiMjZjMDJhM2Q1NDU1OCJ9; laravel_session=eyJpdiI6IjIrN0o1dlJHZVZndm5OdXNoMnA1U0E9PSIsInZhbHVlIjoidGRac2ZUUHl0anJ1RlRwZXNhVWdSUThaOHRvaUw0aUxrNzBSNEphSU9PRUFCVVwvSmx1OGxSVTVxNU1YYWZlTVhrenlvNkNNVFcwQm4rVWpYZmJTSnh3PT0iLCJtYWMiOiIwZjAxZDg2ODM0YWIxNDlhNjExY2FjOTI4M2YxNTg1NWFiNGY5MzQzYTI3MWU4YTUzZWYwNTVhNzcwYTU5MTJiIn0%3D" "PHP_SELF" => "/index.php" "REQUEST_TIME_FLOAT" => 1448013469.6862 "REQUEST_TIME" => 1448013469 "APP_DEBUG" => "true" "APP_KEY" => "oiQgAAnIAKF6uL7QneFy2MxfbbQdknAF" "DB_HOST" => "localhost" "DB_DATABASE" => "prego" "DB_USERNAME" => "homestead" "DB_PASSWORD" => "secret" "CACHE_DRIVER" => "file" "SESSION_DRIVER" => "file" "QUEUE_DRIVER" => "sync" "MAIL_DRIVER" => "smtp" "MAIL_HOST" => "mailtrap.io" "MAIL_PORT" => "2525" "MAIL_USERNAME" => "null" "MAIL_PASSWORD" => "null" "MAIL_ENCRYPTION" => "null" "CLOUDINARY_API_KEY" => "xxxxxxxxx" "CLOUDINARY_API_SECRET" => "xxxxxxxxx" "CLOUDINARY_CLOUD_NAME" => "xxxxxxxxx" |
So if you want to get the IP address of the server, you can just access it like so:
$_SERVER['SERVER_ADDR']
or the route that ran the script $_SERVER['REQUEST_URI']
.
4, 5. $_GET, $_POST
$_GET
and $_POST
are used to get information sent in the page request. Parameters sent in the URL otherwise known as query strings are made available by $_GET
. For example, this URL:
1 |
http://prego.dev/tutorial.php?id=5 |
… will send the parameter id
to tutorial.php, which you can then access the value in tutorial.php as $_GET["id"]
.
When you have a form submission that is sent using method="get"
, the values are appended to the URL so they are available using $_GET
. Forms submitted using method="post"
send their values in the body of the HTTP request; posted data is available in your script by using $_POST
. Here’s a sample web form which posts a username and password to a login script:
1 2 3 4 5 |
<form action="contact.php" method="post"> Name: <input type="text" name="full_name"><br> Message: <textarea name="msg"></textarea> <input type="submit" value="Send Message"> </form> |
The full_name value and msg value will be available as $_POST["full_name"]
and $_POST["msg"]
respectively in contact.php
6. $_REQUEST
The $_REQUEST
superglobal is like an alias. You can use it in place of either $_GET or $_POST.
7. $_SESSION
Sessions are needed to keep track of information about users in a web application as they move from one part of the application to another. So an example of that is this:
1 2 3 4 5 |
<?php // this_page.php session_start(); $_SESSION['first_name'] = 'prosper'; |
Now create another file and name it that_page.php
1 2 3 4 5 6 7 |
<?php session_start(); echo $_SESSION['first_name']; // returns 'prosper'; |
Once session_start() is called on this_page.php it starts a session and in that_page.php, the session_start() called here resumes the session so that the information is not lost.
8. $_COOKIE
A cookie is a small piece of data sent from a website and stored in the user’s web browser while the user is browsing it. Every time the user loads the website, the browser sends the cookie back to the server to notify the user’s previous activity. Cookies were designed to be a reliable mechanism for websites to remember stateful information (such as items added in the shopping cart in an online store) or to record the user’s browsing activity (including clicking particular buttons, logging in, or recording which pages were visited in the past).
$_COOKIE is a superglobal array that is used to retrieve the values of cookies that have been set using the setcookie
function.
Let’s set a cookie like so:
1 2 3 4 5 6 |
<?php setcookie('name', 'prosper', time() + 3600); print_r($_COOKIE['name']); // returns 'prosper' |
If you check your browser cookies, you will see a cookie with these details above.
9. $_FILES
This is an associative array of items uploaded to the current script via the HTTP POST method. It contains information about files you have uploaded via a form.
Create an index.php file like so:
1 2 3 4 5 6 7 8 9 10 |
<html> <body> <form action="process_upload.php" method="post" enctype="multipart/form-data"> <label for="file">Filename:</label> <input type="file" name="file" id="file" /> <br /> <input type="submit" name="submit" value="Upload File" /> </form> </body> </html> |
Create a process_upload.php file like so:
1 2 3 |
<?php var_dump($_FILES); |
Make sure you select a file, once you click submit, it redirects you to process_upload.php and dumps everything in $_FILES.
Please let me know if you have any questions or observations in the comments section below
- How to build your own Youtube – Part 10 - August 1, 2016
- How to build your own Youtube – Part 9 - July 25, 2016
- How to build your own Youtube – Part 8 - July 23, 2016
- How to build your own Youtube – Part 6 - July 6, 2016
- Introducing Laravel Password v1.0 - July 3, 2016
- How to build your own Youtube – Part 5 - June 28, 2016
- How to build your own Youtube – Part 4 - June 23, 2016
- How to build your own Youtube – Part 3 - June 15, 2016
- How to build your own Youtube – Part 2 - June 8, 2016
- How to build your own Youtube – Part 1 - June 1, 2016