Saturday, November 3, 2007

XOR-Encryption With C

Exclusive-OR encryption, while not a public-key system such as RSA, is almost unbreakable through brute force methods. It is susceptible to patterns, but this weakness can be avoided through first compressing the file (so as to remove patterns). Exclusive-or encryption requires that both encryptor and decryptor have access to the encryption key, but the encryption algorithm, while extremely simple, is nearly unbreakable.

Exclusive-OR encrytion works by using the boolean algebra function exclusive-OR (XOR). XOR is a binary operator (meaning that it takes two arguments - similar to the addition sign, for example). By its name, exclusive-OR, it is easy to infer (correctly, no less) that it will return true if one, and only one, of the two operators is true. The truth table is as follows:

A   B    A XOR B

T T F

T F T

F T T

F F F

(A truth table works like a multiplication or addition table: the top row is one list of possible inputs, the side column is one list of possible inputs. The intersection of the rows and columns contains the result of the operation when done performed with the inputs from each row and column)

The idea behind exclusive-OR encryption is that it is impossible to reverse the operation without knowing the initial value of one of the two arguments. For example, if you XOR two variables of unknown values, you cannot tell from the output what the values of those variables are. For example, if you take the operation A XOR B, and it returns TRUE, you cannot know whether A is FALSE and B is TRUE, or whether B is FALSE and A is TRUE. Furthermore, even if it returns FALSE, you cannot be certain if both were TRUE or if both were FALSE.

If, however, you know either A or B it is entirely reversible, unlike logical-AND and logical-OR. For exclusive-OR, if you perform the operation A XOR TRUE and it returns a value of TRUE you know A is FALSE, and if it returns FALSE, you know A is true. Exclusive-OR encryption works on the principle that if you have the encrypted string and the encryption key you can always decrypt correctly. If you don’t have the key, it is impossible to decrypt it without making entirely random keys and attempting each one of them until the decryption program’s output is something akin to readable text. The longer you make the encryption key, the more difficult it becomes to break it.

The actual way exclusive-OR encryption is used is to take the key and encrypt a file by repeatedly applying the key to successive segments of the file and storing the output. The output will be the equivalent of an entirely random program, as the key is generated randomly. Once a second person has access to the key, that person is able to decrypt the files, but without it, decryption is almost impossible. For every bit added to the length of the key, you double the number of tries it will take to break the encryption through brute force.

C++ uses ^ for bit-level exclusive-OR. To encrypt a single character you can use char x=x^key; if you have a key of one byte. To encrypt a string of characters with a longer key, you can use something akin to the following code:

#include 

int main()

{

char string[11]="A nice cat";

char key[11]="ABCDEFGHIJ";

for(int x=0; x<10; x++) {

string[x]=string[x]^key[x];

cout<<string[x];
}

return 0;

}

The program encrypts each character in the string using the ^ bit operator to exclusive-OR the string value with the key value for each character.

http://www.cprogramming.com

Thursday, August 16, 2007

Regular Expressions

Basic Syntax of Regular Expressions (as from PHPBuilder.com)


First of all, let's take a look at two special symbols: '^' and '$'.

What they do is indicate the start and the end of a string, respectively, like this:"^The": matches any string that starts with "The";

"of despair$": matches a string that ends in the substring "of despair";

"^abc$": a string that starts and ends with "abc" -- that could only be "abc" itself!

"notice": a string that has the text "notice" in it.


You can see that if you don't use either of the two characters we mentioned, as in the last example,
you're saying that the pattern may occur anywhere inside the string -- you're not "hooking" it to any of the edges.

There are also the symbols '*', '+', and '?', which denote the number of times a character or a sequence of
characters may occur. What they mean is: "zero or more", "one or more", and "zero or one."

Here are some examples:

Wednesday, August 15, 2007

Assembly Language

Assembly language is essentially the native language of your computer. Technically the processor of your machine understands machine code (consisting of ones and zeroes). But in order to write such a machine code program, you first write it in assembly language and then use an assembler to convert it to machine code.

However nothing is lost when the assembler does its conversion, since assembly language simply consists of mnemonic codes which are easy to remember (they are similar to words in the english language), which stand for each of the different machine code instructions that the machine is capable of executing.

Here is an example of a short excerpt from an assembly language program:

MOV EAX,1
SHL EAX,5
MOV ECX,17
SUB EAX,ECX
....

