Web Development

Web Development Tips & Tricks, the things that you don’t want to figure out.





Archive for the ‘Web Development

The Use Of Includes (PHP)

Monday, May 28th, 2007

It’s a very basic concept but often omitted, making life much more difficult than need be.

A basic principle that I follow is to never repeat identical code. If you have to repeat identical code somewhere, you should use an include, which will save you a lot of time and effort.

So, what is an include? It is a file that has a portion of text that you plan on using repeatedly throughout your site. For instance, the footer of your site that contains perhaps a few navigation links and your copyright is a great idea for an include. Lets say you have a very basic page, something like this:

index.php

<html>
<head>
<title>Include Example</title>
</head>
<body>
<img src=”example.jpg” />
My great website!
Copyright Joe Smith. All Rights Reservered
</body>
</html>

You can put that bottom copyright into a file, lets say footer.php (all my files are php, you can use any extension, .htm, .html, etc).

footer.php

Copyright Joe Smith. All Rights Reserved.

Now, to make this more interesting, lets say we added in some navigation at the bottom:

footer.php

HomeLinksAbout
Copyright Joe Smith. All Rights Reserved.

To include this file (remember that I’m using PHP, there are alternate methods in other scripting languages), your original page would now look like this:

index.php

<html>
<head>
<title>Include Example</title>
</head>
<body>
<img src=”example.jpg” />
My great website!
<?php include(“footer.php”); ?>
</body>
</html>

This puts all the code in footer.php right in that page. No visitor can see your php code – in this case it gets replaced by the code in the file, so it looks like a completely normal page. This enables you to put that little php include at the bottom of all your pages, and they all use the same page, so you never have to repeat that code. Now, if you change something in footer.php it will change that code on every page in your site. Most of my pages look something like this:

index.php

<?php include(“header.php”); ?>
<div id=”leftcolumn”>
<p class=”pagetitles”><b>Unsatisfied with your website?</b></p>
<p>Whether you finally decided to bring your business or career to the web, or you feel your website isn’t reaching
full potential, we can help.</p>
<p>We will build a website from ground up, walking you through every step on the way. If you want a site with
Flash Animation, E-Commerce, Support Forums, Wiki, User Login, etc., we will do it for you, completely customized
to your wish.</p>
<p>We will take care of any touch-ups or new features you need on your site – we constantly develop features for websites
or implement highly customizable ones to match your needs.</p>
<p>If you are a Web Designer but need the back-end taken care of, we will handle that. If you’re a developer and need the
design taken care of, or you need help with a specific section of your site, that will be arranged.</p><br /><br />
<br />
</div>
<? include(“footer.php”); ?>

header.php

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″ />
<title>Phoenix Development</title>
<meta name=”description” content=”Phoenix Development offers professional web design and development services for both personal and commercial websites.” />
<meta name=”keywords” content=”web design, web deveopment, phoenix development, php,” />
<link href=”/css/stylesheet.css” rel=”stylesheet” type=”text/css” media=”all” /><!–[imcss] *** Infinite Menus Core CSS: Keep this section in the document head for full validation. –>
</head><body><div id=”wrap”>
<div id=”page”>
<div id=”textarea”>

footer.php

</div><div id=”footer”>
| <a href=”/” title=”Phoenix Development Home”>Home</a> |
<a href=”/about.php” title=”About Us”>About Us </a> |
<a href=”/services.php” title=”Services”>Services</a> |
<a href=”/testimonials.php” title=”Testimonials”>Testimonials</a> |
<a href=”/referrals.php” title=”Referrals”>Referrals</a> |
<a href=”/faq.php” title=”Frequently Asked Questions”>F.A.Q.</a> |
<a href=”http://phoenixdev.wordpress.com/” target=”_blank” title=”Phoenix Development Blog”>Blog</a> |
<a href=”/contact.php” title=”Contact Us”>Contact Us</a> |
<br /><br />
<br />
© Copyright 2007 Phoenix Development. All Rights Reserved.
</div></div>
</div>
</body>
</html>

