PHP


One of the great promises that actually came true when our Internet-enabled world reached the twenty-first century is efficient customer-to-business interaction. Each day, I find a new way to go through life’s errands without ever waiting on hold for a bank teller, a pharmacist, or an insurance agent. I do it all online.

Internet savvy consumers are coming to expect such web empowerment. And while these information transactions usually require some sort of private data traveling the ether, you, as the webmaster, bear the burden of keeping that data away from those who have no right to it.

Since retina scans and brain wave signatures are still properties of James Bond flicks, we’re stuck using plain old boring passwords.

Is this really secure?

Let’s get this out of the way first. The only truly secure computer is one that’s unplugged. Kind of like “the only safe car is the one that sits in your garage.” Life is a risk/reward proposition and, let’s face it, this (probably) isn’t Fort Knox, we’re securing.

The security measures listed here are suitable for garden-variety data. I’ve used these schemes to write back-end website administration pages for online shopping carts. I’ve used them to write “partner” pages where retailers can download ads and sales data from wholesalers. I wouldn’t use them to secure credit card numbers, social security numbers, or nuclear launch codes.

So what are PHP, MySQL, and session variables?

PHP is a programming language used (in this case) to write HTML. MySQL is a database. Session variable are used by web servers to track information from one page on a domain to another. This article isn’t a how-to for either technology. If you aren’t very comfortable with them, you could just copy and paste the code samples in this article and build yourself a basic password protected website. You could also just read the Cliff’s notes for Pride and Prejudice and get a C+ in literature class. Your choice.

Let’s get started with sessions

It’s often been said that the web is “stateless”, meaning that each web page is entirely independent, needing no other page to exist, and taking no information from the previous page. This is great for anonymous surfing from one site to the next, but it stinks for password protection. Consumers want password protected information, but they don’t want to enter their password on every page. So we turn to our web server to keep track of a user while he’s on our site.

Ex. 1.

<?php

session_start();

?>

<!DOCTYPE html PUBLIC ‘-//W3C//DTD XHTML 1.0 Strict//EN’ ‘http:// www.w3.org/ TR/ xhtml1/ DTD/ xhtml1-strict.dtd’>

<html xmlns=”http://www.w3.org/1999/xhtml”" xml:lang=”en” lang=”en”>

<head><title>Dan McConkey’s Free Web Marketing Guide</title></head>

<body>

<p>Dan McConkey’s Free Web Marketing Guide</p>

</body>

</html>

end Ex. 1

session_start() is a PHP function that looks to see if a session has already been started then does one of two things:

1. If a session has been started, it does nothing.

2. If a session has not been started, it begins one.

It is important to note that session_start() must occur before any other PHP on the page, if you want it to work. Begin every password-protected page with it. Validation

Now let’s think basic validation. What sorts of things do we need to accomplish?

* First, we need to check to see if the user has already logged in, so we don’t ask for a password on every page. If our user has already logged in, we pass him or her through to the secure content.

* If the user hasn’t already logged in, we need him or her to do so. So we need to write a log-in form.

* We need next to compare log-in form results with a known list of usernames and passwords. If the user checks out, we pass him or her along to the secure content.

* If the user doesn’t check out, we direct him or her back to the log-in screen.

* Lastly, we need to provide the user the ability to log out.

So let’s start with a basic frame-work that we’ll fill in later.

Ex. 2

<?php

// start session if not already started

session_start();

// check to see if user just logged out

if ( $log_out )

{

}

function write_log_in( $text )

{

} // end write_log_in function

function verify()

{

// check to see if they’re already logged in

// if yes, return true

// if no, check to see if visitor has just tried to log on

// if yes, verify password

// if it worked, return true

// if it didn’t, send them back to log-in

// if the user didn’t just log-in, (s)he needs to

} // end verify function

?>

<!DOCTYPE html PUBLIC ‘-//W3C//DTD XHTML 1.0 Strict//EN’ ‘http:// www.w3.org/ TR/ xhtml1/ DTD/ xhtml1-strict.dtd’>

<html xmlns=”http://www.w3.org/1999/xhtml”" xml:lang=”en” lang=”en”>

<head><title>Dan McConkey’s Free Web Marketing Guide</title></head>

<body>

<p>Dan McConkey’s Free Web Marketing Guide</p>

<?php

// check for valid user

if ( verify() )