An assembler would convert this set of instructions into a series of ones and zeros (i.e. an executable program) that the machine could understand.

Because it is extremely low level, assembly language can be optimized extremely well. Therefore assembly language is used where the utmost performance is required for applications.

Assembly language is also useful for communicating with the machine at a hardware level. For this reason, it is often used for writing device drivers.

A third benefit of assembly language is the size of the resulting programs. Because no conversion from a higher level by a compiler is required, the resulting programs can be exceedingly small. For this reason, assembly language has been a language of choice for the demo scene. This involves coders writing extremely small programs which show off their creative and technical abilities to other members of the scene.

In this tutorial you will learn how to write assembly language programs and how to make use of these to do interesting things such as calculations, graphics, writing windows programs and optimizing programs written in other languages.

Monday, July 16, 2007

All about computer’s virusses

Your computer is as slow as molasses. Your mouse freezes every 15 minutes, and that Microsoft Word program just won’t seem to open.

You might have a virus.

Just what exactly is a virus? What kind is in your computer? How did it get there? How is it spreading and wreaking such havoc? And why is it bothering with your computer anyway?

Viruses are pieces of programming code that make copies of themselves, or replicate, inside your computer without asking your explicit written permission to do so. Forget getting your permission down on paper. Viruses don’t bother to seek your permission at all! Very invasive.

In comparison, there are pieces of code that might replicate inside your computer, say something your IT guy thinks you need. But the code spreads, perhaps throughout your office network, with your consent (or at least your IT guy’s consent). These types of replicating code are called agents, said Jimmy Kuo, a research fellow with McAfee AVERT, a research arm of anti-virus software-maker McAfee Inc.

In this article, though, we’re not talking about the good guys, or the agents. We’ll be talking about the bad guys, the viruses.

A long, long time ago in computer years, like five, most viruses were comprised of a similar breed. They entered your computer perhaps through an email attachment or a floppy disk (remember those?). Then they attached themselves to one of your files, say your Microsoft Word program.

When you opened your Microsoft Word program, the virus replicated and attached itself to other files. These could be other random files on your hard drive, the files furthest away from your Microsoft Word program, or other files, depending on how the virus writer wanted the virus to behave.

This virus code could contain hundreds or thousands of instructions. When it replicates it inserts those instructions, into the files it infects, said Carey Nachenberg, Chief Architect at Symantec Research Labs, an arm of anti-virus software-maker Symantec. Corp.

Because so many other types of viruses exist now, the kind just described is called a classic virus. Classic viruses still exist but they’re not quite as prevalent as they used to be. (Perhaps we could put classic viruses on the shelf with Hemingway and Dickens.)

These days, in the modern era, viruses are known to spread through vulnerabilities in web browsers, files shared over the internet, emails themselves, and computer networks.

As far as web browsers are concerned, Microsoft’s Internet Explorer takes most of the heat for spreading viruses because it’s used by more people for web surfing than any other browser.

Nevertheless, “Any web browser potentially has vulnerabilities,” Nachenberg said.

For instance, let’s say you go to a website in IE you have every reason to think is safe, Nachenberg said.

But unfortunately it isn’t. It has virus code hidden in its background that IE isn’t protecting you from. While you’re looking at the site, the virus is downloaded onto your computer, he said. That’s one way of catching a nasty virus.

During the past two years, another prevalent way to catch a virus has been through downloads computer users share with one another, mostly on music sharing sites, Kuo said. On Limewire or Kazaa, for instance, teenagers or other music enthusiasts might think they’re downloading that latest Justin Timberlake song, when in reality they’re downloading a virus straight into their computer. It’s easy for a virus writer to put a download with a virus on one of these sites because everyone’s sharing with everyone else anyway.

Here’s one you might not have thought of. If you use Outlook or Outlook Express to send and receive email, do you have a preview pane below your list of emails that shows the contents of the email you have highlighted? If so, you may be putting yourself at risk.

Some viruses, though a small percentage according to Nachenberg, are inserted straight into emails themselves.

Forget opening the attachment. All you have to do is view the email to potentially get a virus, Kuo added. For instance, have you ever opened or viewed an email that states it’s “loading”? Well, once everything is “loaded,” a virus in the email might just load onto your computer.

So if I were you, I’d click on View on the toolbar in your Outlook or Outlook Express and close the preview pane. (You have to click on View and then Layout in Outlook Express.)

