This tutorial will show you how to add such a text size switcher to your Web pages using PHP and CSS.

When designing a Web site, it's important to remember thatall of its visitors will not necessarily be young, in fine fettle, and fully conversant with the intricacies of using a Web browser. The smart designer knows this and always builds special accessibility features into a Web site so that even older or handicapped users can use the site comfortably, without excessive strain or stress.

One of the most useful accessibility features any Web site can possess is a text size switcher. Simply put, this is a tool that allows users to alter the size of the text on a Web page, usually to make it larger and therefore easier to read. Some browsers come with this feature built-in, but novice Web users are not likely to know about it; for this reason, site designers often place easily-accessible control buttons for this purpose on each Web page.

This tutorial will show you how to add such a text size switcher to your Web pages using PHP and CSS, thereby immediately making your Web site more accessible and scoring you useful brownie points from everyone over the age of 50. Keep reading, and find out how!

Note: This tutorial assumes a working Apache/PHP installation.

How it works
Before writing any code, it's instructive to spend a few minutes understanding how the size switcher is supposed to work. Each page of the Web site will sport a set of control buttons, allowing the user to select one of three sizes for the text on the page: small, medium and large. Each of these sizes corresponds to a CSS stylesheet, which holds the rules needed to render the page in the selected size.

When the user makes a selection, PHP internally stores the selected size in a session variable and then reloads the page. The reloaded page reads the selected size from the session variable and dynamically loads the corresponding stylesheet to re-render the page in a smaller or larger size.

Procedure
Step 1: Create a Web page
Begin by creating a HTML document, complete with placeholder content. Here's an example (Listing A):

Listing A:

<html>
<head>
</head>
<body>

<!-- font size buttons -->
Text size: <a href="resize.php?s=small">small</a> | <a href="resize.php?s=medium">medium</a> | <a href="resize.php?s=large">large</a>

<p />

<!-- dummy page content -->
Loremipsum dolor sit amet,
consecteturadipisicingelit, sed do eiusmodtemporincididuntutlabore et dolore magna aliqua. Utenim
ad minim veniam, quisnostrud exercitation ullamcolaboris nisi utaliquip ex ea commodoconsequat.
Duisauteirure dolor in reprehenderit in voluptatevelitessecillumdoloreeufugiatnullapariatur.
Excepteursintoccaecatcupidatat non proident, sunt in culpa qui
officiadeseruntmollitanim id estlaborum.

</body>
</html>

Pay special attention to the text hyperlinks at the top of this page. Each hyperlink points to the script resize.php, and passes it the selected text size through the URL GET method.

Save this document to your Web server directory with a .php extensionââ,¬"for example, index.php.

Step 2: Create stylesheets
Next, create stylesheets for each of the available text sizes for the page: small.css, medium.css and large.css. Here's what small.css looks like:

body {
font: 10px
}

In a similar manner, create medium.css and large.css, with font sizes of 17px and 25px respectively. Save these stylesheets to the same directory as the Web page created in the previous step.

Step 3: Create the text resizing mechanism
As previously described, the Web page "knows" which stylesheet to load by looking in a pre-defined session variable. This session variable is controlled by the script resize.php, (Listing B) which is activated whenever a user clicks one of the text-sizing buttons at the top of each page. Here's what resize.php looks like:

Listing B

<?php
// start session
// import selected size into session
session_start();
$_SESSION['textsize'] = $_GET['s'];
header("Location: " . $_SERVER['HTTP_REFERER']);
?>

This is fairly simple. When a user selects a new text size, resize.php receives that size value through the GET method and stores it in the session variable $_SESSION['textsize']. It then redirects the browser back to the page from whence it came.

Of course, there's still one missing component: the intelligence that lets the page detect which text size is currently selected and load the appropriate stylesheet. To add this, pop open your Web page index.php, and add the following lines at the beginning of the page (Listing C):

Listing C

<?php
// start session
// import variables
session_start();

// set default text size for this page
if (!isset($_SESSION['textsize'])) {
$_SESSION['textsize'] = 'medium';
}
?>

You should also add a stylesheet link between the <head>...</head> elements, as follows:

<link rel="stylesheet" href="<?php echo $_SESSION['textsize']; ?>.css" type="text/css">

Here's (Listing D) what the completed index.php will look like:

Listing D

<?php
// start session
// import variables
session_start();

// set default text size for this page
if (!isset($_SESSION['textsize'])) {
$_SESSION['textsize'] = 'medium';
}
?>

<html>
<head>
<link rel="stylesheet" href="<?php echo $_SESSION['textsize']; ?>.css" type="text/css">
</head>
<body>

<!-- font size buttons -->
Text size: <a href="resize.php?s=small">small</a> | <a href="resize.php?s=medium">medium</a> | <a href="resize.php?s=large">large</a>

<p />

