PHP vs ASP

By: John Lunney (johnl) Posted: 16-Jun-02, 06:46:54 Rated: General

Alert!: Attention: Cet article/tutorial est ‰gé de plus de 45 jours. Ainsi les informations qu’il contient peuvent être, maintenant, dépassé. Merci de lire toutes les informations qu’il contient pour vous assurez que cet article fonctionnera bien sur votre système

This is my first article, so bear with me.
This will (hopefully) be the first in a series of articles comparing PHP to some of the other languages available.
Here we goÉ

PHP vs ASP

ASP is not really a language in itself, it’s an acronym for Active Server Pages, the actual language used to programme ASP is Visual Basic Script or JScript. But anyway, on with the comparison.

Speed
PHP is faster and more stable than ASP. ASP is built on a COM-based architecture so when ever a programme tries to connect to a database or file he calls a COM object. When that COM object tries to access the file system it calls up yet another COM object. All these COM overheads add up and slows things down.

In PHP modules, everything runs in PHP’s memory space. This means that PHP code will run faster because there is no overhead of communicating with different COM objects in different processes. In this case too, ASP is slower and more memory intensive than PHP’s model because each ASP language compiler runs in its own process.

Price
PHP installations are far cheaper to install than ASP installations. PHP runs great on Linux which is free, on the other hand ASP runs on the IIS Server (Internet Information Server) which need’s Windows N.T/2000/XP, any of which costs a lot, especially when compared to the price of PHP, nothing.

Apart from that ASP mostly uses MS-SQL Server as the back end which again is expensive, Where as PHP programmes mostly use MySQL which is FREE!

Extras
With ASP, if you need to upload files, then you need a third party component ASPuplod, if you want to send mail or encrypt passwords you need another component and so on. Each of these components has to be bought.

In PHP, if you want to FTP, encrypt passwords in MD5, or send email from a web page, you do not need any extra components as they are all built-in, which is, incidentally, another speed increase. Because everything is built-in, there is no extra layer of COM objects and access to email, for example, is faster than in ASP. Since PHP is Open-Source there are lots of plug-ins and lots of sample code.

Platform Support
PHP runs on Mac OS X, Windows, Win NT, Linux, Solaris, Unix, BSD etc.
ASP runs on Windows, under MicrosoftÕs IIS server, but there are a couple of projects that allow ASP to run on other platforms and servers but guess what, most of them cost money.

Summary:

Speed:
PHP: Faster.
ASP: Limited by COM-object model.
Cost:
PHP: Free.
ASP: Money.
Extras:
PHP: Many, free.
ASP: Limited, cost money.
Platforms:
PHP: OS X, Win NT, Windows, Linux, BSD, Solaris, Unix etc.
ASP: Windows, with commercial adaptations for other platforms.

Updated 23/06/02:
After the very kind comments on my article I have decided to add and discuss some of the points they raised.

Why does ASP still dominate?

Firstly, ASP does not dominate. The truth is quite on the contrary.
ÒZend Technologies Ltd., the designers of PHP 4 and the Zend Engine, today announced that as of April 2002, PHP, the open-source software phenomenon, has surpassed MicrosoftÕs ASP as the most popular server-side Web scripting technology on the Internet.Ó
There is, in fact, only a perception that ASP dominates industry. Just remember who makes ASP. ThatÕs right, Microsoft. Many people in the industry were brought up using Visual Basic and it is natural that they should continue using it. These people would mainly be in industry or big business. Now, this is just an opinion, but it seems to me that big business web-sites often seem to use ASP where as community web-sites often use PHP. Could there be something in that?

-John Lunney

Building and Installing Apache 2.2.4 and PHP 5.1.4 on Mac OS X 10.4.6

Alert!: Warning: This article/tutorial is more the 45 days old. As such the information contained within could be, by now, out of date. Please read all information to make sure that this article/tutorial will work with your current version of the Operating System

 

FYI Usual stuff… Full Developers’ Tool installation is required as well as up to date system. At this time it means Mac OS X 10.4.6 for PPC or INTEL WITH ALL latest Security Updates. Special Note for Intel Macs: Please make sure you install the developers’ tools that came with your mac, do not use old PPC developers’ tools. Mac OS X Server is not supported