On a network at work? You could get a virus that way. Worms are viruses that come into your computer via networks, Kuo said. They travel from machine to machine and, unlike, the classic viruses, they attack the machine itself rather than individual files.

Worms sit in your working memory, or RAM, Nachenberg said.

OK, so we’ve talked about how the viruses get into a computer. How do they cause so much damage once they’re there?

Let’s say you’ve caught a classic virus, one that replicates and attacks various files on your computer. Let’s go back to the example of the virus that initially infects your Microsoft Word program.

Well, it might eventually cause that program to crash, Nachenberg said. It also might cause damage to your computer as it looks for new targets to infect.
This process of infecting targets and looking for new ones could eventually use up your computer’s ability to function, he said.

Often the destruction a virus causes is pegged to a certain event or date and time, called a trigger. For instance, a virus could be programmed to lay dormant until January 28. When that date rolls around, though, it may be programmed to do something as innocuous but annoying as splash popups on your screen, or something as severe as reformat your computer’s hard drive, Nachenberg said.

There are other potential reasons, though, for a virus to cause your computer to be acting slow or in weird ways. And that leads us to a new segment – the reason virus writers would want to waste their time creating viruses in the first place.

The majority of viruses are still written by teenagers looking for some notoriety, Nachenberg said. But a growing segment of the virus-writing population has other intentions in mind.

For these other intentions, we first need to explain the “backdoor” concept.

The sole purpose of some viruses is to create a vulnerability in your computer. Once it creates this hole of sorts, or backdoor, it signals home to mama or dada virus writer (kind of like in E.T.). Once the virus writer receives the signal, they can use and abuse your computer to their own likings.

Trojans are sometimes used to open backdoors. In fact that is usually their sole purpose, Kuo said.

Trojans are pieces of code you might download onto your computer, say, from a newsgroup. As in the Trojan War they are named after, they are usually disguised as innocuous pieces of code. But Trojans aren’t considered viruses because they don’t replicate.

Now back to the real viruses. Let’s say we have Joe Shmo virus writer. He sends out a virus that ends up infecting a thousand machines. But he doesn’t want the feds on his case. So he instructs the viruses on the various machines to send their signals, not of course to his computer, but to a place that can’t be traced. Hotmail email happens to be an example of one such place, Kuo said.

OK, so the virus writers now control these computers. What will they use them for?
One use is to send spam. Once that backdoor is open, they bounce spam off of those computers and send it to other machines, Nachenberg said.

That’s right. Some spam you have in your email right now may have been originally sent to other innocent computers before it came to yours so that it could remain in disguise. If the authorities could track down the original senders of spam, they could crack down on spam itself. Spam senders don’t want that.

Ever heard of phishing emails? Those are the ones that purport to be from your internet service provider or bank. They typically request some information from you, like your credit card number. The problem is, they’re NOT from your internet service provider or your bank. They’re from evil people after your credit card number! Well, these emails are often sent the same way spam is sent, by sending them via innocent computers.

Of course makers of anti-virus software use a variety of methods to combat the onslaught of viruses. Norton, for instance, uses signature scanning, Nachenberg said.

Signature scanning is similar to the process of looking for DNA fingerprints, he said. Norton examines programming code to find what viruses are made of. It adds those bad instructions it finds to its large database of other bad code. Then it uses this vast database to seek out and match the code in it with similar code in your computer. When it finds such virus code, it lets you know!

by Kara Glover

Friday, June 8, 2007

How to Install a WebDAV Server in PHP

How to install a webdav server in PHP

It's very simple.

  • Download this package, and decompress it.
  • The inc folder contains PEAR and the HTTP_WebDAV_Server class.
  • Copy the inc folder and authenticate.php file in the include_path (see php.ini)
  • Copy webdav.php file in the root of your site.

The authenticate.php file contains a digest authentification.

The webdav.php file create a webdav server


include_once("authenticate.php");

ini_set("error_reporting", "");

# Name of your restricted area
$realm = 'Restricted area Keyphrene';
$DBUSER = "your login";
$DBPWD = "your password";
$users = array($DBUSER => $DBPWD);
# With this authentication method,
# your password is not readable when you use this service
AuthenticationDigestHTTP($realm, $users);
# AuthenticationBasicHTTP($realm, $users);