<!-- dummy page content -->
Loremipsum dolor sit amet,
consecteturadipisicingelit, sed do eiusmodtemporincididuntutlabore et dolore magna aliqua. Utenim
ad minim veniam, quisnostrud exercitation ullamcolaboris nisi utaliquip ex ea commodoconsequat.
Duisauteirure dolor in reprehenderit in voluptatevelitessecillumdoloreeufugiatnullapariatur.
Excepteursintoccaecatcupidatat non proident, sunt in culpa qui officiadeseruntmollitanim id estlaborum.

</body>
</html>

It should be easy to understand how this works. When the Web page is loaded, it restores the current session, checks the $_SESSION['textsize'] variable to see which text size is currently selected, and then dynamically loads the corresponding stylesheet through the <link... /> element. This causes the page to automatically re-render in the correct size.

Using PHP and CSS in this combination is slightly different from the traditional approach, which uses JavaScript to dynamically alter CSS styles. The advantage of using PHP instead of JavaScript is that you're not dependent on the client supporting JavaScript, nor do you need to worry about creating browser-specific workarounds. Perhaps you will find a use for this tip the next time you sit down to design a Web site. Happy coding!

Do you need help with PHP? Gain advice from Builder AU forums

Related links

Comments

1

Day Tooley - 31/12/05

Nice solution for IE users. I tried both the px and the em font size optons.

But doesn't seem to work for Firefox or Opera browsers.

Any ideas on those?

» Report offensive content

2

Pete Wason - 21/09/06

Seems like this would result in a billion almost identical stylesheets if, for example, you extended this idea to other styles. Why not create a session-relative copy of the stylesheet, make the changes to the copy, and specify the session stylesheet in the html. Then you could save the stylesheet name in a user cookie and reload it when they come back.

Just a thought :)

» Report offensive content

3

Ed Johnson - 22/09/06

Interesting that you reccommend using php to avoid javascript issues when the text resizing options on this very article use javascript...

» Report offensive content

4

Mortisha Adams - 28/09/06

It will work in Firefox or Opera browsers if you just change

body {font: 10px }

to

body {font-size: 10px;}

in small.css, medium.css and large.css. I use Mozilla and this script is working just perfect.

» Report offensive content

5

Day Tooley - 08/10/06

Thanks, Mortisha.

That does the trick.

» Report offensive content

6

MrRundog - 05/03/07

This tells me more about sessions than most the session tutorials out there! Nice work.

» Report offensive content

7

Memory-Guard - 14/05/07

Using sessions is like eating up system memory.

» Report offensive content

8

.m,.m - 17/07/07

.m.m,..mm,.m.,m,.m.m.m....

» Report offensive content

9

Mark - 21/07/07

I get the following error when loading the index.php a browser:

what would be causing this?

Warning: Unknown(): write failed: Disk quota exceeded (122) in Unknown on line 0

Warning: Unknown(): Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/tmp) in Unknown on line 0

» Report offensive content

10

Harmit - 28/09/07

Not working for me.
Whenever i click Text : small or medium or large
it went to:
http://localhost:9000/php-font/resize.php?s=large
and doesn'e show me anything.

» Report offensive content

11

ty - 19/10/07

*********** MARK ***************
Warning: Unknown(): write failed: Disk quota exceeded (122) in Unknown on line 0

Warning: Unknown(): Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/tmp) in Unknown on line 0


this is a server issue you are experiencing.

You need to enable sessions
and/or
/tmp directory does not exist on the server
and/or
you need to be able to write to the /tmp directory on your server

» Report offensive content

12

eod - 23/05/08

same problem like Harmit :( the page reloads without changes

» Report offensive content

Leave a comment

You must read and type the 6 chars within 0..9 and A..F

* indicates mandatory fields.

12

eod - 23/05/08

same problem like Harmit :( the page reloads without changes ... more

11

ty - 19/10/07

*********** MARK *************** Warning: Unknown(): write failed: Disk quota ... more

10

Harmit - 28/09/07

Not working for me. Whenever i click Text : small or medium or large it went to: http://localhost:9000/php-font/resize.php?s=large and doesn'e show me anything. ... more

Log in


Sign up | Forgot your password?

  • Staff XP stays on life support for longer

    This week's Roundup looks at Microsoft's decision to extend the life of Windows XP, the release of Microsoft Surface SDK, Firefox's new Geode plug-in, Yahoo's new tool -- Smush It and more. Read more »

    -- posted by Staff

  • Chris Duckett The good and truly awful celluloid depictions of computers

    Ever wonder why your lawyer uncle leaves the room whenever you turn over to Boston Legal? Or why your forensic science cousin can't stand crime drama? You know the answer: it’s the horrid trivialisation and dumbing down of an occupation to make it appear entertaining. Sometimes it is so unbelievable that it actually hurts and yelling at the screen is the only outlet. Read more »

    -- posted by Chris Duckett

  • Brendon Chase Apple's iPhone engineers to tour Sydney, Melbourne

    Aussie developers will be able to get up close and personal with some of the iPhone engineers in November to learn how to build applications for the platform. Read more »

    -- posted by Brendon Chase

What's on?