How to use the query string in PHP
This article tells you how to pass variables to a PHP page using the query string, and how to access them from that page.
Introduction
Have you ever seen a URL which looked like "www.example.com/page.php?mode=1&style=red"? Well, this page is being passed variables and their values through the query string, here the variables "mode" and "style" are being passed, with values "1" and "red" respectively. The question mark indicates the start of the query string and the ampersand, &, symbol seperates variable=value assignments. The page is then able to read these variables and react according to them, for example to display them to the user.
Passing a query string to a page
There are two ways to pass a QueryString to a page, the first is to enter it manually, for example:
<a href="page.php?mode=1">Mode 1</a>
The above HTML creates a link to a page passing the variable mode with the value "1".
An alternative, and perhaps more useful, way is to use HTML forms. The main thing to remember with forms is that you need to use the GET method to send information via the query string, for example:
<form method="GET" action="page.php"> Please enter your name: <input type="text" name="username" /> <input type="submit" value="submit" /> </form>
This code displays a simple HTML form with a text box and a submit button. When the user enters their name and presses submit, the information in the name box is passed to a page called "page.php" (specified in the form's action attribute) via the query string. So, if I entered "mooseh" and pressed submit, the form will call page.php?username=mooseh. Remember that "username" was what we entered as the text input's name attribute.
Accessing a query string element in a PHP page
In PHP, all the information passed via the query string is held in the $_GET super global array (prior to PHP version 4.1.0 it was called $HTTP_GET_VARS, but that's now depreciated). To access an item, type $_GET['varName'], where varName is the name of the variable in the query string.
To demonstrate, let's create page.php to process the information from the form above:
<?
if($_GET['username'] == "")
{
// no username entered
echo "You did not enter a name.";
}
else
{
echo "Hello, " . $_GET[’username’];
}
?>
So now, me typing in mooseh and pressing submit will generate the reply "Hello, mooseh".
Listing the contents of $_GET
Should you wish to find out everything that's in the query string, you can do so with the following code which displays the variables next to their values in a table:
<table border="1">
<tr><th>variable</th> <th>value</th></tr>
<?
foreach($_GET as $variable => $value)
{
echo "<tr><td>" . $variable . "</td>";
echo "<td>" . $value . "</td>";
}
?>
</table>
Conclusion
This article showed you how to pass information between pages with the query string, and a use which allows you to add some increased interactivity. There are a lot of other uses, for example selecting which section of a site to display based on a variable in the query string, and processing form data.
Categories: Basics Tags: introductions, PHP, query string, tutorial
How to Find the Current URL with PHP
The full URL to a page comes in three parts: The domain name, the path to the file then the filename, and the query string. For example, take the URL http://www.example.com/example/page.php?name=Bob. The three parts of this are:
1. The domain name: www.example.com
2. The path to the page: /example/page.php
3. The query string: name=Bob
So how do you find it all out with your own PHP scripts?
Categories: Basics Tags: introduction, PHP, tutorial, url
Find a visitor's IP Address with PHP
Do you want to know the IP address of a visitor? This can be useful for many reasons, such as tracking site usage or blocking access to specific people. Here's how you can find it using PHP.
In a PHP page, within the PHP tags, <?php ... ?>, you can retrieve the IP address of a user through the server variables array, which is contains information about the user and the server environment and is accessible from anywhere in your PHP script. To do this, you use the code $_SERVER['REMOTE_ADDR']. It works like a normal array, where REMOTE_ADDR is the key, and the IP address of the visitor is the value associated with that key.
Display The IP Address
So, if you want to display the IP Address to the user then the following page will suffice:
<?php echo "Hello! Your IP Address is: " . $_SERVER['REMOTE_ADDR']; ?>
Exploring the $_SERVER array
You might be wondering what other information you can get from $_SERVER, well you can find out with the following script which displays all the variables in it along with their values if set, in a HTML table:
<table border="1">
<tr><th>Variable</th><th>Value</th></tr>
<?
foreach( $_SERVER as $key => $value )
{
echo "<tr><td>" . $key . "</td>";
echo "<td>" . $value . "</td></tr>";
}
?>
</table>
Finally, the following code works harder to find the true IP of the user by checking for proxies:
function userIP()
{
//This returns the True IP of the client calling the requested page
// Checks to see if HTTP_X_FORWARDED_FOR
// has a value then the client is operating via a proxy
$userIP = $_SERVER['HTTP_X_FORWARDED_FOR'];
if($userIP == "")
{
$userIP = $_SERVER['REMOTE_ADDR'];
}
// return the IP we've figured out:
return $userIP;
}
Categories: Basics Tags: introduction, ip address, PHP, tutorial, web development
Generate a Month Calendar In PHP
This article shows you how to display a calendar for a given month, mainly using PHP's date() function.
The date() function
The date() function displays the date in your desired format, at a given time. It works by accepting one or two parameters, the first is a string with the format, the letters in the string tell the function how to format the date. You can see what formatting options are available by seeing the PHP Manual entry for date(). If you just pass it a string to format the date then it uses the current time, however if you pass a timestamp (a standard way of representing time: the number of seconds since a set time in the 1970s), then it will output that date with the given format.
Generating Random Numbers in PHP
To create random numbers in PHP, you can use the rand() function call, which takes either zero or, optionally, two parameters determining the minimum and maximum random numbers (inclusive) that you'd like. If you don't specify a maximum then it will default to a value, RAND_MAX, set in the PHP configuration. The function returns an integer, generated "randomly." (Computers can't generate real random numbers, but this tries and is suitable for most purposes.)
You can get the value of RAND_MAX with the function getrandmax(). Then if you desire a random number larger than that, you have to specify the min and max bounds as parameters, eg rand(0, 100000) will return a random number between 0 and 100000 inclusive - so both 0 and 100000 can be returned.
For example:
<!--?php // random number between 0 and RAND_MAX: echo rand(); // output: 28688 (for example) // random number between 37 and 50: echo rand(37, 50); // output: 44 // find out the value of RAND_MAX: echo getrandmax(); // output: 32767 // get a larger random number by specifying min and max: echo rand(0, 1000000); // output: 351990 ?>
The output shown in the comments above is as an example. Since it is generating random numbers, the numbers generated are very likely to be be different every time.
Categories: Basics, PHP Tags: PHP, random numbers, tutorial
How To: Find Items in PHP Arrays
The problem: we have an array of items in PHP and we want to find out if a specific item is in the array. In code we can define the array as:
IE we have an array called $fruitBasket which contains 5 strings, each of which is the name of a fruit. We want to find out if there is an Apple in the $fruitBasket - is there an element "Apple" in the array?
We do this with the following code:
<? // create an array of strings called $fruitBasket:
$fruitBasket = array( "Apple", "Orange", "Mango", "Lemon", "Pear" );
// use the in_array() function to check if "Apple" is in the array:
if( in_array("Apple", $fruitBasket) )
{
echo "Apple is in the array";
}
else
{
echo "Apple is not in the array";
}
?>
This code uses the in_array() method to check if the element "Apple" exists in the array $fruitBasket:
in_array("Apple", $fruitBasket)
in_array() takes two parameters here: firstly the object we're looking for, in this case "Apple", and secondly the array which we're looking in, $fruitBasket. It then returns a boolean value: true if "Apple" is in the array, or false if it isn't.
References: php.net manual: in_array() function
What is the difference between require() and include() in PHP?
The key difference between require() and include() is that if you require() a file that can't be loaded (eg if it isn't there) then it generates a fatal error which will halt the execution of the page completely, and no more output will be generated. On the other hand, if you include() a file that can't be loaded, then this will merely generate a warning and continue building the page.
What one you should use depends on the situation; require() is best suited for loading files that are essential to the rest of the page - for example if you have a database driven website then using require() to include a file containing the database login and password is clearly preferred over using include(). If you used include() in this situation, then you may end up generating more warnings and errors than you had intended.
include() should be used when it isn't essential for that file to be loaded to execute the page. This is best used in situations where the file isn't essential to the processing of the page (for example a footer file), so if the file isn't present then the user can still view the site. You should, of course, make sure that all files you include() and require() are going to be available.
In PHP versions prior to 4.0.2. there was slightly different behaviour of require(). If you used a require() statement in an if block then the require() statement will always make sure that the file you're require()ing is readable, regardless of whether the condition was true for that if block to be processed. This is best illustrated with the following code example:
<? $a = 1;
if($a == 2) {
require("header.php");
}
?>
In this example, PHP versions before 4.0.2. will always make sure that header.php is available, but it will only actually execute the contents of it if $a is equal to 2.
From php.net:
Note: Prior to PHP 4.0.2, the following applies: require() will always attempt to read the target file, even if the line it's on never executes. The conditional statement won't affect require(). However, if the line on which the require() occurs is not executed, neither will any of the code in the target file be executed. Similarly, looping structures do not affect the behaviour of require(). Although the code contained in the target file is still subject to the loop, the require() itself happens only once.
How to use PHP in pages with a .html extension (or any other)
To be able to use php code on a page with an extension other than .php, you need a server which supports .htaccess files.
To add an extension to be parsed for php, create or edit a file called .htaccess (with the dot first) containing the following line:
AddType application/x-httpd-php .html .moo .htm
This tells the server to check for php code and execute it in files with extensions .html, .moo or .htm. So upload that .htaccess file in the same folder as your .html files with PHP code inside them (using PHP tags: <?php ... ?>) then when you view them in the browser, the PHP should be dealt with as you'd expect from a PHP page.