require_once "HTTP/WebDAV/Server/Filesystem.php";
$server = new HTTP_WebDAV_Server_Filesystem();
# Database configuration for the lock method
$server->db_host = $DBHOST;
$server->db_name = $DB_WEBDAV;
$server->db_user = $DBUSER;
$server->db_passwd = $DBPWD;
# Real path of your site
$server->ServeRequest($DOCUMENT_ROOT."/www/");

?>

To use this service, you must connect you at this adress http://mysite.org/webdav.php. You can configure a lot of access on your site. Becareful, if you must copy files on your server, you must use the good permissions with the FTP client.

Thursday, June 7, 2007

LIBNAME Statement Support for WebDAV Servers

   LIBNAME statement support for WebDAV servers will be available for use
in SAS® 9.1.3 (9.1 TS1M3) with hot fix D9BA08, which is currently
under production.

The LIBNAME statement is being extended to allow access to content
stored in a Web Distributed Authoring and Versioning (WebDAV) server.

Syntax

LIBNAME libref 'SAS-library' WEBDAV USER="user-ID"
PASSWORD="user-password";

Where 'SAS-library' specifies the URL location (path) on a WebDAV
server. The URL specifies either HTTP or HTTPS communication protocols.

Only one data library is supported when using the WebDAV extension to
libnames. REMOTE engines are not supported with the WebDAV options.


WebDAV Specific Options

WEBDAV
specifies that the libref accesses a WebDAV server.

USER="user-ID"
specifies the user name for access to the WebDAV server. The user-ID is
case-sensitive, so it must be in single or double quotes.
Alias: UID

PASSWORD="user-password"
specifies a password for the user to access the WebDAV server. The
user-password is case-sensitive, so it must be in single or double
quotes.
Alias: PWD=, PW=, PASS=


Data Set Options

The following table lists the data set options that have different
functionality when using a WebDAV server. All other data set options
will function as described in the SAS Language: Reference.

Data Set Option Functionality with WebDAV

Data Set Option WebDAV Storage Functionality

CNTLLEV= LIB locks all data sets in the library prior to writing
the data into the local cache. All members are unlocked
once the data step has completed and the data set has
been written back to the WebDAV server.

MEM locks the member prior to writing the data into the
local cache. Member is unlocked once the data step has
completed and the data has been written back to the
WebDAV server.

REC is not supported. WebDAV will only allow updates to
the entire data set.

FILECLOSE VxTAPE engine is not supported, therefore this option
is ignored.

GENMAX= This functionality is not supported because the maximum
number of revisions to keep cannot be specified in
WebDAV.

GENNUM= If present, the specific version specified isnot
retrieved from the WebDAV server for read-only access.

IDXNAME= Users can specify an index to use if one exists.
However, to use this option, you need to
have accessed the data set (to get it locally) then
created an index so that it would be available.

INDEX= Indexes may be created in the local cache and used in
subsequent DATA steps.

TOBSNO= Remote engines are not supported, so this option
is not needed.


Details

When accessing a WebDAV server, the file is pulled from the WebDAV
server to your local disk storage for processing. When you complete the
updating, the file is pushed back to the WebDAV server for storage. The
file is removed from the local disk storage when it is pushed back.

Example

The following example associates the libref davdata with the WebDAV
directory /users/mydir/datadir on the WebDAV server www.webserver.com:

libname davdata v9 "https://www.webserver.com/users/mydir/datadir"
webdav user="mydir" pw="12345";


A fix for SAS 9.1.3 (9.1 TS1M3) for this issue is available at:

http://www.sas.com/techsup/download/hotfix/e9_sbcs_prod_list.html#013763

For customers running SAS with Asian Language Support (DBCS), this
fix should be downloaded from:

http://www.sas.com/techsup/download/hotfix/e9_dbcs_prod_list.html#013763

Monday, May 28, 2007

FTP With PHP

Just some rough scripts showing uses for PHPs FTP library.

One of the biggest ways I have used FTP is a cheat for those servers which will not give Apache permission to create local directories. Assuming that the FTP module is install, just FTP to yourself and create the directories the hard way. Not ideal by any stretch of the imagination, but it is a work around.

The below script is a cheat that I used at an old employers company. The issue was we needed dynamic creation of directories on a webserver which we had no permissions to other than via FTP ( and the PHP FTP module was not installed either ). So, I rigged a scheduled script which ran locally to check which directories needed to be created, which in turn called a script on a remote server which would FTP the directories back.