I removed a little bit of code from my website that has more advanced features. If you want to learn about those, let me know.-Kerry

htaccess – Securing a Folder

Saturday, May 26th, 2007

Ever wondered how to get that little box to pop up before you access a page, insisting that you enter in a username and password? Well, here’s how:

One of the first things you need to do is create a username and password, and there are many places that do this. This .htaccess Password Generator also gives you brief instructions in case you forget later on.

It’s going to ask you to create an .htaccess file, this is simply a text file that is only an extension. Here’s an example of the code that would go in it:

AuthName “Example Section”
AuthType Basic
AuthUserFile /usc/www/.htpasswd
require user example

The AuthName can be changed to anything. It’s just lets you know what section this is securing. Now, the AuthUserFile can be difficult. You need to get the path extension on the server to your soon-to-be .htpasswd file (its like .htaccess in that it is also just an extension). Your .htpasswd file should be in a directory below your website. For instance, if your hosting provider lets you have access to the root directory (“/”), and you put your website in “/website/” folder, you would put your .htpasswd file in the “/” directory, meaning it is not accessible off your website. Your website can access it because its on the server, but no where on your website can it be accessed (this is for security purposes).

Now, to get the path to your .htpasswd file you need to get the server variable document root. Simply put this PHP code on a test page (like “test.php”):

<?php echo $_SERVER['DOCUMENT_ROOT']; ?>

That is going to give you a path like this: “/usc/homepages/52/d167925675/htdocs/website”. Now, hopefully you managed to put your .htpasswd in a directory below your website, so this would make AuthUserFile look something like this:

AuthUserFile /usc/homepages/52/d167925675/htdocs/.htpasswd

The last line can vary. You can setup multiple usernames and passwords, if you want any of them those usernames and passwords to get access to this folder, the last line would look like this:

require valid-user

If you want a specific user, you specify the username:

require user admin

Now, your .htacccess file should look something like this:

AuthName “Example Section”
AuthType Basic
AuthUserFile /usc/homepages/52/d167925675/htdocs/.htpasswd
require user admin

Upload your .htaccess file to the folder you want secured. The next part is the contents of your .htpasswd file, which should contain the code generated by your Password Generator. If you put in the username admin with a random password, the generator should return a line like this:

admin:$1$GfdY8TeD$7mQP0niEKyKw1AIfq3Sh40

Save that line in your .htpasswd file. If you want more than one user, generator another password for another user and just put it in the next line. You can have as many users as you want:

admin:$1$GfdY8TeD$7mQP0niEKyKw1AIfq3Sh40
bob:$1$Io1beImD$fzX1R0OuyF.tx93BXOYun/
jennifer:$1$.0yS.o4t$ozvF/On0AomFSIxJ1HUx80
jimmy:$1$RC3tDZPt$ZxWEad3cZ74G9l9e3/7q71
guest:$1$glop/HIQ$8PdBnCwpSwcqFS30mY2Dl0

Now, upload your .htpasswd file to that root under your website. Your done! It should now require a password.

If you find that your password isn’t working and now you’ve locked a section of your site and can’t get in, simple remove the .htaccess file from the folder that its in, and everything should return to normal.

If you need additional assistance, feel free to contact me.

-Kerry

PHP – cURL

Wednesday, May 9th, 2007

My post today is actually not a complaint nor instructive.

Yesterday I decided I was going to figure out how I could post through a proxy server. Right before I went to bed I found the functions cURL but didn’t have enough time to thoroughly explore it, which I did today.

cURL stands for Client URL and is a very powerful too. You can send all sorts of different requests to other servers and get all sorts of information.

In the tutorial I did today, he goes over how you can get definitions from dict.org (a dictionary site) or from amazon.com with requests based off input. Of course, you have to know what’s needed on the other end, but that information is out there. You can use it to FTP files back and forth. In my case I liked the posting ability. You can post data to another server.

I had been looking for this data for months, never really trying hard, just a couple searches here and there. This is it. Instead of giving you a bunch of code how you can do it, I’m just going to refer you to this tutorial: Using cURL with PHP. He briefly goes over all the things I was telling you about, but he does assume you have a little bit of prior PHP knowledge and experience.

