December 13, 2007

How to Calculate PHP Load Times

Filed under: PHP — Matt @ 8:42 am

Here’s a popular request amongst those who are learning PHP. When developing PHP applications, it’s good practice to benchmark your pages to see if you need to further optimize your code. The following snippet will show you how much time it took your server to process your PHP document.

Insert this at or near the top of your PHP file.

$m_time = explode(" ",microtime());
$m_time = $m_time[0] + $m_time[1];
$loadstart = $m_time;

Now place this snippet at or near the bottom of your file for the best results.

$m_time = explode(" ",microtime());
$m_time = $m_time[0] + $m_time[1];
$loadend = $m_time;
$loadtotal = ($loadend - $loadstart);
echo "<small><em>Generated page in ". round($loadtotal,3) ." seconds</em></small>";

That’s it! I suggest adding this while you develop any PHP application, and include it even after the launch, so that you can see how well your scripts scale with the traffic you receive.

October 21, 2007

Protecting Your PHP/MySQL Queries from SQL Injection

Filed under: MySQL, PHP — Matt @ 6:36 am

SQL injection is a serious concern for webmasters, as an experienced attacker can use this hacking technique to gain access to sensitive data and/or potentially cripple your database. If you haven’t secured your applications, I implore you to get yourself familiar with the following method and grind it into your coding routine. One unsafe query can result in a nightmare for you or your client.

I’ve read through a lot of guides, and they tend to over complicate this, so I’ll be as straight forward as possible. In PHP the easiest way is to pass your data through the mysql_real_escape_string function. By escaping special characters on fields where the user can manipulate the database, you will avoid being vulnerable. Take a look below at the example of what to do and what not to do.

// This is a vulnerable query.
$query = "SELECT * FROM products WHERE name='$productname'";
mysql_query($query);

// This query is more secure
$query = sprintf("SELECT * FROM products WHERE name='%s'",
mysql_real_escape_string($productname));
mysql_query($query);

Since I primarily code in PHP, I can’t confidently provide techniques for other programming languages. The most important part of protecting yourself is stopping users from being able to pass unaltered database manipulative special characters, like single quotes.

MSDN - SQL Injection Article
Wikipedia - SQL Inection
SecuriTeam - SQL Injection Walkthrough
SitePoint - SQL Injection Attacks, Are You safe?

October 16, 2007

How to Check Link Popularity in Google & Yahoo With PHP

Filed under: PHP, SEO — Matt @ 4:31 pm

Everyone knows that the best traffic you can get is organic, meaning people who come to your site naturally with genuine interest. Search engines like Google & Yahoo are notorious for placing a high value on the amount of websites that are linking to you. While their algorithms haven’t been completely unraveled yet, SEO specialists have a pretty good idea of how to make your site rank higher, and it usually starts with link building (assuming you have quality content first of course!).

The amount of links your site has indexed in Google & Yahoo can change often, so checking can be an arduous task. Luckily there are a ton of tools out there for this, but you’re not here for that, are you? You’re here because you want the code to run your own service, or maybe you want your own local copy of it, or maybe you just want to see how it works. The script below will check your backlinks in Google and Yahoo, as well as your Alexa rating. Feel free to modify and redistribute (non-commercially) as you see fit.

Live Demo | View Source Online

<?php
// Setting the URL variable
$link = $_GET['url'];

// Google Backlinks
function fetch_google($uri) {
$uri = trim(eregi_replace('http://', '', $uri)); $uri = trim(eregi_replace('http', '', $uri));
$url = 'http://www.google.com/search?hl=en&lr=&ie=UTF-8&q=link:'.$uri;
$v = file_get_contents($url);
preg_match('/of about \<b\>(.*?)\<\/b\>/si',$v,$r);
return ($r[1]) ? $r[1] : '0';
}

// Yahoo Inlinks
function fetch_yahoo($uri) {
$uri = trim(eregi_replace('http://', '', $uri)); $uri = trim(eregi_replace('http', '', $uri));
$url = 'http://siteexplorer.search.yahoo.com/search?p=http://'.$uri.'&bwm=i&bwmf=s&bwmo=&fr2=seo-rd-se';
$v = file_get_contents($url);
preg_match('/of about \<strong\>(.*?) \<\/strong\>/si',$v,$r);
return ($r[1]) ? $r[1] : '0';
}

// Alexa Rating
function fetch_alexa($uri){
$uri = trim(eregi_replace('http://', '', $uri)); $uri = trim(eregi_replace('http', '', $uri));
$url = 'http://data.alexa.com/data?cli=10&dat=snbamz&url=' . urlencode($uri);
$v = file_get_contents($url);
preg_match('/\<popularity url\="(.*?)" TEXT\="([0-9]+)"\/\>/si', $v, $r);
return ($r[2]) ? $r[2] : '0';
}

// Page Header
echo "<h2>Search Engine Popularity</h2>";

// Display Links and Information
if (isset($link)) {
echo "<strong>URL:</strong> " . $link . "<br />";
echo "<strong>Google Backlinks:</strong> " . fetch_google($link) . "<br />";
echo "<strong>Yahoo Backlinks:</strong> " . fetch_yahoo($link) . "<br />";
echo "<strong>Alexa Rating:</strong> " . fetch_alexa($link) . "<br />";
}

// Search Form
echo "<br />
<form action=\"linkcheck.php\" method=\"get\">
<input type=\"text\" name=\"url\" />
<input type=\"submit\" />
</form>";