This is by no means the best way of doing things, but, sometimes you have to be a bit messy. And, incase you are wondering, the bigger version of these scripts are still in use today!!

We check for the existence of the directory prior to calling the creation script as FTP does use a lot of resource, the less work we do the better.

This is the local file ( if needed )

// This is the directory we want to create

$dir = “newdir”;

// This is the URL on the remote server of the
// script that is going to FTP back to us.

$url = “http://ftpenabled.server.com/ftp.php?dir=$dir”;

// This just checks if the directory already exists ….
// if it doesn’t call our remote script to FTP back to
// us and create it.

// Also check “allow_url_fopen” is enabled.

if(!file_exists(“/var/www/html/testdomain/public_html/$dir”))
{

// Now open the URL. The remote script can pass data back to
// us in $var

$fh = fopen($url,“r”);
while(!
feof($fh))
{

// Just to stop it timing out … FTP isn’t fast!

set_time_limit(10);
$var = fgets($fh, 1024);
print(
$var);
}
fclose($fh);
}
}
?>

This is the remote file http://ftpenabled.server.com/ftp.php

// If the server where this file is located
// has the FTP portion of PHP enabled then
// you call just run this function locally.

// Dir is the directory to create

$dir = $HTTP_GET_VARS[“dir”];

// These 3 variable you could pass to the
// script within the URL if you wanted -
// bit insecure though

$ftp_ip = “ftp.this.com”;
$ftp_username = “username”;
$ftp_password = “password”;

if($ftp=ftp_connect($ftp_ip))
{
if(
ftp_login($ftp,$ftp_username,$ftp_password))
{

// Set to PASV mode

ftp_pasv( $ftp, 1);

// In this example set the current directory to
// public_html

ftp_chdir($ftp,“/public_html/”);

// If we cannot set our directory to the new one
// then we create it

if(!ftp_chdir($ftp,$dir))
{
ftp_mkdir($ftp,$dir);
echo(
“Directory $dir created ok”);
}
}
ftp_close($ftp);
}

?>

Tuesday, May 15, 2007

Coloring Your Scrollbars with CSS

It’s true! You really can color your scrollbars and have a change of scenery from the basic gray or other browser default. It just takes a few snippets of CSS markup, which you’ll learn how to do in this tutorial.

Note: To see the results, you’ll need to view your page with Internet Explorer 5.5+, too. (Most other browsers use the browser default and do NOT support scrollbar colors - see the Further Information section below.)

You can also color the scrollbar of a form’s textarea field, as shown below. I used a variety of bright colors to show some of the scrollbar property attribute colors that are possible to change.

If you don’t see a colorful scrollbar above, here are some screen shots. (A separate popup window will open.)

Editor note Feburary 2006: Note that not everyone considers colored scrollbars a good thing, and you should also be sure the colors you choose aren’t a problem for those with color deficiencies or vision impairments. Before altering scrollbar colors, make sure they won’t be a problem to use by anyone and that they will be well received by your visitors! See the following:

This tutorial is geared for those with a knowledge of basic HTML markup, including forms, and a beginning to intermediate level knowledge of CSS.

Friday, April 13, 2007

What is a Domain Name?

A domain name is basically the name of your website such as google.com or cbc.ca or computercops.biz. These are all domain names which are registered by official registrars with various domain name authorities. These authorities make up part of an international database or “domain name system” overseen by the Internet Corporation for Assigned Names and Numbers (ICANN).

The domain name that you select basically consists of two parts:

  • Second level domain - The actual name of your website, e.g., ironspider
  • Top level domain (TLD) - The 2 or 3 letter suffix at the end of the domain name, e.g. .com, .org, .ca, .uk, etcetera.

Choosing the Right Domain Name

Second level domain names may not be repeated within each top-level domain but may be repeated across top level domains. For example, as of this writing, there exists ironspider.ca, ironspider.net and ironspider.com. But within the .ca top level domain, there is only one ironspider (yours truly). If you find that the domain name you want is already taken then try changing the top-level domain before changing the second level domain.

As for which second level domain name to choose (the actual name of your website), you could try to work in some keywords related to your niche to help gain higher rankings in seach engines. However be advised that there is much disagreement among the experts as to whether this is actually works.

For example, you may want to choose the domain name blue-widgets.com if your company sells ‘blue widgets’. Personally, I think this has little effect on your rankings and you can prove this by just doing a search in Google for keywords related to your niche and see how many of the top ten results have those keywords in their domain names.