Of course, like most great function sets (it’s not a specific function, its a set of different functions), it has its own home page.

I hope this discovery is exciting for you as it was for me.

-Kerry

PHP MCrypt (Encryption)

Tuesday, April 24th, 2007

Wow! Haven’t posted in a while. I should start more frequently, I’ve had some very busy days.

As I touched on in a previous post, I was working an encryption. I had found that GnuPG (a free version of PGP – Pretty Good Privacy) could be used in PHP and was trying to get that working. I looked into it and it seemed pretty complicated and I didn’t easily have access to install the necessary modules on on Linux Hosting. Therefore I decided to look for an alternate method.

I needed two-way encryption, meaning I could encrypt and decrypt it. The PHP function crypt() is one-way encryption, and wouldn’t work for my needs. MCrypt(), however, is a two way encryption function that supports many different methods. To see what methods are available on your server, put in the phpinfo() function in a page and you will find a section called “mcrypt”. Here it will tell you what methods are available for your use.

A page from hudzilla.org goes over the main different encryption methods and what should be used for your situation. I ended up choosing rijndael-256 (256 bit encryption, which is quite powerful). The example I give below will use this method.

I have made two functions, one to encrypt a string and one to decrypt a string. Here they are:

function encrypt($string, $extra = “”)
{
/* Open the cipher */
$td = mcrypt_module_open(‘rijndael-256′, ”, ‘ecb’, ”);

/* Create the IV and determine the keysize length, used MCRYPT_RAND
* on Windows instead */
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_DEV_RANDOM);
$ks = mcrypt_enc_get_key_size($td);

/* Create key */
$key = substr(md5(“CoMpLiCatED K3y” . $extra), 0, $ks);

/* Intialize encryption */
mcrypt_generic_init($td, $key, $iv);

/* Encrypt data */
$encrypted = mcrypt_generic($td, trim($string));

/* Terminate encryption handler */
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return $encrypted;
}

Where “CoMpLiCatED K3y” is your key for encryption and decryption. The optional $extra argument is what you can append to your key. This can make something more secure and different encryption keys for different purposes. Here’s the decrypt function:

function decrypt($encrypted, $extra = “”)
{
/* Open the cipher */
$td = mcrypt_module_open(‘rijndael-256′, ”, ‘ecb’, ”);

/* Create the IV and determine the keysize length, used MCRYPT_RAND
* on Windows instead */
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_DEV_RANDOM);
$ks = mcrypt_enc_get_key_size($td);

/* Create key */
$key = substr(md5(“CoMpLiCatED K3y” . $extra), 0, $ks);

/* Initialize encryption module for decryption */
mcrypt_generic_init($td, $key, $iv);

/* Decrypt encrypted string */
$decrypted = mdecrypt_generic($td, $encrypted);

/* Terminate decryption handle and close module */
mcrypt_generic_deinit($td);
mcrypt_module_close($td);

return trim($decrypted);
}

The same data applies to the above function, and it returns the decrypted string.

Enjoy!
-Kerry

PHP Ternary Operator – A Rare Find

Monday, April 16th, 2007

Today I discovered the ternary operator, which I’ve seen once before, while studying C++.

The ternary operator is a one-line way to do an if else statement, and I found it very good for cutting down unnecessary code. For example, if you had the statement:

if($color == “blue”) {
$correct = true;
} else {
$correct = false;
}

You could make it something much simpler:

$color = ($color == “blue”) ? true : false;

The way the ternary operator works is: “condition ? (expression if true) : (expression if false);”. You can assign variables to it like I did, or simple print it out. I haven’t tested this yet, but I’m pretty sure you can put functions there (I don’t see why you couldn’t).

Anyway, not a big post, but I thought it would be a useful operator to know about.

-Kerry

Dynamic Content and Static URLs

Saturday, April 14th, 2007

SEO at its best!