{

// begin secure content

echo “<p>Clatu, verata, nicto</p>”;

// end secure content

} // end if ( verify() )

?>

</body>

</html>

End Ex. 2

As I said, this is just a frame-work. I like to start all my projects this way. It allows me to get a grand view of what I’m doing before getting mired down in the details.

Basically, so far, all we’ve done is place some secret content inside an if statement. If the user is valid, we show the content, if not, we don’t. Writing a log-in form

The first thing we should flesh out is our log-in function. This is a basic form, with no bells and whistles, so it should be pretty straight forward.

Ex 3

function write_log_in( $text )

{

echo ”

<p>$text</p>

<form method=’post’ action=”>

<p>User ID: <input type=’text’ name=’user_name /></p>

<p>Password: <input type=’password’ name=’password’ /></p>

<p><input type=’submit’ value=’Log In’></p>

</form>

“;

} // end write_log_in function

End Ex. 3

No problems, right? All this is is PHP writing a basic HTML log-in form. Two things are worth noting:

1. The method attribute to the <form> tag is ‘post’. We could have used ‘get’, but that would add our user name and password to the URL as varibles. ie our_url?user_name=bob&password=truck64 . This shows the password–in plain text– right there in the URL. Why spend all this time on security if you’re just going to put peoples’ passwords out for display?

‘post’ is much more secure, forcing the server to keep track of form data, rather that the URL. Any time you can keep information out of the URL, you’re one step closer to a secure web page.

2. Next you want to look at the action attribute to the <form> tag. Leaving it blank tells the server that you plan to process these form results with this same page.

Checking the log-in values

Now let’s flesh out our frame-work a little more.

Ex. 4

<?php

// start session if not already started

session_start();

// check to see if user just logged out

if ( $log_out )

{

}

function write_log_in( $text )

{

} // end write_log_in function

function verify()

{

// check to see if they’re already logged in

// if yes, return true

// check to see if visitor has just tried to log on

$user_name = $_POST["user_name"];

$password = $_POST["password"];

if ( $user_name && $password )

{

// verify password and log in to database

$db = mysql_pconnect( “localhost”, “$user_name”, “$password” );

if ( $db )

{

// register session variable and exit the verify function

$valid_user = $user_name;

$_SESSION['valid_user'] = $valid_user;

return true;

}

else

{

// bad user and password

$text = “User Name and Password did not match”;

write_log_in( $text );

}

}

else

{

// if the user didn’t just log-in, (s)he needs to

}

} // end verify function

?>

<!DOCTYPE html PUBLIC ‘-//W3C//DTD XHTML 1.0 Strict//EN’ ‘http:// www.w3.org/ TR/ xhtml1/ DTD/ xhtml1-strict.dtd’>

<html xmlns=”http://www.w3.org/1999/xhtml”" xml:lang=”en” lang=”en”>

<head><title>Dan McConkey’s Free Web Marketing Guide</title></head>

<body>

<p>Dan McConkey’s Free Web Marketing Guide</p>

<?php

// check for valid user

if ( verify() )

{

// begin secure content

echo “<p>Clatu, verata, nicto</p>”;

// end secure content

} // end if ( verify() )

?>

</body>

</html>

End Ex. 4

First, we’ll check whether the user has just tried to log in.

$_POST is a PHP superglobal array that keeps track of data sent to a page via a <form method=’post’> tag. In the log-in function, we named our inputs user_name and password, so we can access the user input by calling $_POST["user_name"] and $_POST["password"].

We next run an if ( $user_name && $password ) statement to see if both $_POST["user_name"] and $_POST["password"] hold values. If they do, the user just tried to log in.

Our next section of code is the part that actually checks whether the user name and password are correct. Here, we use MySQL’s User table (part of the mysql database) to keep track of our users. This is, perhaps, the best route, as MySQL is already set up to control access permissions. However, this can present problems when you want to keep the database connection open across pages. Also, some hosting companies won’t give you grant access (let you make new users) to the mysql database.

In those cases, you can accomplish much the same thing by setting up your own users table in your database. You would then need to write an SQL query that compares user names and passwords. That would look something like this:

Ex. 5

$select = “select user_name from users

where user_name=’$user_name’

and password=PASSWORD( ‘$password’ )”;

$query = mysql_query( $select );

if ( mysql_num_rows( $query ) == 1 )