Also I’m a firm believer in using your domain name for branding purposes. I think it’s much better to create highly memorable domain name than a blasé domain name that simply contains keywords related to your business.

For example, which name are you more likely to remember?

purplemonkeyplaytime.com OR best-toys-for-tots.com

Right?

To register a domain name, it is simply a matter of performing a domain name ‘look up’ to find a name that isn’t already taken (since all domain names must be unique), then finding an official registrar, laying the cash on the barrel and presto, you are the owner of an internet domain name.

Choosing the Right Registrar

The cheapest domain name registration (from a reputable provider) is currently hovering around $8 - $9 per year.

Here’s some info on what to look for in a domain name registrar:

  • ICANN-accredited domain name registrar — You can change web hosts from one month to the next but when it comes to your domain name, you’re pretty much stuck with it for an entire year. This is something you don’t want to mess around with and you definitely want to avoid petty hassles such as who actually owns your domain name once it’s registered. Using a properly accredited registrar will ensure that you are doing business with a reputable company that has met a required set of standards as set out by the Internet Corporation for Assigned Names and Numbers (ICANN) which is the official body that oversees domain name registration.
  • Easy domain name management interface — You won’t be accessing this very often so you’ll want to have your domain name managed by a registrar that provides an easy-to-use domain name management interface that speaks plain English. Some of the cheapest domain name registrars won’t put much thought into this which will ultimately have you wasting a lot of time trying to plow past a bunch of technobabble like ‘CNAME’ and ‘MX Record’ when all you want to do is simply update your contact information. Typically you’ll be accessing your domain name management screens to renew your domain name, update contact information or change your nameservers (switch web hosts).
  • 24/7 technical support — This is self-explanatory. Like web hosting, domain name registration is now a highly competitive business. If your registrar can’t offer you 24/7 tech support then they simply aren’t in the game.

Using Subdomains

Third level domain names, a.k.a., host names or subdomains, are often used by free web hosts to create multiple free hosting accounts to allow users to have a little piece of the web without actually having to register a ‘real’ (second level) domain name. Subdomains usually look like this:

username.freewebhostname.com

If you sign up with a free web host and you don’t have your own domain name then they will assign you a subdomain name of this sort. As mentioned earlier, in this situation, it will be painfully obvious that you’re using a free web hosting service. If you’re serious about your website (and you want others to thinks so too) then you should definitely spend the few bucks a year it takes to have your own domain name.

Wildcard DNS and Sub Domains

What follows is what I consider to be best practice for my personal sites and a guide for those who wish to do the same. Months ago I dropped the www. prefix from my domain in part because I think it’s redundant and also because I wanted to experiment with how Google treated valid HTTP redirect codes. The experiment has been a great success. Google seems to fully respect 301 Permanent Redirects and the change has taken my previously split PageRank has been combined and now I am at 7. There are other factors that have contributed to this, of course, and people still continue to link to my site and posts with a www. (or worse) in front of it, but overall it just feels so much cleaner to have one URI for one resource, all the time. I’m sure that’s the wrong way to say that, but the feeling is there nonetheless.

Now for the meat. What’s a good way to do this? Let’s look at our goals:

  • No links should break.
  • Visitors should be redirected using a permanent redirect, HTTP code 301, meaning that the address bar should update and intelligent user agents may change a stored URI
  • It should be transparent to the user.
  • It should also work for mistyped “sub domains” such as ww. or wwww. (I still get hits from Carrie’s bad link)

So we need a little magic in DNS and in our web server. In my case these are Bind and Apache. I am writing about this because at some point the code I put in to catch any subdomain stopped working and while I reimplemented it I decided to write about what I was doing. This method also works with virtual hosts on shared IPs where my previous method did not.

In Bind you need to set up a wildcard entry to catch anything that a misguided user or bad typist might enter in front of your domain name. Just like when searching or using regular expressions you use an asterisk (or splat) to match any number of any characters the same thing applies in Bind. So at the end of my zone DB file (/var/named/photomatt.net.db) I added the following line:

*.photomatt.net. 14400 IN A 64.246.62.114

Note the period after my domain. The IP is my shared IP address. That’s all you need, now restart bind. (For me /etc/init.d/named restart.)