For anyone that has been wishing to switch to Apache 2 on their Mac, this is the time to do it. PHP 5 has also recently been updated to 5.1.3 and this tutorial describes in detail, the best method to both build and install these programmes on your Mac.

Since Apple don’t include Apache 2 with OS X yet I have felt it better to keep Apache 2 in its own directory, and to keep PHP for Apache 2, etc. confined the that directory too.

Step 1: Downloading Apache 2----------The first step, as in any build like this, is to download the source and uncompress it. To do this we open the Terminal and enter the following commands. FYI: the % represents the Command Line Prompt and should not be entered

% curl -O http://apache.oss-mirror.org/httpd/httpd-2.2.4.tar.gz
% gnutar -xzf httpd-2.2.4.tar.gz

Step 2: Building and Installing Apache 2----------I’ve decided to install to a new directory which we will make /apache2. It’s nice and convenient. To do this enter the following commands (sudo is required as the directory doesn’t already exist):

% cd httpd-2.2.4
% sudo ./configure \
% –prefix=/apache2 \
% –enable-module=most \
% –enable-shared=max
% sudo make
% sudo make install

Step 3: Building and Installing PHP----------Building and Installing PHP with Apache 2 is fairly simple. We want to install it into the same directory as Apache… just for sanity’s sake.

% curl -O http://ie2.php.net/distributions/php-5.1.4.tar.gz
% gnutar -xzf php-5.1.4.tar.gz
% cd php-5.1.4
% sudo mkdir /apache2/php

Once all that’s done, we will configure and compile PHP (Remember % represents the prompt, it should not be entered).

% ./configure \
% –prefix=/apache2/php \
% –with-zlib \
% –with-xml \
% –with-ldap=/usr \
% –enable-cli \
% –with-zlib-dir=/usr \
% –enable-exif \
% –enable-ftp \
% –enable-mbstring \
% –enable-mbregex \
% –enable-dbx \
% –enable-sockets \
% –with-iodbc=/usr \
% –with-curl=/usr \
% –with-mysql=/usr/local/mysql \ (optional, required MySQL)
% –with-gd \ (optional, requires jpeg + png)
% –with-jpeg-dir=/usr/local \ (optional)
% –with-png-dir=/usr/local \ (optional)
% –with-apxs2=/apache2/bin/apxs
% sudo make
% sudo make install

The lines marked “Optional” are optional. lib jpeg and png are to enable jpeg and png support in GD Lib – you will need LibJPEG and LibPNG installed previously to enable GD. Please note, due to a bug with PHP, 64bit MySQL will not compile in, revert to 32bit. Also, due to a different bug, the latest version of MySQL should not be used. Please revert to an older version.

If you want a PHP.ini file then enter this. It’s not required though.

% sudo cp php.ini-dist /apache2/php/lib/php.ini

Step 4: Configuring Apache----------The next bit is to configure Apache to load PHP files properly. Add it below the file’s current contents. The httpd.conf file is located at /apache2/conf/httpd.conf. Make sure to use a flat text editor like BBEdit or Pico in the command line.

AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps
DirectoryIndex index.html index.php

Also, You now have a choice. By default your new document root will be /apache2/htdocs. If you want to change this back to the Apple default of /Library/WebServer/Documents you need to open the httpd.conf file (/apache2/conf/httpd.conf) and change the following:

DocumentRoot “/apache2/htdocs”

to

DocumentRoot “/Library/WebServer/Documents”

and

<Directory “/apache2/htdocs”>

to

<Directory “/Library/WebServer/Documents”>

Similarly, Apache 2 will now point to the UNIX standard user directory. Which means if you type http://::1/~user/ it will point to the ~/public_html directory in your user folder. In Mac OS X the usual standard is ~/Sites. If you wish to change this you need to access the /apache2/conf/extra/httpd-userdir.conf file and change

UserDir public_html

to

UserDir Sites

Step 5: Starting and Stopping Apache 2----------If all went well you should now have a working Apache 2 installation. However, this will not work with the Web Sharing option in System Preferences. Before you continue, please make sure the option in System Preferences is set to “Off”.

