PHP

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.

8 comments - What do you think?  Posted by Steven - April 19, 2012 at 6:04 pm

Categories: Basics   Tags: , , ,

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?

Read more...

5 comments - What do you think?  Posted by Steven - at 4:00 pm

Categories: Basics   Tags: , , ,

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;
}

7 comments - What do you think?  Posted by Steven - April 18, 2012 at 4:00 pm

Categories: Basics   Tags: , , , ,

Write Text on to an existing PNG image using PHP

This article will tell you how to write text on an existing PNG image using PHP using PHP's image manipulation functions. The image functions require the GD library to be installed. This article is fairly basic, however some more detail on the basic functions used is included in the article, "write text on a dynamically generated image in PHP"

First, we need the source image. In this example, we're using an image called image.png (with dimension 150x150, though this code will work with any size of image) which is shown below:
source image
This image is going to be kept in the same directory on the webserver as the php file we're using to manipulate it.

Now it's time for PHP code to load the image. We make use of the function imagecreatefrompng() to get the image into PHP to manipulate. This takes the path to the image as a parameter. If the image can't be loaded then we'll tell it to die() and stop interpreting the page, however there are better ways of dealing with this error.

$im = imagecreatefrompng("image.png");
// if there's an error, stop processing the page:
if(!$im)
{
die("");
}

Next, we'll define some colours for use in the image using the imagecolorallocate() function:

$red_background = imagecolorallocate($im, 255, 0, 0);
$black = imagecolorallocate($im, 0, 0, 0);

Now we get the dimensions of the image, using the imagesx() and imagesy(), which take the image resource as a parameter and return the width and height respectively:

// get the width and the height of the image
$width = imagesx($im);
$height = imagesy($im);

The next step is to draw a black rectangle on to the image to ensure that the text we write is visible. This step is optional, as you could write the text directly on to the image.
The coordinate system used in PHP is that the top left of an image is (0,0) and the bottom right is ($width, $height). We're going to draw the rectangle across the bottom 20px of the image, so we pass imagefilledrectangle two sets of coordinates: (0, $height-20) and ($width, $height). The coordinates we're passing - as the 2nd to 4th parameters) tell the method to draw a rectangle from a point on the left hand side, 20 pixels from the bottom, to the very bottom right of the image. The rectangle is then automatically filled black.

// draw a black rectangle across the bottom, say, 20 pixels of the image:
imagefilledrectangle($im, 0, ($height-20) , $width, $height, $black);

Now it's time to write the text on the image. In this example, we will write the text in the middle of the rectangle we just created. First we declare two variables, $font and $text, to store the int representing the system font we're using and the text we're going to write to the image, respectively.

$font = 4; // store the int ID of the system font we're using in $font
$text = "tiposaurus"; // store the text we're going to write in $text

Then we will calculate where the left edge of the text is. This is done by using imagefontwidth() to get the width of the system font we're using (which is fixed width, so all characters have the same width), then multiplying that by the number of characters in the string we're writing. This finds the length of the text in pixels. We then subtract that from the total width of the image and divide by two to find the left position, which we store in the variable $leftTextPos:

// calculate the left position of the text:
$leftTextPos = ( $width - imagefontwidth($font)*strlen($text) )/2;