Now you need to set up Apache to respond to requests on any hostname under photomatt.net. Before I just used the convinence of having a dedicated IP for this site and having the redirect VirtualHost entry occur first in my httpd.conf file. That works, but I have a better solution now. So we want to tell Apache to respond to any request on any subdomain (that does not already have an existing subdomain entry) and redirect it to photomatt.net. Here’s what I have:


DocumentRoot /home/photomat/public_html
BytesLog domlogs/photomatt.net-bytes_log
User photomat
Group photomat
ServerAlias *.photomatt.net
ServerName www.photomatt.net
CustomLog domlogs/photomatt.net combined
RedirectMatch 301 (.*) http://photomatt.net$1

The two magic lines are the ServerAlias directive which is self explanitory and the RedirectMatch line which redirects all requests to photomatt.net in a permanent manner.

There is a catch though. The redirecting VirtualHost entry must come after any valid subdomain VirtualHost entries you may have, for example I have one for cvs.photomatt.net and I had to move that entry up in the httpd.conf because Apache just moves down that file and uses the first one it comes to that matches, so the wildcard should be last.

Simple Optimization for PHP and MySQL

Here is a list of a few very simple tips for optimizing your php/mysql applications. Keep these in mind while developing.
MySQL

  • MySQL is interpreted from right to left so you should put the most significant limiters as far to the right as possible.
  • Only select fields you need, instead of selecting * (everything).
  • Don’t put things that changes very rarely in the database, instead put it in a global array in some include file.
  • Use indexes on the columns in the WHERE clause and on the columns you want to ORDER BY.
  • Indexes are great if you search the table alot, but it slows down insertion.
  • Use the EXPLAIN command to analyze your indexes.
  • If you only want one line as a result from the database you should always use LIMIT 1. This way mysql stops searching when it finds the first line instead of continuing through the whole database, only to find that there weren’t any more lines that matched the query.
  • If you use $line = mysql_fetch_array($result) you’ll get two ways of accessing the columns, $line[0] and $line[’columnname’]. If you only use the $line[’columnname’] you should use $line = mysql_fetch_assoc($result) instead, then there will not be any $line[int index] array.
  • Sometimes mysql_free_result() end up wasting more memory than it saves. Check the difference with memory_get_usage().
  • Don’t ask the database for the same stuff over and over again, save the result.
  • Use NOT NULL as default value as much as you can, it speeds up execution and saves one bit.
  • Use datatypes that fits your data, not too large. For example, INT can hold values up to 4294967295 unsigned, which is often unnecessarily big. Use MEDIUMINT or SMALLINT where applicable.
  • Make use of the default values, only insert values that differs from the default values to speed up the insertion.

PHP:

  • Many code blocks might slow down the interpretation a little bit.
      ...
    ...
    ...
    ?>

    is faster than



  • Don’t concatenate when you don’t need to.
    "SELECT id FROM tabell WHERE id = $_SESSION[id] LIMIT 1"

    is faster than:

    "SELECT id FROM tabell WHERE id = ".$_SESSION['id']." LIMIT 1"
  • Surrounding your string by ‘ instead of ” will make things interpret a little faster since php looks for variables inside “…” but not inside ‘…’. Of course you can only do this when you don’t need to have variables in the string.
  • The previous item makes it all boil down to
    'SELECT id FROM tabell WHERE id =
    '.$_SESSION['id'].' LIMIT 1'

    as the fastest way of concatenating querys.

  • When echoing strings it’s faster to separate them by comma instead of dot.
    echo "echoing ",$variable," something";

    Note: This only works with echo, which is a function that can take several strings as arguments.

  • echo is faster than print.
  • Set the maxvalue for your for-loops before and not in the loop.
    $maxvalue = 100/10;
    for($i=0; $i<$maxvalue; $i++){
    // Some code
    }

    is faster than:

    for($i=0; $i<100/10; $i++){
    // Some code
    }

    because the value is calculated once instead of ten times.

  • Unset your variables to free memory, especially large arrays.

If possible it’s of course always better to generate static html pages every time something is updated or as often as an update might be relevant instead of querying the database every time.

Further reading:

10 things if you didn’t know about PHP

PHP is simultaneously the most infuriating and joyful languages I’ve ever worked with. I say “infuriating” primarily because the function names are so inconsistant. Despite the fact that I use it almost everyday, I still have to think to myself “Is it str_pos or strpos? str_split or strsplit?” On the other hand, occasionally I’ll stumble across a gem that perfectly solves the problem at hand with a single line of code.