To start Apache 2:

sudo /apache2/bin/apachectl start

To stop Apache 2:

sudo /apache2/bin/apachectl stop

You will need to switch this on everytime your restart your Mac. Or, you can use another PHPmac tutorial to enable Apache 2 as the default OS X server. Additional Useful Apache2 Config Settings. This tutorial also contains important settings to secure your server, all are recommended to follow this

Hope all goes well… if, however, you hit a wall or you need help, however trivial, please contact support. Click Here. Please note; a PHPmac login is required.

-James Pelow
PHPmac


Some frequent Issues:

Q: I receive the following error message while running the Apache configure command:

Creating Makefile in src
+ configured for Darwin platform
Error: could not find any of these C compilers
anywhere in your PATH: gcc cc acc c89
Configure terminated

A: You need to install the Apple supplied Developers’ Tools. These come on a CD in your Mac OS X box or in the Applications folder if you’ve just bought your Mac recently

Q: I received an error message regarding the absence of LibXML2

A: Building and Installing libXML2 (Required for PHP 5)

libXML2 is required by PHP. It comes bundled in Tiger and if you met the requirements of the article then you shouldn’t have this problem. The building of libXML2 is releativly simple, but it takes for ever and a day to compile. So be prepared to go and make yourself a coffee and maybe dinner.

First step is to download the source then Untar it. We will make a directory to do this:

% cd ~/Desktop
% mkdir libxml2build
% cd libxml2build
% curl -O ftp://gd.tuwien.ac.at:21//pub/libxml/libxml2-2.6.22.tar.gz
% gnutar -xzf libxml2-2.6.22.tar.gz
% cd libxml2-2.6.22

We are now in the libxml2-2.6.22 source directory. From here it’s a simple compile and install.

% ./configure
% make
% sudo make install
% sudo ranlib /usr/local/lib/libxml2.a

libXML2 is now installed. Go Back and try configure PHP again, with the line –with-libxml-dir=/usr/local in your PHP configuration command.

How to sign an email with Mail

Alert!: Attention: Cet article/tutorial est ‰gé de plus de 45 jours. Ainsi les informations qu’il contient peuvent être, maintenant, dépassé. Merci de lire toutes les informations qu’il contient pour vous assurez que cet article fonctionnera bien sur votre système

 

FYI Mac OS X 10.3 and up-to-date Mozilla [Firefox] or Safari 1.2.4 or greater are required for this tutorial.
This tutorial updated on 20th October 2005

Digitally signing email is a way to guarantee not only that email is most definitively from you, but also guards against possible spamming claims. Add to this the ability to encrypt messages and it’s clear to see the advantages of signing your email. This tutorial shows how to start signing your email with OS X Mail.

The first part of this tutorial is to request your actual digital certificate. Thanks to the people at Thawte, this is free for everyone, and it is as simple as filling out an online form.

Go to http://www.thawte.com/secure-email/personal-email-certificates/index.html in your browser.

Click the “Join” button at the top right of the page

You will be brought through a fairly standard enrolment process where Thawte take some information about you – state ID number, Passport Number, etc. It should be noted that this is secure and Thawte are trustworthy.

Once you have completed your signup and confirmed your email, you will be asked to login using the email and password you supplied in the enrolment stage.

Once logged in, click “Certificates” in the left menu, on the resulting page click “Request a Certificate” and following that click the button in the main area to request an X.509 format certificate.

In the resulting pop-up window, select “Netscape Communicator or Messenger” and then click request. Click Next. Choose your email address (one only if there are more then one) and click next. Once again click next, followed by Accept.

Under the Public Key heading be sure to choose 2048 (High Grade) and once again click next. Confirm that everything is correct and click “Finish”.

The next part of this tutorial is actually acquiring your certificate. In the main account area, click “View Certificate Status”. You should see you requested certificate with either a status of pending or issued. If it has been issued, click on it. View the details of the certificate and then click fetch.