{

// validated user and password

End Ex 5

Getting back to our validation using MySQL’s built in features, we know that the user name and password checked out because the connection attempt returned true.

Registering a session variable

Now that we know our user name and password check out, we need to store that information and allow our user to continue surfing our protected area without logging in each and every page. Looking back at example four, we notice another of PHP’s superglobal variables: $_SESSION.

$_SESSION is an array that holds all of our session variables. By setting the valid_user session variable, we can later make a call to ession_is_registered( “valid_user” ) to see if our user has already logged in successfully.

Logging out

The last thing we have to attend to is allowing our users to log out of our system. In this case, we’ve used a simple link inside our protected area.

Ex 6

<?php

// start session if not already started

session_start();

// check to see if user just logged out

if ( $log_out )

{

session_unregister( “valid_user” );

session_destroy();

session_start();

}

function write_log_in( $text )

{

} // end write_log_in function

function verify()

{

} // end verify function

?>

<!DOCTYPE html PUBLIC ‘-//W3C//DTD XHTML 1.0 Strict//EN’ ‘http:// www.w3.org/ TR/ xhtml1/ DTD/ xhtml1-strict.dtd’>

<html xmlns=”http://www.w3.org/1999/xhtml”" xml:lang=”en” lang=”en”>

<head><title>Dan McConkey’s Free Web Marketing Guide</title></head>

<body>

<p>Dan McConkey’s Free Web Marketing Guide</p>

<?php

// check for valid user

if ( verify() )

{

echo “<p><a href=’?log_out=1′>Log out</a></p>”;

// begin secure content

echo “<p>Clatu, verata, nicto</p>”;

End Ex 6

First, looking in the HTML body, we see a simple HTML link that adds a variable to the URL. In this case, the variable name is log_out and its value is 1. We use 1 as a value because it’s easy to store in a URL, but really any value greater than zero will work.

Once we pass a log-out request to the page, we need to process it. That’s what the if( $log_out) part is for.

The if statement checks if a log-out request was passed. Once it sees that one was, it unregisters the valid_user session variable, then it destroys the session entirely.

Ironically, it starts a new session right back up. That’s in case the user decides to log in later (without closing the browser window), or log in as a different user. The final code

Putting it all together we get this:

Ex. 7

<?php

// start session if not already started

session_start();

// check to see if user just logged out

if ( $log_out )

{

session_unregister( “valid_user” );

session_destroy();

session_start();

}

function write_log_in( $text )

{

echo ”

<p>$text</p>

<form method=’post’ action=”>

<p>User ID: <input type=’text’ name=’user_name /></p>

<p>Password: <input type=’password’ name=’password’ /></p>

<p><input type=’submit’ value=’Log In’></p>

</form>

“;

} // end write_log_in function

function verify()

{

// check to see if they’re already logged in

if ( session_is_registered( “valid_user” ) ) return true;

// check to see if visitor has just tried to log on

$user_name = $_POST["user_name"];

$password = $_POST["password"];

if ( $user_name && $password )

{

// verify password and log in to database

$db = mysql_pconnect( “localhost”, “$user_name”, “$password” );

if ( $db )

{

// register session variable and exit the verify function

$valid_user = $user_name;

$_SESSION['valid_user'] = $valid_user;

return true;

}

else

{

// bad user and password

$text = “User Name and Password did not match”;

write_log_in( $text );

}

}

else

{

// user must log in

$text = “This is a secure server. Please log in.”;

write_log_in( $text );

}

} // end verify function

?>

<!DOCTYPE html PUBLIC ‘-//W3C//DTD XHTML 1.0 Strict//EN’ ‘http:// www.w3.org/ TR/ xhtml1/ DTD/ xhtml1-strict.dtd’>

<html xmlns=”http://www.w3.org/1999/xhtml”" xml:lang=”en” lang=”en”>

<head><title>Dan McConkey’s Free Web Marketing Guide</title></head>

<body>

<p>Dan McConkey’s Free Web Marketing Guide</p>

<?php

// check for valid user

if ( verify() )

{

echo “<p><a href=’?log_out=1′>Log out</a></p>”;

// begin secure content

echo “<p>Clatu, verata, nicto</p>”;

// end secure content

} // end if ( verify() )

?>

</body>

</html>

End Ex. 7

That’s a pretty hefty code block to put at the head of every web page. Typically, I would put my verify() and write_log_in()functions into a seperate file and reference them with an include() function. That provides the added benifit of updating your entire website by editing one file only.

Hope that helps.

Copyright (C) 2005 Dan McConkey

About The Author

Dan McConkey is a freelance web marketing professional, working in and around Charlotte, NC. In the web, Dan has found an amazing potential for lead generation for businesses. Using traditional advertising theories, appropriate technologies, and a little common sense, your electronic marketing campaigns can easily be your most effective.

Dan maintains Dan McConkey’s Free Web Marketing Guide at http://www.dmcconkey.com

dmcconkey@yahoo.com

In this article I am going to cover some tools that you can use that will allow you to publish RSS feeds on your site. This will allow you to have fresh, updated content on your site and you have control of what sort of content you display and how often it is updated.

First off if you do not know much about RSS or feel you require more information take a look at this RSS publishers FAQ and then rejoin us again later.

There are several ways you can go about publishing RSS content, two of which this article will cover are using third party software that will take care of the RSS republishing for you. The second is to use some freely available PHP code to generate your RSS pages.

If you do not what PHP is or have little knowledge or PHP or programming then I would recommend that you use RSS Equalizer which takes care of the complicated stuff for you. RSS Equalizer produces HTML format pages that it has transformed from the RSS feeds it is using as its source.

RSS Equalizer is a PHP script that runs from your server so you will need to make sure your host can run PHP, most web hosts do. Once installed and set up RSS Equalizer can be left to parse content from the RSS feeds and produce a readable HTML format pages on your website.

If you have any programming experience or know a little PHP then there are some other free tools that you can use. These PHP scripts will allow you to parse RSS feeds and if you know PHP will give you more options for customisation. These tools are CaRP, Last RSS and zFeeder.

If you have the time and feel you can handle the PHP then the free PHP scripts above will be your best option. If you neither have the time or the inclination and want the hard work already done for you then try out RSS Equalizer, its not free but it’s the best option for the non programmer.

About The Author

Allan is the webmaster at NewsNiche an RSS resource for webmasters. Learn how to use RSS to attract and retain visitors to your site.

newsniche.com

PIM Team Case Study

This article could be very usefull for the owers of web service businesses. If you are offering e-commerse, hosting, live support or ticketing web based services you have probably met the discussed problem many times in your work. My intend with this article is to help you solving this trouble and save your valued time.

Supporting multiple instanses of a web based application can be very time consuming and frustrating, especially if the app is in development stage or is being updated often. Here in PIM Team we met such a problem, trying to perform constant upgrades on an application running simultanteously on about 50 different domains.

Problem You know, if you make just one change and don’t transfer it on the other instanses it can cause big errors and stop your scripts from working. But (as in our case) opening 50 control panels and going to the MySQL administration and running manually these ALTER TABLE or CREATE TABLE statements was a cumbersome task, taking all of our time.

Solution All the instances of our app were running on one physical server, which definitely was a facilitation. But you can implement similar solution even if your ap is running on different servers – you just need to allow connection to the master host – the one which will run the Synhronizer – the script i will describe below. Our Synchronizer is actually a simple PHP script which is started manually and have one only purpose – to synchronize all 50 databases with one “master” database. In our case we needed that script to synchronize only the DB structure, but not the content. But if you understand the simple logic of the script, you can easy extend it to copy/synchronize your content if this is you case.

Implementation First, you need to select all the tables and their fields from the master database:

//select tables from the master $q=”SHOW TABLES FROM master_database”; $tabs=$DB->aq($q); //$DB is a database fetching object, you can use the built PHP functions to select from mysql if you prefer

$tables=array();

foreach($tabs as $tab) { //select fields $q=”SHOW FIELDS FROM $tab[0]“; $fields=$DB->aq($q); array_push($tables,array(“name”=>$tab[0],”fields”=>$fields)); }

You see how our script fills an array $tables with all the table names and itself containing another array – with the table fields.

Secondly, you need a list with the databases or domains where the instances of the synchronized application are running. Once having that list, you can browse thru it with “foreach” or another cycle.

Now we are going to select all the tables in the database on each target domain. (Of course you need to connect to its database, and disconnect from master one! We already did our job in selecting the tables from the master database :)

In the same way as above, you need to select the tables from the target domain. Then below, just compare the tables:

foreach($tables as $table) //browse thru master tables { $found=false; foreach($dtables as $dtable) { if($dtable[name]==$table[name]) $found=$dtable; } if(is_array($found)) { //table exists, check fields foreach($table[fields] as $field) { $ffound=false; foreach($found[fields] as $dfield) { if($field[Field]==$dfield[Field]) $ffound=true; } if(!$ffound) { //alter table add field if($field[Key]=='PRI') $primary=" PRIMARY KEY "; else $primary=''; $q="ALTER TABLE `$table[name]` ADD `$field[Field]` $field[Type] NOT NULL $field[Extra] $primary"; $DB->q($q); } } else { //table does not exists, create $q="CREATE TABLE `$table[name]`("; foreach($table[fields] as $cnt=>$field) { if($field[Key]=='PRI') $primary=" PRIMARY KEY "; else $primary=''; $q.="`$field[Field]` $field[Type] NOT NULL $field[Extra] $primary "; if($cnt<(sizeof($table[fields])-1)) $q.=", "; } $q.=")"; $DB->q($q); } } }

And that’s all! You may need to work a little on this code, but the logic is here provided for your needs. Feel free to use the ideas for your own applications.

admin@pimteam.net
Author’s URL:
Bobby Handzhiev is software developer and manager of PIM Team Bulgaria.
PHP Calendar Scripts
High Yield Weekly Digest

What are Regular Expressions?

A regular expression is a pattern that can match various text strings. Using regular expressions you can find (and replace) certain text patterns, for example “all the words that begin with the letter A” or “find only telephone numbers”. Regular expressions are often used in validation classes, because they are a really powerful tool to verify e-mail addresses, telephone numbers, street addresses, zip codes, and more.

In this tutorial I will show you how regular expressions work in PHP, and give you a short introduction on writing your own regular expressions. I will also give you several example regular expressions that are often used.

Regular Expressions in PHP

Using regex (regular expressions) is really easy in PHP, and there are several functions that exist to do regex finding and replacing. Let’s start with a simple regex find.

Have a look at the documentation of the preg_match function (http://php.net/preg_match). As you can see from the documentation, preg_match is used to perform a regular expression. In this case no replacing is done, only a simple find. Copy the code below to give it a try.

<?php

// Example string
$str = "Let's find the stuff <bla>in between</bla> these two previous brackets";

// Let's perform the regex
$do = preg_match("/<bla>(.*)<\/bla>/", $str, $matches);

// Check if regex was successful
if ($do = true) {
	// Matched something, show the matched string
	echo htmlentities($matches['0']);

	// Also how the text in between the tags
	echo '<br />' . $matches['1'];
} else {
	// No Match
	echo "Couldn't find a match";
}

?>

After having run the code, it’s probably a good idea if I do a quick run through the code. Basically, the whole core of the above code is the line that contains the preg_match. The first argument is your regex pattern. This is probably the most important. Later on in this tutorial, I will explain some basic regular expressions, but if you really want to learn regular expression then it’s best if you look on Google for specific regular expression examples.

The second argument is the subject string. I assume that needs no explaining. Finally, the third argument can be optional, but if you want to get the matched text, or the text in between something, it’s a good idea to use it (just like I used it in the example).

The preg_match function stops after it has found the first match. If you want to find ALL matches in a string, you need to use the preg_match_all function (http://www.php.net/preg_match_all). That works pretty much the same, so there is no need to separately explain it.

Now that we’ve had finding, let’s do a find-and-replace, with the preg_replace function (http://www.php.net/preg_replace). The preg_replace function works pretty similar to the preg_match function, but instead there is another argument for the replacement string. Copy the code below, and run it.

<?php

// Example string
$str = "Let's replace the <bla>stuff between</bla> the bla brackets";

// Do the preg replace
$result = preg_replace ("/<bla>(.*)<\/bla>/", "<bla>new stuff</bla>", $str);

echo htmlentities($result);
?>

The result would then be the same string, except it would now say ‘new stuff’ between the bla tags. This is of course just a simple example, and more advanced replacements can be done.

You can also use keys in the replacement string. Say you still want the text between the brackets, and just add something? You use the $1, $2, etc keys for those. For example:

<?php

// Example string
$str = "Let's replace the <bla>stuff between</bla> the bla brackets";

// Do the preg replace
$result = preg_replace ("/<bla>(.*)<\/bla>/", "<bla>new stuff (the old: $1)</bla>", $str);

echo htmlentities($result);
?>

This would then print “Let’s replace the new stuff (the old: stuff between) the bla brackets”. $2 is for the second “catch-all”, $3 for the third, etc.

That’s about it for regular expressions. It seems very difficult, but once you grasp it is extremely easy yet one of the most powerful tools when programming in PHP. I can’t count the number of times regex has saved me from hours of coding difficult text functions.

An Example

What would a good tutorial be without some real examples? Let’s first have a look at a simple e-mail validation function. An e-mail address must start with letters or numbers, then have a @, then a domain, ending with an extension. The regex for that would be something like this: ^[a-zA-Z0-9_\.\-]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$

Let me quickly explain that regex. Basically, the first part says that it must all be letters or numbers. Then we get the @, and after that there should be letters and/or numbers again (the domain). Finally we check for a period, and then for an extension. The code to use this regex looks like this:

<?php

// Good e-mail
$good = "john@example.com";

// Bad e-mail
$bad = "blabla@blabla";

// Let's check the good e-mail
if (preg_match("/^[a-zA-Z0-9_\.\-]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$/", $good)) {
	echo "Valid e-mail";
} else {
	echo "Invalid e-mail";
}

echo '<br />';

// And check the bad e-mail
if (preg_match("/^[a-zA-Z0-9_\.\-]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$/", $bad)) {
	echo "Valid e-mail";
} else {
	echo "Invalid e-mail";
}

?>

The result of this would be “Valid E-mail. Invalid E-mail”, of course. We have just checked if an e-mail address is valid. If you wrap the above code in a function, you’ve got yourself a e-mail validation function. Keep in mind though that the regex isn’t perfect: after all, it doesn’t check whether the extension is too long, does it? Because I want to keep this tutorial short, I won’t give the full fledged regex, but you can find it easily via Google.

Another Example

Another great example would be a telephone number. Say you want to verify telephone numbers and make sure they were in the correct format. Let’s assume you want the numbers to be in the format of xxx-xxxxxxx. The code would look something like this:

<?php

// Good number
$good = "123-4567890";

// Bad number
$bad = "45-3423423";

// Let's check the good number
if (preg_match("/\d{3}-\d{7}/", $good)) {
	echo "Valid number";
} else {
	echo "Invalid number";
}

echo '<br />';

// And check the bad number
if (preg_match("/\d{3}-\d{7}/", $bad)) {
	echo "Valid number";
} else {
	echo "Invalid number";
}

?>

The regex is fairly simple, because we use \d. This basically means “match any digit” with the length behind it. In this example it first looks for 3 digits, then a ‘-’ (hyphen) and finally 7 digits. Works perfectly, and does exactly what we want.

What exactly is possible with Regular Expressions?

Regular expressions are actually one of the most powerful tools in PHP, or any other language for that matter (you can use it in your mod_rewrite rules as well!). There is so much you can do with regex, and we’ve only scratched the surface in this tutorial with some very basic examples.

If you really want to dig into regex I suggest you search on Google for more tutorials, and try to learn the regex syntax. It isn’t easy, and there’s quite a steep learning curve (in my opinion), but the best way to learn is to go through a lot of examples, and try to translate them in plain English. It really helps you learn the syntax.

In the future I will dedicate a complete article to strictly examples, including more advanced ones, without any explanation. But for now, I can only give you links to other tutorials:

The 30 Minute Regex Tutorial (http://www.codeproject.com/dotnet/RegexTutorial.asp)

Regular-Expressions.info (http://www.regular-expressions.info/)

About The Author

Dennis Pallett is a young tech writer, with much experience in ASP, PHP and other web technologies. He enjoys writing, and has written several articles and tutorials. To find more of his work, look at his websites at http://www.phpit.net, http://www.aspit.net and http://www.webdev-articles.com

dennis@nocertainty.com

This article was posted on March 28, 2005

The Problem with Putting an E-Mail Address On Your Site

A contact us page is a useful thing to have. Many sites just provide an e-mail address for contact purposes. However, there are several problems with e-mail:

  • If you leave your e-mail address on a website it almost certainly will get picked up by spammers and soon you’ll be getting a flood of unsolicited spam with viagra and cheesy pharmacy ads, virus attachments and the like. Hopefully you’ll have some sort of spam blocker but as always the best defense is prevention.
  • When a visitor clicks on your e-mail address, they may or may not launch the appropriate e-mail program. E-Mail hot links only work if you have a client based e-mail program (like MS-Outlook) which works seemlessly with e-mail links. Many times, people prefer to use web based e-mail rather than Outlook and the click links won’t work with web-mail.
  • If your browsing the web, its often quicker to enter a message into a browser page than to go to a seperate program or browser page. It’s more seemless for the end-user.
  • With a contact us page, you can control where the message goes and what information gets collected. For example, you may want additional marketing data like how they heard about your site, or if its a support question you may want to gather certain pre-requisites like the version of software they are using, etc.
  • You may want to log messages into a database, which is much harder to do with e-mail.

Creating the Contact Us Page

The following HTML and PHP script allows you to just that (except the database part. If your really interested in DB let me know and I’ll write a second part to this article).

Here is the HTML part, which is the data collection form. Place the following code in the <body> portion of your contact us page.

<form method=post action="sendmessage.php">
  <p>If you would like to contact us, please fill out the form below and press "Send". Enter your message in the space provided below:</p>
<table align="center" border="1" bordercolor="#CCCCCC" cellpadding="10">
<tr><td>
<b>Message:</b>
  <dl>
    <dd>    <p>Message Type: <select name="MessageType" size="1">
    <option selected>- - - - - -</option>
    <option>Suggestion</option>
    <option>Bug Report</option>
    <option>Question</option>
    <option>Advertising Request</option>
    <option>Link Exchange</option>
    <option>Other</option>
    </select></p>
    <p>Message:<br /><textarea name="Message" rows="5" cols="60"></textarea></p>
  </dd>
</dl>
  <p><strong>Tell us how to get in touch with you:</strong><strong></strong></p><p>
  <dl>
    <dd>
    <table>
      <tr>
        <td>Name</td>
        <td>
 <input type="text" size="35" maxlength="256" name="UserName"/></td>
      </tr>
      <tr>
        <td>E-mail</td>
        <td>
        <input type="text" size="35" maxlength="256" name="UserEmail"/></td>
      </tr>
      <tr>
        <td>Phone</td>
        <td>
        <input type="text" size="35" maxlength="256" name="UserPhone"/></td>
      </tr>
      </table>
    </dd>
  </dl>
  <dl>
    <dd>
      <input type="checkbox" name="ContactRequested" value="ContactRequested"/> Please contact me regarding this matter.</dd>
  </dl>
  </p>
 
  <p align="right"><input type="submit" value="Send"/>   <input type="reset" value="Clear Form"/></p>
</td></tr></table></form>

Now you’ll need to create need to create a PHP page that processes the message (e.g. sendmessage.php) as follows. Again, place this code in the <body section of your page:

<?php
    /* Initialize Variables */ 
    $myemail = "webmaster@mysite.com"; 
    $homepage = "http://www.mysite.com"
?>
<p>Thank you <?php echo $UserName ?> for your comments: <br>
<?php echo $Message ?> 
<br>
<br>
<?php 
    if (isset($ContactRequested)) { 
        echo "You have requested a follow up contact with the following contact information:<br>";
        echo "e-Mail: $UserEmail";
        echo "<br>Telephone: $UserPhone <br>";
    }
?>
<br> 
<a href= <?php echo $homepage ?> title="Web MYSITE Home Page"> 
    Return to MYSITE Home Page</a><br>

<?php
   $ip = getenv("REMOTE_ADDR");
   $todayis = gmdate("l, F j, Y, g:i a") ;
   $Comments = stripcslashes($Comments);
   $messageis = 
       "Time = $todayis [GMT] \n" .
       "Message From = $UserName \n" .
       "Type = $MessageType \n" .    
       "e-Mail = $UserEmail \n" .
       "Telephone = $UserPhone \n" .
       "ContactRequested = $ContactRequested \n" .
       "Message = $Message";

   $messageme = $ip . " " . $messageis;
   mail($myemail, "Comments from $UserName", $messageme);
?>
</p>

For a demonstration, you can see how this code works on our own contact us page.

PS. If you like this code sample, please link to our site (http://www.webmastersloom.com). It will be much appreciated.

PPS. Don’t forget to paste the code into a plain text editor (e.g. notepad) before placing it into your web page otherwise you’ll pick up the extra HTML from this page.

What most successful web site marketers already know is that that your search position is influenced by two factors. On-site optimization (i.e. site content, keywords, meta tags, navigation,etc.) and off-site optimization (inbound links). There are many different strategies for getting other sites to link to you including reciprocal links, article submissions and the like. However, one of the most effective is the use of text ads.

Just to be clear, not all text ads will help your search position. Ads that use JavaScript (i.e. Google Ads and Overture Ads) are not seen by search engine spiders and thus get ignored. No, what I’m talking about is the tagged ads that include HTML tags like this:

<a href="www.yoursite.com">Visit This Great Site</a>

Most of the text ad networks out there use server site technology such as PHP or ASP to generate these text ads on the fly. Unfortunately, if you participate in one of theses networks you can usually expect to fork out hundreds of dollars a month for the privalege of getting only 20-30 inbound links. Typically you’ll pay for each link. There is a better way. Many web sites have seen dramatic improvement in thier SERP and thousands of inbound links by joining the Free Text Ad Network available from Digital Point. The ad network is a network of site owners that offer ad space to the network. In return, the ads they define are displayed across the entire network. It works like an exchange where members place a bit of PHP code on content pages of thier site which create links to other member of the network. They in turn return the favor.

The best part about this network is you don’t actually have to put any links on your money site or your sales and landing pages. You simply need to create a popular site that gets indexed by Google. You can choose to have your ads point to a completely different site from the one participating in the network. The easiest way to do this is if your have a PHP based bulletin board or blogging site.

If you’re like most web site owners you’re always on the lookout for a bit of free marketing. What sales and marketing folks have known if years is that nothing is more effective than a referral from a friend or relative. In the web world this is concept is sometimes referred to as “viral-marketing”. The idea is that if a percentage of your web sites visitors tell one or more friends about your site your almost guaranteed to get more targeted traffic.

With this simple PHP script, adding the tell-a-friend function is a breeze.

First you’ll need to create a form entry HTML page (e.g. “tellafreind.htm”) where the visitor can enter their information and friends information, then place a link on your front page referring them to this page on your site. Place the following HTML in the <body> section of your newly created tell-a-friend page.

<p align=center><strong>Tell a friend about MYSITE</strong></p>
<form method="POST" action="sendtofriend.php"> </p>
<p>Your Name: <input type=text name="visitor" size="30"></p>
<p> Your Email: <input type=text name="visitormail" size="30"></p>
<p> Friend's Name: <input type=text name="friend" size="30"></p>
<p> Friend's Email: <input type=text name="friendmail" size="30"></p>
<p> Message:<br>
<textarea name=notes rows=4 cols=80></textarea></p>
<p> <input type=submit VALUE="Send Message"></p>
</form>

Now create a second send page “sendtofreind.php” with the following PHP code in the body section that gets called when the form is submitted.

<?php
$myemail = "webmaster@mysite.com";
$sitename = "MySite Title";
$urlis ="http://www.mysite.com";
$redirectlink = "http://www.mysite.com";
?>
Thank You : <?php echo $visitor ?> ( <?php echo $visitormail ?> ) <br>
For sending : <a href="<?php echo $urlis ?>"> <?php echo $sitename ?>
</a> (link)<br>
To: <?php echo $friend ?> (<?php echo $friendmail ?>)
<a href="<?php echo $redirectlink ?>"> Return to MySite Home Page </a>
<br>
<?php
$ip = getenv("REMOTE_ADDR");
if (!isset($visitormail) || !isset($friendmail))
echo "Please go back and input valid e-mail addresses. Thanks.</font> $ip" ;
$todayis = gmdate("l, F j, Y, g:i a") ;
$notes = stripcslashes($notes);
$messageis = "$todayis [GMT] \n" .
"To: $friend ($friendmail) \n" .
"Your Friend: $visitor ($visitormail) \n" .
"Recommended you visit the MySite web site ($urlis). \n" .
"Comments: $notes \n\n\n\n\n" .
"This e-mail was sent using the tell-a-friend feature at www.mysite.com " .
"from a user at IP address: $ip\r\n" .
"If this e-mail was sent inappropriately, please contact webmaster@mysite.com\r\n";

if ($csMail != "")
mail($csMail, $sitename, $messageis);
if ($friendmail != "")
mail($friendmail, $sitename, $messageis);
if ($visitormail != "")
mail($visitormail, $sitename, $messageis);
?>

Replace all occurrences of “mysite” with your site name.

Note, if you cut and paste this code your need to paste it into NotePad (or other plain text editor) first so you don’t pick up the extra HTML tags from IE.

PS. If you like this code sample, please link to our site (http://www.webmastersloom.com). It will be much appreciated.

« Previous Page