Here’s a short list of cool features that might have slipped under your radar as well:

  1. Use ip2long() and long2ip() to store IP addresses as integers instead of strings in a database. This will reduce the storage space by almost a factor of four (15 bytes for char(15) vs. 4 bytes for the integer), make it easier to calculate whether a certain address falls within a range, and speed-up searches and sorts (sometimes by quite a bit).
  2. Partially validate email addresses by checking that the domain name exists with checkdnsrr(). This built-in function checks to ensure that a specified domain name resolves to an IP address. A simple user-defined function that builds on checkdnsrr() to partially valid email addresses can be found in the user comments section in the PHP docs. This is handy for catching those occasional folks who think their email address is ‘joeuser@wwwphp.net’ instead of ‘joeuser@php.net’.
  3. If you’re using PHP 5 with MySQL 4.1 or above, consider ditching the mysql_* functions for the improved mysqli_* functions. One nice feature is that you can use prepared statements, which may speed up queries if you maintain a database-intensive website. Some benchmarks.
  4. Learn to love the ternary operator.
  5. If you get the feeling that you might be reinventing the wheel during a project, check PEAR before you write another line. PEAR is a great resource that many PHP developers are aware of, yet many more are not. It’s an online repository containing over 400 reusable snippets that can be dropped right into your PHP application. Unless your project is trully unique, you ought to be able to find a PEAR package that saves at least a little time. (Also see PECL)
  6. Automatically print a nicely formatted copy of a page’s source code with highlight_file().This function is handy for when you need to ask for some assistance with a script in a messageboard, IRC, etc. Obviously, some care must be taken not to accidently show your source when it contains DB connection information, passwords, etc.
  7. Prevent potentially sensitive error messages from being shown to users with the error_reporting(0) function. Ideally error reporting should be completely disabled on a production server from within php.ini. However if you’re on a shared webhost and you aren’t given your own php.ini, then your best bet is to add error_reporting(0); as the first line in each of your scripts (or use it with require_once().) This will prevent potentially sensitive SQL queries and path names from being displayed if things go awry.
  8. Use gzcompress() and gzuncompress() to transparently compress/decompress large strings before storing them in a database. These built-in functions use the gzip algorithm and can compress plaintext up to 90%. I use these functions almost everytime I read/write to a BLOB field within PHP. The only exception is when I need full text indexing capabilities.
  9. Return multiple values from a function with “by reference” parameters. Like the ternary operator, most PHP developers who come from a more formalized programming background already know this one. However, those who’s background is more HTML than Pascal, probably have wondered at one time “how do I get multiple values back from a function I wrote, even though I can only use one return value?” The answer is that you precede a variable with “&” and use it “by reference” instead of “by value”.
  10. Fully understand “magic quotes” and the dangers of SQL injection. I’m hoping that most developers reading this are already familiar with SQL injection. However, I list it here because it’s absolutely critical to understand. If you’ve never heard the term before, spend the entire rest of the day googling and reading.

Cheat Sheet Roundup - Over 30 Cheatsheets for developers

Lets face it, unless you have a photographic memory, no developer can remember all the different functions, options, tags, etc. that exist. Documentation can be cumbersome at times, thats why I like cheat sheets. They are quick references that feature the most commonly forgotten things on a specific topic. You can print them out and hang them on your wall, or just keep them handy in your bookmarks for quick reference.

I have rounded up over 30 cheatsheets that developers might find useful.

Web Development Cheat Sheets

Databases / SQL Cheat Sheets

Language Cheat Sheets

Version Control Cheat Sheets

Other

Commercially Printed CheatSheets

Am I missing any good ones? Feel free to post any others in the comments.

Updates:

Related Entries

PNG OVERLAY : USEFUL CSS TECHNIQUE FOR MASKING IMAGE ON YOUR WEBSITE

When designing a webpage webdesigner have some idea, something to beautify an image shape so it’s not common and classic style with just box style. But other reason that must be a consideration is if that image is part of dynamic content, that mean every time post a news/dynamic content we must editing the image shape, it’s very wasting time. In this case, I have some problem too :) , so I browse on the net to find solution, and lucky me I found some interesting solution for this :) , thanks to Nathan Smith for the “PNG Overlay” solution.

Related article about PNG Overlay and Transparency :

PNG overlay using one single Image element
How to create simplemasks

Anton Subagja