?>

October 14, 2007

Startup Kit for Making Websites from Scratch

Filed under: CSS, HTML, PHP — Matt @ 5:42 pm

If you’re somewhat new to making websites, or if you’re like me and find yourself making new websites on a regular basis, whether it’s for work or something else, you might find this useful. I find it a chore to constantly make the same files when making a new website, so I’ve put together a basic startup kit that contains all the files/folders I usually need to get going with the development. Here’s what’s included:

index.php > With doctype & appropriate head tags defined.
robots.txt > With major search engines allowed by default, cgi-bin disallowed.
style/global.css > With a couple basic preset classes.
style/index.html > Blank file to disable directory browsing.
images/spacer.gif > 1×1 pixel transparent gif.
images/index.html > Blank file to disable directory browsing.

Download: http://www.metatitan.com/files/sitestartup.zip

Extract the zip and use these files as a starting point when making websites. There isn’t instruction included with these files, if you know what you’re doing you’ll know what to do with them. If not, I’ll probably have a guide for this eventually.

October 12, 2007

How to Protect Your PHP Code With Encryption

Filed under: PHP — Matt @ 4:42 am

This was an article I wrote for Web Hosting Talk back in April 2004. I’ve made a few revisions to it and felt it would be worthwhile to share here as well.

This guide is intended for programmers who frequently take on freelance projects, those contracted over the internet by strangers to make a PHP script. Due to the nature of the web, it’s very easy to get scammed in this exchange, and there usually isn’t much you can do about it if it happens. Luckily for you, you’re 1 step ahead of the scammers by reading this guide before you sent them your script (hopefully).

Scenario: You are paid $1,500 to write a PHP script for Joe Montana. Joe pays you, you send him the script, all is well, until Joe reverses the charges, leaves you out in the cold while you just wasted several weeks and he gets a free script. Now you have to stress yourself with tracking him down to press charges, which most of the time never happens. Debating intangibles over the internet is a sticky situation for the seller, aka service provider, aka you. I just read the same story on another forum, which is all too common, and this prompted me to share this with hopes of protecting your time and profit.

Step 1
Open the file that is critical to the script’s operation and won’t require modifications by the client at any point in time. You’ll want to pick a file that if you take it out of the picture, it will cripple the operation of his script.

Step 2
Paste this snippet at the top of the file, before the script’s operations are run.

$lines = file('http://www.example.com/joemontana.txt');
foreach ($lines as $line_num => $line) {
$license = htmlspecialchars($line);
if ($license == "invalid") {
exit("License Invalid - Please contact THECOMPANY");
}
}

Now do the following:
- Create a .txt file, call it something unique, preferably the name of the project/client.
- Upload the .txt file somewhere accessible from the web, preferably on your server where only you can write to it.
- On Line 1 of the code above: Change example.com/joemontana.txt to your website and path to the text file you uploaded.
- On Line 5 of the code above: Change YOURCOMPANY to its respective variable. You can edit this message to say whatever you want.

Now if at any time you have a reason to disable his script, all you need to do is open that text file, and type the word: invalid

After you save that file, his script will not function. This method is safe for your client; if your server is down, the file doesn’t exist, or anything other than the word “invalid” is in the document, it will function properly.

Step 3
Now you’re thinking, “That’s good Matt, but what if the client isn’t an idiot and he goes in and deletes my protection”. This is where encoding comes into play. Pick your favorite one, if you don’t have one in mind, I suggest IonCube. Encrypting a file with them through their Online Encoder costs 50 cents, which is peanuts when you consider the sheer satisfaction you’ll receive if a client does scam you and you’re able to pull the rug from under them.

After your file is encrypted, open it up in a text editor, you should see a bunch of nonsensical data in there. Pack it up and ship it to your client! It’s important to remember that you’re not safe from being scammed, always exercise caution when doing business over the Internet. You’ll at least have a lot more control over the situation using these methods.

I suggest that you inform your client that you will be encrypting the file. Include instructions and offer to install the IonCube loaders on their server. Make sure to tell them to upload the encrypted file in BINARY mode, as it will not work otherwise. You should send them the unencrypted file after a couple months from their payment (or whenever you feel it has fully cleared and you’re safe) for their convenience, people don’t like being under the gun forever.

These instructions are provided without warranty. Any damage or loss, yadda yadda yadda *insert long disclaimer here*, is your own fault.

How to Display Server Load in PHP

Filed under: PHP — Matt @ 3:35 am

As the inaugural post on my new blog, I figured I’d start with something I put to good use today. When developing a PHP application or monitoring a web server, it’s important to know what your server load is to properly identify that there is a problem. This can be achieved through most control panel software (like WHM) or by typing in “uptime” in your SSH command prompt.

For those interested, there is a very easy way to output your load in PHP using the exec function. See the code below.

$load = exec(”uptime”);
$load = split(”load average:”, $load);
$load = split(”, “, $load[1]);
$load = $load[0];
echo “Current Load: $load”;

Place that snippet wherever you want in your PHP application to output the current server load. If you want to display something like “03:55:48 up 49 days, 13:36, 0 users, load average: 0.04, 0.12, 0.10″ instead of just “0.04″, you can delete lines 2-4 of the code.

Of course, since “uptime” is a Unix command this won’t work on Windows servers, and from what I understand, there’s no easy solution for those users.