Search engines will look at Dynamic pages as their own pages (with their own query strings), and index them as such. The advantage to having a Static URL is you can use keywords in the title which well help with your SEO. For instance, if you had an article about global warming, you might want the name to be “http://www.yoursite.com/global-warming.php”. But you don’t want to have to actually create a static page for each of those URLs.

There are two ways of doing this, one better than the other. What I had been doing for a long time is make a static page, then including the dynamic page and passing variables to it. Something like:

<?php
$articleid = 27;
include(“dynamic-page.php”);
?>

The dynamic page is coded to take that variable and then it displays the page. This is definitely better then redoing the code every page, but it can be improved.

.htaccess is the key to this solution. It can only be used on Apache servers as far as I know (sorry to those of you who have a Windows Server). Regular Expressions are also used in .htaccess, and will be in this example. The basis of this solution is you use .htaccess to redirect static links to a dynamic page, but when you redirect the links address doesn’t change. Here’s an example of how you can do that (put this code in your .htaccess file).

Options +FollowSymLinks
RewriteEngine on
RewriteRule ^(.*)-a-([0-9]*).php$ /dynamic-page.php?articleid=$2 [L]

Ok, basically says any link to .php that ends with “-a-” (number) “.php” will be sent to your dynamic page, with the query string “articleid=” (number). So, lets say you went to “global-warming-a-27.php” it would redirect the page to “/dynamic-page.php?articleid=27″. Now your page can use that ID to call the right article from the database or wherever you’re storing the article.

That’s it! It’s as simple as that. This will allow you to create static urls, so Search Engines can find them and people can book mark them, but you don’t have to create any extra code.

-Kerry

Reading XML – XSL or PHP?

Friday, April 6th, 2007

XML, or Extensible Markup Language, is probably the most versatile language there is.

Since you make your own tags, and then get readers to use them, you can use the data in them for pretty much anything. Well, today I was making my php reader display a bunch of URLs based on a category they were in. They also had special attributes and so on, all of which was contained in an XML file.

As I was looking at my sitemap, I realized that it had formatting, but it was an XML, and XML files can’t format themselves. So, I found out that it called an XSL (or Extensible Stylesheet Language) file that gave it formatting. XSL is a language used to make XML in HTML or XHTML. Call glorified HTML or XHTML (has in built functions to read XML). You can make entire pages, or parts of pages in XHTML and call in the data from an XML sheet.

If this is the language, why should you use the roundabout method offered in PHP? It took me some time thinking and wondering the advantages of each. Realise, I don’t know XSL (I started learning today), so I don’t know its full functionality. I do know, however, that you can see the XSL file and you can see the XML file. There’s a difference.

PHP code is server side, meaning completely executed before it reaches you, so you can’t see it. This includes the call to the XML file. This means you can display data based on an XML file without letting the surfer know that you called an XML file. This is a security feature, which I kind of enjoy for my current purpose of the URLs.

Now, I assume that XSL has a lot more functionality than PHP, seeing as how it is a language specifically to convert XML into HTML or XHTML. PHP is a complete programming language. It actually didn’t have a lot of it’s support for XML until PHP5 came out.

One more thing while we’re on the subject of URLs. I needed to grab just the domain name out of a url. For example in “http://www.google.com” I want just “google.com”. In the case of “http://mail.google.co.uk” should match “mail.google.co.uk”. I decided to see if I could put my regex skills to work, and I came up with this: “(?:www\.)?([^.\/]+\.(?:[a-zA-Z]+\.)*(?:[a-zA-Z]{2}\.[a-zA-Z]{2}|[a-zA-Z]{2,4}))” which matches both of those examples. You simply have to grab the return value (there’s only one) and it will have the right result.

-Kerry

Mastering Regular Expressions (2)

Friday, March 30th, 2007

First chapter complete! And so I shall share with thee my knowledge of this divine subject…