Now we write the text to the image, using the imagestring() function passing the variables we created earlier as parameters (NB. As height we're using the image height minus 18 pixels, to estimate a decent fit in the box, rather than calculating the height in the same way as width.)

// finally, write the string:
imagestring($im, $font, $leftTextPos, $height-18, $text, $yellow);

Lastly, we send the image to the browser then clear it from memory:

// output the image
// tell the browser what we're sending it
Header('Content-type: image/png');
// output the image as a png
imagepng($im);

That's it! the output image is:
image with tiposaurus written on it
This will be shown in the browser whenever anyone accesses the php page we've just created!

To finish off, here's the code in full:

<?
// load the image from the file specified:
$im = imagecreatefrompng("image.png");
// if there's an error, stop processing the page:
if(!$im)
{
die("");
}

// define some colours to use with the image
$yellow = imagecolorallocate($im, 255, 255, 0);
$black = imagecolorallocate($im, 0, 0, 0);

// get the width and the height of the image
$width = imagesx($im);
$height = imagesy($im);

// draw a black rectangle across the bottom, say, 20 pixels of the image:
imagefilledrectangle($im, 0, ($height-20) , $width, $height, $black);

// now we want to write in the centre of the rectangle:
$font = 4; // store the int ID of the system font we're using in $font
$text = "tiposaurus"; // store the text we're going to write in $text
// calculate the left position of the text:
$leftTextPos = ( $width - imagefontwidth($font)*strlen($text) )/2;
// finally, write the string:
imagestring($im, $font, $leftTextPos, $height-18, $text, $yellow);

// output the image
// tell the browser what we're sending it
Header('Content-type: image/png');
// output the image as a png
imagepng($im);

// tidy up
imagedestroy($im);
?>

10 comments - What do you think?  Posted by Steven - at 12:21 am

Categories: Image Handling   Tags: , , ,

Rotating Images with PHP

This tutorial will show you how to rotate an image in your PHP scripts. You'll need to have the GD library installed to be able to use some of the functions we use in this guide, though this is included with most PHP installations so there's a chance you'll have it.

Image rotation in PHP is handled by a function called imagerotate(), which takes three parameters (and optionally a fourth, which deals with transparency and is beyond the scope of this guide). The first is the resource identifier which you obtain when you load the original image within your script, the second is the angle which you want to rotate the image and the third parameter is used when the image isn't going to be rectangular, and specifies the colour with which to fill the uncovered areas of the rotated image to make it into a rectangle (since all image formats require rectangular images).

Read more...

9 comments - What do you think?  Posted by Tiposaurus - April 17, 2012 at 2:12 am

Categories: Image Handling, PHP   Tags: , , , ,

Write text on a dynamically generated image using PHP

This tutorial will tell you how to write text to a blank dynamically generated PNG image in PHP. This is fairly simple, so it will just be the first step in a series of tutorials dealing with images in PHP. The image functions require the GD library to be installed.

Read more...

6 comments - What do you think?  Posted by Steven - at 12:29 am

Categories: Image Handling, PHP   Tags: , , ,

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.

Read more...

5 comments - What do you think?  Posted by Steven - April 16, 2012 at 12:10 am

Categories: Basics, PHP   Tags: , , ,

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.

1 comment - What do you think?  Posted by Steven - June 10, 2011 at 2:56 am

Categories: Basics, PHP   Tags: , ,

How To: Read a file's contents with PHP

PHP provides three built-in functions which allow you to easily read the contents of a file on your webserver. This is useful when, for example, another program may write information to the file and you could access that information through your script.

In this example, we're going to use the following example 5 line file, saved as file.txt:

line 1
line 2
line 3
line 4
line 5

In the same directory as file.txt, we're going to work with the PHP file test.php. We'll outline the file reading functions below.

readfile()

readfile() is the least useful of the file functions. As a parameter, it takes a string which specifies the location of the file to read - this can be relative or absolute; since our file is the same directory as the script, we just need to pass the string 'file.txt' as this paramter. We call the function using the code readfile('file.txt') and it prints out the contents of the file straight to the browser:

// readfile() writes the contents of the file straight to the browser
echo 'Contents of file.txt using readfile():<br>';
readfile('file.txt');

The disadvantage of readfile() is that it doesn't allow you to manipulate the file contents before displaying it - the next two functions we're going to look at will allow you to do that.

file()

The code file('file.txt') will read the contents of file.txt into an array, which you can then manipulate in your scripts and display yourself. Each line of the file is stored in a seperate element of the array, this means that we can access and manipulate each line of the file seperately using normal array notation.

// file() loads the contents of file.txt into an array, $lines
// each line in the file becomes a seperate element of the array.
$lines = file('file.txt');

// now loop through the array to print the contents of the file
echo 'Contents of file.txt using file():<br>';
foreach ($lines as $line)
{
echo htmlspecialchars($line) . '<br>';
}

// we can also access each line of the file seperately
echo '3rd line of the file: "' . htmlspecialchars($lines[2]) . '"<br>';

In this example, we've loaded the contents of file.txt into an array called $lines then used foreach to loop through the array and display each line on the user's browser. We then use $lines[2] to access the third line of the file (the element at array index 2, since line 1 is $lines[0]).

You may notice that we've used a function called htmlspecialchars() when displaying the file's contents - this enables that special characters used in HTML, such as > and " are displayed correctly. This illustrates the power of file() over readfile() since readfile() was unable to perform this kind of processing.

get_file_contents()

The last method we will look at is get_file_contents('file.txt') which is similar to file() however rather than returning an array, it returns a string with all the lines of the file. We can manipulate and display this in a similar way as with file():

// file_get_contents() reads the file and places the contents in a string
$fileString = file_get_contents('file.txt');
echo 'Contents of file.txt using file_get_contents():<br>';
echo nl2br( htmlspecialchars($fileString) );

Since we have no way of seperating the lines with this method, we've used the nl2br() function which converts line breaks in the string (represented by the special character n) into the HTML line break <br /> so that the file will display correctly on the visitor's browser.

The full contents of test.php is below:

<?php
// file() loads the contents of file.txt into an array, $lines
// each line in the file becomes a seperate element of the array.
$lines = file('file.txt');

// now loop through the array to print the contents of the file
echo 'Contents of file.txt using file():
';
foreach ($lines as $line)
{
echo htmlspecialchars($line) . '<br>';
}

// we can also access each line of the file seperately
echo '3rd line of the file: "' . htmlspecialchars($lines[2]) . '"<br>';
echo '<br>';

// file_get_contents() reads the file and places the contents in a string
$fileString = file_get_contents('file.txt');
echo 'Contents of file.txt using file_get_contents():
';
echo nl2br( htmlspecialchars($fileString) );
echo '<br>';

// readfile() writes the contents of the file straight to the browser
echo 'Contents of file.txt using readfile():<br>';
readfile('file.txt');
?>

The output from test.php is:

Contents of file.txt using file():
line 1
line 2
line 3
line 4
line 5
3rd line of the file: "line 3 "

Contents of file.txt using file_get_contents():
line 1
line 2
line 3
line 4
line 5

Contents of file.txt using readfile():
line 1 line 2 line 3 line 4 line 5

1 comment - What do you think?  Posted by Tiposaurus - April 5, 2011 at 2:04 am

Categories: Files, PHP   Tags:

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

Be the first to comment - What do you think?  Posted by Tiposaurus - April 4, 2011 at 4:17 pm

Categories: Basics, PHP   Tags:

Next Page »