If you are using Mozilla Firefox:
Once Mozilla has received the certificate, go to the Mozilla application menu and click preferences. Choose “Certificates” under the advanced tab and click the button to “Manage Certificates”. You should see your new certificate from Thawte in the list. Select it and click “Backup”. Save this file to your desktop. You can now quit Mozilla.

If you are using Safari:
The file should download to the desktop, or your download folder.

The final part of this tutorial demonstrates how to actually add this new certificate to your keychain so it can be used by Mail. In typical Apple style this is probably the most easy stage. Simply go to your desktop to where you saved the file from Mozilla and double click it. Keychain Access will open and ask you what Keychain to add it to. Personally I added it to my login one, and for most people this will be perfect – however, if you have advanced keychains feel free to add where you wish. Quit Keychain Access.

That is basically it. From now on when you compose mail with your address you will see a small tick in the top right. If this is selected the email will be signed. If you have received a signed email off someone, you will be able to reply with an encrypted email. If available you will also see a padlock beside the tick.

From now on, people will receive a “Security: Signed” header when viewing emails from you.

What is a VPN?

When data transmitted over the Internet uses a public network infrastructure, the path they follow is not defined in advance. It is then possible that the network is “listened”, worse, that the traffic is diverted by an indiscreet user.

The need for secure communication is therefore essential for the exchange of sensitive information. However, most companies can not afford to link their local networks with dedicated links; it would be excessively expensive.

Instead, the Internet is used as a public, insecure and unreliable network. How can one then transit his confidential information in this condition without being intercepted? This is the problem that responds to the VPN Virtual Private Network or VPN, the acronym for Virtual Private Network.

VPN is, therefore, an excellent compromise that, taking the internet as a transmission medium, uses an encapsulation protocol (in English tunneling) to transmit the data in a secure way.

A VPN for end-to-end security

VPN is called virtual network because it connects two physical networks (local area networks) over the Internet which is an unreliable virtual link. It is said to be private because only computers on these local networks can access the data.

It will be remembered that the VPN makes it possible to obtain a secure link for the exchange of data.

How does a VPN work?

Two main elements are used when establishing a secure VPN link between two hosts. The typical scenario being the access to data of an organization by a third party user from a remote location, these elements are:

A VPN server whose role is to encrypt and decrypt data on the enterprise side
A VPN client whose role is to encrypt and decrypt data on the remote user’s side.

When the user wants to access the virtual private network, his request is transmitted to the gateway system. The latter will connect to the remote network via a public network infrastructure and then transmit the request encrypted.

The remote computer will then provide the data to the VPN server of its local network that will transmit the response in an encrypted manner. Upon receipt on the user’s VPN client, the data will be decrypted for readability

Data encapsulation

The operation of the VPN is also based on the encapsulation or tunneling protocol used. It is a protocol that, thanks to some cryptography algorithms, helps protect the data that pass through the VPN.

The main tunneling protocols frequently used by VPNs are Point-To-Point Tunneling Protocol (PPTP), Layer-to-Forwarding (L2F), Layer-to-Tunneling Protocol (L2TP), IPsec and OpenVPN.

At the entrance and exit of the VPN, the data is encrypted using these protocols. Anyone who tries to intercept the traffic will end up with incomprehensible and almost indecipherable data.

Why buy a VPN?

The reasons that support the purchase of a VPN in 2018 are legion. First of all, the VPN offers the possibility of securing the user’s internet connection. Thanks to it, the client has the possibility to encrypt all the packets that he sends or receives through the VPN tunnel.

The various risks of espionage, loss or interception of data are thus greatly reduced. In addition, the use of the VPN also allows the user to surf the net anonymously. He may use a (virtual) IP address other than his own to circumvent various forms of unwanted surveillance on the internet.

No trace of the activities performed through a virtual private network is then identifiable. On the other hand, the VPN makes it possible to circumvent censorship and geo-restrictionn on the internet. Whether to impose traditional social values, to maintain political stability or national security, censorship and restrictions have often placed limitations on the use of the Internet.

Fortunately, VPNs have evolved and now allow to easily bypass this category of restrictions through the use of non-blacklisted IP addresses. And finally, the VPN can stream from any location, even download content without risk.

 

