Random things with PHP

Especially when it comes to advertising, random things can be quite usefull. Random ads, sites, etc, can all be done with PHP very easily.

Step 1: Build an Array
You’ll first need an array of whatever will be random. If you are doing images, then the URLs to all the images. If you are doing banners then you’d need to do the full link and image code. In this example I’m going to make a random image script.

$randomarray = array("image1.jpg","image3.jpg","cat.gif","freddy.png");

Step 2: Output the Random Pick
Next is the core of it. I’ll put the code down, and then explain it in depth for those who need more explaination. You can of course just play with the code (the best way to learn).

$img = $randomarray[mt_rand(0, count($randomarray)-1)];
Header("Location: $img");

Explaination:

$max = count($randomarray) - 1;
$randnumber = mt_rand(0, $max);
$img = $randomarray[$randnumber];

Because looking at the one liner can be confusing, I’ve broken it down into 3 lines so you can understand it. The gist of it is this:

Line 1: Get the maximum value you want the random number to be. In this case, it is the number of items in the array minus one. That is because PHP counts 0, 1, 2, 3 not 1 2 3 4 like we do. There are 4 items in the array, but if you had a random number between 0 and 4 picked, then $randomarray[4] would return nothing.

Line 2: This is the core of it, mt_rand takes two arguements: $min, $max. Just give it the minimum and maximum numbers to pick between.

Line 3: This just assigns the chosen image to $img for easier inserting into the Header() statement.

Getting your PHP Info

One of the first things you should learn how to do with PHP, is getting all the info about your PHP installation.

Sometimes you’ll see a script that says it requires a certain setting to be one way. If you don’t know, you could be purchasing something you can’t use.

It is as simple as making a script, and naming it something like phpinfo.php – I’d recommend naming it something else, so people can’t run it themselves. The less one knows about your setup, the harder it is to be mischeaveous.

<?php
phpinfo();
?>

It’s that simple. You’ll then get a full page of information about your PHP Installation.

Search Engine Friendly URLs

Today I am going to talk about Search Engine Friendly URLs. You may not have taken them into consideration, but you should if you want good search engine rankings.

You’ve probably seen websites that have some crazily long website address, for example:
http://store.britannica.com/jump.jsp?itemType=CATEGORY&itemID=7&iMainCat=7&iSubCat=7

Not only does it make it hard for you to remember that long address, all those variables in the URL hurt the ranking of the site.

Some search engines simply get confused with the variables, but the good engines can still crawl them. However, when you use variables a couple things can happen:

  1. Google states that it will crawl dynamic pages slower
  2. The variables could be in a different order, creating a duplicate page with different url
  3. Users might link to the site, leaving out a variable, or in a different order
  4. The variables don’t describe the page.. iMainCat=7 is what category??

With that in mind, it is very important to make your URLs search engine friendly. Here are some basic tips for your URLs:

  1. Use category text, not category numerical ids
  2. Use dashes (-), not spaces
  3. Use only alpha-numeric characters, thats a-z, 0-9
  4. Use keywords in your URL
  5. Use directories sparingly, I wouldn’t go over 5 deep

If you use software like a forum or blog, chances are the software supports search engine friendly urls if you have access to htaccess and mod re-write. For instance, WordPress can make these nice blog urls with it, or you can have index.php?id=# – The sooner you use search engine friendly urls, the better!

Custom PHP Programming

If you’ve ever wanted your site to have something like a lead capture page, a members area, or some other kind of page that requires interaction from the user, than Custom PHP Programming may be for you!

Custom PHP programming can also include service kind of sites. For instance, if you ever wanted your own Traffic Exchange, Tracker Site, and any other kind of service that users sign up for. Most sites that are services include some kind of free plan, and then an upgraded paid plan with more features.

So if you have some brilliant idea, how do you know it is worth hiring a PHP programmer? Below I’ll go over some things to consider:

Consider your budget
If you have less than $500, then I wouldn’t suggest hiring a programmer to create a full blown website. They can take quite alot of time, and you don’t want to find yourself having to cut corners! If, however, its just a modification or addition to your existing site, than having less than $500 wouldn’t be bad.

Consider your market
How big is it? Is it a unique market? Are there any sites that currently offer what your bright idea is? Try doing some real research on this. You don’t want to jump into a market that already has large companies spending tons of money on their sites that people already love. It would take a whole lot to compete with them.

Consider your target audience
If your target audience is teenagers, you’ll be in for some trouble. Rarely do teenagers have money to spend, and even if they do – most either aren’t willing to spend it online, or aren’t capable of it. The younger your audience is, the harder it’ll be to get them to spend (unless you target their parents). Of course, there are exceptions to this.. It’s just alot harder.