They have a summary of the chapter, so I’ll basically just hit those points. Here are the symbols and what they mean.

  • . or dot means any character – number, digit or symbol.
  • [] encloses a character class, which has it’s own set of rules. It will match any one character listed. For example, [0-9a-zA-Z] is looking for any 1 character that is a digit, a lowercase letter or an uppercase letter. The hyphen in a character class shows a range, like 0-9 means 0 through 9. The only exception is if it’s at the beginning, like [-0-9] would mean to either get a hyphen or a digit.
  • \char can change the value or escape a character. For instance, \. would mean literally a ., while \< and \> can mean the beginning and ending of a word, respectively.
  • ? applies to the preceding 1 character or expression, meaning there may be 0 or 1 of the expression. So you could say colou?r to allow an optional u in the word color. If you said [0-9a-zA-Z]? it would mean an optional letter or digit.
  • * applies to the preceding 1 character or expression, meaning there may be 0 or more. So if you said [0-9]* it would mean that you were allowing an infinite amount of digits, or none.
  • + applies to the preceding 1 character or expression, meaning there may be 1 or more of the expression. So if you put [0-9]+ that would mean that there needs to be atleast 1 number, but can contain an infinite amount.
  • ^ (also called a caret) means to match from the beginning of the line or string, so if you said ^[0-9], it would not match the string “I’m 12″, but it would match the string “12 I am” (it would match the 1, since the character class only matches one character). It also has a special meaning inside of a character class. If you put a caret inside a character class, like [^0-9], that means anycharacter that is not a ______. In this case, any character that is not a digit.
  • $ means it matches at the end of a line. So if we used our previous example, but warped a little bit, ^[0-9]$ would mean the string or line would need to have 1 digit on it, and nothing else. Both “12 I am” and “I’m 12″ would not match. “12″ would also not match. It would match “1″ or “2″. On the other hand, if you put in ^[0-9]+$ that would mean that it would match “1″, as well as “12″, or “314159265″ etc.
  • \< As I briefly mentioned earlier means the start of a word. So if you said “\<at” (I’m starting to use double quotes to make it more clear) that would match “at” or event “attached”, but it would not match “categories”.
  • \> means the end of a word, so if you put “ate\>” it would match “ate” and “fate“, but not “categories”. “\<ate\>” would only match the word “ate”. Note on the last two, they are not supported by all regex utilities, so you should test it before you rely on it.
  • | means alternate when inside of parentheses. For example, if you were matching an extension of a file, like an image, your regex might look something like “(jpg|jpeg|gif|bmp|png|tiff)$”. That would mean any of those options would match.
  • () (parentheses) can be used for alternation, or grouping so that the symbols, ?, * and + will work on entire expression. For instance, if you said ([0-9]\.)+ that would mean you would have the whole expression (0-9]\.) 1 or more times to match. It is also used for captures (coming up next).
  • \1, \2, etc… refers to a back reference. This means that \1 will refer to the text matched in a set of parentheses. The example used in the book was used for editting. If you wanted to find everytime a word was repeated, you could use a regex like “\<([a-zA-Z]+) +\1\>” and that would match any word that doubled itself. If that’s a bit confusion, in english it says, start at the beginning of a word, followed by a word with 1 or more letters, with 1 or more spaces between it and the next word, while the next word is the same as the first word. If that’s a bit confusing, I’m sorry, but here’s an example it would match. “He ran ran to the store.” It would also match “He ran    ran to the store,” or a number of other combinations. Back references may not be supported by all regex checkers, so make sure you test it.

I hope that helped, and if you have any questions, feel free to contact me or get the book. It explains it far better than I did (that was basically a 30 page chapter). I’m just giving you the highlights if you want to get into the nitty gritty fast.

Shopping Carts

Thursday, March 29th, 2007

Which one should you pick? There are many you can pay for, which I’ve never used, and there are many that are free, of which I’ve used a couple.

osCommerce is a great open source (hence the “os”) shopping cart. It’s one of the most widely used shopping carts, but it’s made for huge sites. If you have 5-10 items or so, it’s definitely not made for you .This can supports thousands of items, complex categories and shipping methods and so on. It integrates into all sorts of paying methods, obviously Paypal is one of them. There are also thousands of modules that people have made (since it’s open source) and you can get them all from their home page. They also have a support forum to answer all your questions and thorough help guides. You can completely customize the look and feel of the shopping cart (it can require you to get into the nitty-gritty part of the code), and is overall my favorite shopping cart, and definitely a good pick.