XAMPP 0.5 on Intel Macs

Warning: This article/tutorial is more the 45 days old. As such the information contained within could be, by now, out of date. Please read all information to make sure that this article/tutorial will work with your current version of the Operating System

FYI How to run Xampp on your Intel Mac.
Required: OS X (10.3 or 10.4), Xampp

1. Download
Get XAMPP 0.5 and install it.

2. Locating httpd.conf
Go to the xampp directory in your Applications folder, open the etc folder and doubleclick the httpd.conf file.

Users of Mac OS 10.3: Find the entry
LoadModule unique_id_module modules/mod_unique_id and type a # at the beginning of the row.

Users of Mac OS X 10.4: Find the entry
LoadModule rewrite_module modules/mod_rewrite.so and type a # at the beginning of the row.
If you’re not familiar with commenting: this inhibits processing of the selected code. That’s it. Now we’re ready to run.

3. Terminal
Start the terminal which you’ll find in the utilities folder of your Applications directory.

4. Starting the app
Type in

sudo /Applications/Xampp/xamppfiles/mampp start

You will be asked to type in the password of the system administrator.

(If you’re the only one that uses this Mac you can type probably the same as you used when installing the software)

Note that the cursor will not move during your entry and stay at the same position… Enter it and the Xampp will start up.

FYI Xampp will only work if you run the command as the root user.

If everything works fine, you’ll see the following messages:

Starting XAMPP for MacOS X 0.5…
XAMPP: Starting Apache with SSL (and PHP5)…
XAMPP: Starting MySQL…
XAMPP: Starting ProFTPD…
XAMPP for MacOS X started.

That’s it. You’re good to go! Open your browser and go to http://localhost.

6. Stopping Xampp is done also through the Terminal. Refer to the official readme part for more information.

7. NOTE: If the Terminal prints Error 1 and Apache couldn’t start, the first thing you might wanna look at is the logfile and see what error message it contains. Try to comment the false part out with the same method as described in step 2.

SourceGuardian 7.0 for PHP – Mac OS X version

Warning: This article/tutorial is more the 45 days old. As such the information contained within could be, by now, out of date. Please read all information to make sure that this article/tutorial will work with your current version of the Operating System

We’ve just released a GUI for sourceguardian for Mac.
Now Mac PHP developers are able to use SourceGuardian encoder power
to protect PHP scripts.

SourceGuardian 7.0 for PHP is the ultimate protection solution for encoding and protecting your PHP scripts. It has full native bytecode encoding, time limiting scripts, IP and domain locking, a license generator and many other features. SourceGuardian 7.0 for PHP is the most comprehensive and user-friendly protection solution on the market.

SourceGuardian 7.0 for PHP is the only serious choice for protecting and encoding your PHP source code assets. It has the flexibility that other products only dream of – Professional PHP developers everywhere are using SourceGuardian products to distribute their scripts safely. Thousands of developers have turned to SourceGuardian because of the nominal investment and superb rich featureset.

SourceGuardian 7.0 for PHP Includes:

– Advanced bytecode obfuscation
– Install wizards for encoded scirpts and loaders
– Custom predefined constants
– Custom error handling
– Zend extension support
– Fully encode and deploy for PHP5 (and PHP4)
– Choice of Windows/Linux/Mac OS X encoding clients
– Work only with other files encoded with your copy of SourceGuardian™
– Command line encoder available now!
– Encrypt to domain name (for superrior security based on specified domain name)
– Encrypt to IP (for superrior security based on specified IP address)
– License generator for encoded scripts
– Replace the standard error handler with your own messages
– Full online help and PDF user manual
– Easy to use Wizard interface and Advanced mode in GUI
– Automatic backup of source files
– Deployment options
– Lock to multiple LAN hardware (MAC) addresses
– Full Bytecode Encryption – protect your files by removing the original PHP Source Code
– Powerful encryption built on top of Bytecode
– Lock to specific dates or days in the future
– Lock to multiple domain names
– Lock to multiple ip addresses
– Customised banners and messages for trial scripts and for IP/Domain limited scripts
– Run scripts under virtual hosting accounts with no change to the default php installation
– Encoded files run under Linux, FreeBSD, Windows, Mac OS X, SunOS Solaris (x86-32-bit/x86-64-bit/Sparc)
– Encrypt multiple files, folders and projects with a single click
– Fully compatible with Zend Optimizer
– Requires no changes to the Linux kernel
– Create projects to easily manage your workload
– Add file masks for automatically including or excluding files
– Require no changes to the standard web server installation
– Include any HTML or PHP code to run before a protected script
– Encoding of HTML templates and other non-PHP files (including Smarty templates)
– Free minor updates
– Technical support