After you’ve considered those three things, and you REALLY think you have a GOOD IDEA, then you’ll want to start rolling it into action. Remember, you’ve got to really think this through, and do alot more planning than what I’m telling you here. I’m no legal expert, and their are tons of laws that are unique to certain types of businesses, so you’ll need to do some consulting on that too. Below I’ll go over what you need to do when hiring a PHP programmer.

Review their experience
If you hire someone with little experience, they’ll likely take longer to create what it is you are looking for. For instance, I’ve built dozens of traffic exchanges – I already know exactly what it takes to make one tick, I could build one much faster than someone who doesn’t. You could hire someone to build you a traffic exchange, and have to describe anti-cheating technologies, most of which you don’t even see while surfing an exchange yourself.

If a programmer doesn’t have a website with their portfolio, areas of expertise, etc – ask them for it. Just because they don’t have it on a website doesn’t mean they don’t have any, as I’ve gotten so busy that I haven’t had time to update my own sites. But if they are reluctant to give you any past experience, go with someone else.

Get an estimate
If you feel this person can do your project, try getting an estimate. From experience, I know it is hard to give estimates. However, I can generally tell if a project is going to take a while or be quick. I’ll also tell you if it just won’t work, or if I don’t think the idea is a good one, or if I think the project is over my abilities (or at least what parts are). Find out how much they charge per hour, if there is a minimum amount per project, and see if they can give you an estimate in hours.

Just remember, it is an estimate and it can be much quicker or much longer than expected. I try to overestimate my projects to have a happy client. Also remember, if you want something changed or added after the project is complete – those changes could require big changes in the backend. If you have to, make any changes as early as possible – it’ll save you money!

Hire Me!
Well I’ve written alot, and I’m running out of writing juice. But of course if you’d like to hire me, you can find more information about me at Linden Software. I’ve also written alot of information at CLiX Network. Many clients have read what I wrote there, and hired me because they could see first hand what I know.

PHP Date QuickList

First we need to breifly go over how the date function works. It is fairly straightforward:

string date ( string format [, int timestamp] )

You simply pass a string containing the date format, and a timestamp if you don’t want to use the current time. Something to note: Any character that isn’t recognized by the date function will be displayed as is.

Character     Description
F Full text of month (January)
n Number of the month (1)
j Number of day (1)
d Number of day (01)
Y Full year (2005)

With the individual characters you can create full formats. Below are the formats that I use most frequently:

Format     Example     PHP Code
n/j/Y 10/8/2005

date(“n/j/Y”)

F j Y October 8 2005

date(“F j Y”)

For a full list of all the recognized characters visit the PHP: date – Manual. This list is only a list of the characters I use frequently myself.

PHP Multi-Page MySQL Results

If you use any search engine, they will all limit the number of results per page. Some searches can return millions of pages! Now what about your site? Do you have any pages that return more than 30 items? You can easily break that down into 10 items per page.

In this example, I will show you how to return a results page with PHP, using a MySQL database. This script will return the entire table, with 10 items per page, and it will generate the appropriate previous and next links.

The MySQL Table
This code assumes you have a table named directory with “ID”, “URL”, and “Title” fields.

The Code
[code type=php]<?
if ($page < 1) {
$page = 0;
} else {
$links[] = "<a href=’directory.php?page=".($page-1)."’>Previous</a>";
}

$global_dbh = mysql_connect("localhost","username","password");
mysql_select_db("mydatabasename", $global_dbh);

$query = "SELECT * FROM `directory` ORDER BY `ID` DESC LIMIT ".($page*10).", 11";
$result = mysql_query($query, $global_dbh);
$cnt = mysql_num_rows($result);

if ($cnt > 10) {
$cnt = 10;
$links[] = "<a href=’directory.php?page=".($page+1)."’>Next</a>";
}

echo @implode(" | ",$links);

for ($i=0; $i<$cnt; $i++) {
$row = mysql_fetch_array($result);
echo "<a href='{$row["URL"]}’>{$row["Title"]}</a><P>";
}

echo @implode(" | ",$links);
?>[/code]

The Explaination
In this code example it is assumed you have already connected to your database previously in the script, with $global_dbh

Lines 2-6: If $page is less than 1, make sure it is set to 0 to prevent negative input. Otherwise create a previous link to go back.

Lines 8-10: Here we select the database information. We start at the current page * 10, skipping over previous pages. Notice we are going to select 11 entries – if it returns 11 entries, we know to add a next page link.

Lines 12-15: Check if the returned results is greater than 10, if it is – set the counter to 10 (so we only get 10 results) and create the next page link.

Lines 17,24: Here we output the links to the browser. It looks nice having “Previous | Next”, but ugly if it was just “Previous |” or “| Next”. Using the implode function (with an @ in case there is only one link) we get the “|” only if there are two links.

Lines 19-22: Simply outputing the table rows.