The second shopping cart I found while attempting to find a nice and simple one was Zen Cart. Unfortunately, it related to osCommerce in many ways. It can be used for less items, but it takes a bit to get into it. Not something you pickup and implement in a few minutes (which is what I was trying to do.) I don’t know why you would pick this over osCommerce of vice versa, but if for some reason you have a grudge against one of them, choose the other.

The small shopping cart I ended up using was the Paypal Shopping Cart. It’s free to use, and you simple fill in a bunch of form fields and make a button for each one, and it handles the rest. It’s not very customizable at all, but if you only have a few items, and want to sell them individually, it will do the trick. They have demos you can see, pdfs with instructions and a support form for your use.

One shopping cart I suggest not using is 1ShoppingCart.com. You have to pay for it, and I’ve heard from fellow web friends that it is simply a terrible shopping cart.

If you have any more questions, feel free to let me know.

Until next time,
Kerry

Tools of the Web Master

Monday, March 19th, 2007

There is a vast amount of tools that can be used in web development. In this blog I’m going to give you my opinions on a few of them.

Well, the first thing I’m going to talk about is the use of WYSIWYG (what you see is what you get) editors. One of the most common, and worst ones is Front Page. I haven’t actually used this product, but I’ve never heard someone speak of it highly. I’ve seen it ruin the code on pages (make really confusing a bad code), so I really don’t suggest that.

As a web developer, I don’t actually use WYSIWYG, but I do use Dreamweaver (DW). This is a great design tool and supports all languages besides ASP.NET. Unfortunately, DW isn’t free. If you have the money to get it, it’s got a lot of useful tools and I’ve been using it for years with very few problems. The older versions (not DW 8 ) also can create some messy code if you use the Design View, so if make sure you clean the code up after.

Microsoft Visual Web Developer 2005 Express Edition is a free WYSIWYG. Along that line, they have an express edition (means it’s free) of every language in Microsoft Visual Studio. They are apparantly not a powerful but I haven’t hit their limitation yet, and they’re great tools. They keep your code clean, and they do support ASP.NET (if you’re programming in ASP.NET, this is a must). The reason why I don’t use them all the time is they don’t support PHP, which is their one downfall. PHP is best run on Apache, which is best run on Linux, which is kind of Microsoft’s rival. If you want a free PHP WYSIWYG, I haven’t it before but I think PHP Designer 2007 – Personal is a good one.

Both DW and the Microsoft Visual Web Developer have built in FTP programs, but if you decide on another editor, or already have one that doesn’t include an FTP program, you may want to know a good one. Core FTP LE is a great free FTP program that I’ve used for various other reasons in the past and it works very well, so this is my suggestion.

Another unusual program that can come in handy is a better notepad. Sometimes, for various reasons, you may have to open a certain file in notepad instead of your editor. I’ve tried two, but was completely satisfied with Notepad++. It supports color coding for pretty much every language and some other really good features. It’s definitely my pick.

Graphic tools. There are many different graphics programs that may interest you, many are kind of pricey. My favorite is Adobe Photoshop CS2. It’s kind of complex, but really has the tools to help make great artwork. There are also many tutorials all over the internet to teach how to do pretty much anything with it, and it’s probably the most popular of the graphics programs.

Fireworks is the graphics program that comes in the Macromedia Suite. It’s very user friendly and integrates into the other Macromedia products nicely, but I don’t like it nearly as much Photoshop, even though it has a lot of functionality.

The next program I would go to, the only free one I recommend, is GIMP (pardon the name). It’s the only open source graphics program I know, and it’s supposed to have similar functionality to Photoshop. I didn’t like it because it seemed to be a bit more confusing and used several windows instead of one. I have, however, seen a lot of great artwork created with GIMP, so it’s definitely a good choice.

That’s it for now. There are more specific programs for specific areas of web development, but I will go into those later .

Until next time,
Kerry