Tatiana Egorova
Marketing Services
http://www.sourceguardian.com

IP Banning

Warning: This article/tutorial is more the 45 days old. As such the information contained within could be, by now, out of date. Please read all information to make sure that this article/tutorial will work with your current version of the Operating System

Blocking certain IP addresses from your site is actually much easier than you might think.

In fact, it is only a seven-line code inserted at the top of your page!

The code:

1 :

Please note that the used IP addresses are randomly selected numbers.

Now, for the explanation of the code.

Line 1 simply opens the PHP code.

Line 2 sets the variable $banned to an array containing all the IP addresses you want to be blocked from your site.

Line 3 opens a conditional. The conditional uses the in_array() function. This function checks if the first argument is in the second argument, which is an array. Our first argument, $_SERVER[‘REMOTE_ADDR’], is automatically set to the viewer’s IP address.

Line 4 echoes the message “You have been banned” if the user’s IP address is in the array $banned.

Line 5 exits the page, not executing any code below line 5 if the above conditions are met.

Line 6 ends the conditional.

Line 7 ends the PHP code.

So, if you are implementing this code into your page, just put it above the HTML tag like below:



My Page


Main content

And that is the simple code that blocks chosen IP addresses from your site.

Query Strings

Warning: This article/tutorial is more the 45 days old. As such the information contained within could be, by now, out of date. Please read all information to make sure that this article/tutorial will work with your current version of the Operating System

What is a query string?
A query string is the part of a URL that sends variable values to the script.

What’s the syntax?
Well, after the page name, you put a question mark (?). This separates the file name from the variables. Between each variable you set, put an ampersand (&).

An example?
The query string is bold:
http://www.phpmac.com/page.php?name=Jake&colour;=red

Show me how to incorporate them into the page!
You use them as $_GET variables. The following code will be page.php, and will be accessed with the URL of http://www.phpmac.com/page.php?name=Jake&colour;=red.



Using Query Strings




This would output The favourite colour of Mr. Jake is red

Displaying MySQL Data

Warning: This article/tutorial is more the 45 days old. As such the information contained within could be, by now, out of date. Please read all information to make sure that this article/tutorial will work with your current version of the Operating System

In this tutorial, we will learn how to retrieve and display data from a MySQL database using PHP. This tutorial is a perfect companion to my tutorial entitled “Writing Form Data to a MySQL Database using PHP” so we will use the same database information – a table named “colors”, fields named “name” and “favoriteColor” with the following connection data:
Host: localhost
Username: lefteh
Password: 1234
DB Name: MyDB
Remember, these pieces of data are just examples. Remember to replace them with your own data.

Okay, first we’ll create a skeleton.



Displaying MySQL Data


Our PHP code will go in the body of the document.

First, we’ll connect to the database. In this step, we will also create the beginning and end of a table, because that is what our results will be printed into.



Displaying MySQL Data



With me so far?

We set our four connection variables, connected to the MySQL server, and selected the database. Then, we created the beginning and end tags of a table.

Printing our data is actually quite easy. It is a simple while loop. In the argument of the loop, we set a variable to mysql_fetch_array($query). Then, whatever is inside the brackets is repeated for every row in the table. Furthermore, we can use the variable that we used in the argument as an array using the column names of our database. Now, for the query, we will want to select all columns from “colors”. Therefore, our query is “SELECT * FROM colors”. Confused? Me too. Just look at the example:



Displaying MySQL Data


“;
echo “

“;
echo “

“;
echo “

“;
}
?>

“.$row[‘name’].” “.$row[‘favoriteColor’].”


Understand? All we do is put a table row on a loop, with two table cells each displaying a different MySQL field. Now, keep in mind displaying MySQL data can be manipulated much more. We don’t have to put it in a table, you can just make a loop that echos the variables. You can use the $row[‘fieldname’] for all fields in the database.

Displaying MySQL can be extremely confusing for some, so feel free to drop me a line.

PHP Navigation using Switch

By: Jacob Manser (lefteh) Posted: 27-Dec-05, 22:38:01 Rated: General/Experienced

Alert!: Warning: This article/tutorial is more the 45 days old. As such the information contained within could be, by now, out of date. Please read all information to make sure that this article/tutorial will work with your current version of the Operating System

In this tutorial, you will learn how to use PHP’s “switch” capability to create your site’s navigation. The switch is basically an alternative to a million ifs or elseifs.

First of all, decide what GET variable your navigation will be based upon. For example, this tutorial will use $_GET[‘page’]. Therefore, our links will be like this: <a href=”?page=about”>.

Now, let’s learn the basic outline of a switch.


<?php
switch ($var) {

case “page1”:

break;

case “page2”:

break;

case “page3”:

break;

default:

break;

}

?>

Every time the “case” statement is used, the code is testing the value of the variable that is the argument of switch().

For example, in the above example it says “switch($var)”.
This means that the variable that will be tested is $var.
When it says case “page1”, it is seeing if the value of $var is “page1”. If it is, then it executes the code between the colon ( : ) and the break; statement.

The default: part acts like a last resort, like an else.

Now, let’s put this to use. Let’s say I have four pages on my site: Home, About, Products, and Contact. I will use $_GET[‘page’] as my switch variable, and make the links as follows:


<a href=”?”>Home</a>
<a href=”?page=about”>About</a>
<a href=”?page=products”>Products</a>
<a href=”?page=contact”>Contact</a>

The PHP code will be as follows:


<?php
switch($_GET[‘page’]) {

case “about”:
echo “About”;
break;

case “products”:
echo “Products”;
break;

case “contact”:
echo “Contact”;
break;

default:
echo “Home”;
break;

}

?>

 

Create an easy PHP Navigation with Query Strings

This system of doing things is pretty simple. First lets go over the breakdown of what exactly this script will do. Basically it will create an easy way to navigate your site that looks quite neat. EX. http://www.watever.com/index.php?id=tutorials. In the example the page being shown will be the tutorials page. Lets take a look at the code first, then we can run through a quick breakdown.

<?php
$id = $_GET[“id”];
$id = addslashes(strip_tags($id));

switch( $id )
{
default:
include ‘home.php’;
break;

case ‘home’ :
include ‘home.php’;
break;
}
?>

Some people use IF statements, but this way seems a little neater.

Line 1: Initiates the PHP file. Nothing really happens here.
Line 2: This is the opening of the switch statement. Basically it “GET”s the id from the address.
Line 4-6: Is the default switch statement. If there is no id then it will include the file home.php
Line 8-10: Is the first case. It says, IF the id is home THEN include home.php.

To add more links you just need to add more of the following:

case ‘contact’ :
include ‘contact.php’;
break;

Don’t forget to change the case and the include file.

Implementing The Code
Implementing the code is pretty simple as well. Basically you build your main page, and where you want your main content to appear you put in this SWITCH statement. Then for each file, (EX. home.php) you only put the content. Hers a quick example of what a page would look like:

<?php
include’dbconnect.inc.php’;
?>
<html>
<head>
<title>Xangelo</title>
<link rel=”stylesheet” type=”text/css” href=”style.css”>
</head>
<body>
<div class=”header”>
Navigation
</div>
<a href=”index.php?id=home”>Home</a>
<div class=”content”>
<?php include’id.php’; ?>
</div>
</body>
</html>

And you home.php file would look like this:

Welcome to my site

The file id.php contains your switch statement. If you need more help implementing this, feel free to drop me an email.

*Edit*
Made page slightly more secure with use of addslashes/strip_tags code performed on variable.

And that’s all folks. You can add as many cases as you need, and do anything you want in the meat of the cases.