Deprecated: Assigning the return value of new by reference is deprecated in /home/tryangle/public_html/blog/wp-includes/cache.php on line 36

Deprecated: Assigning the return value of new by reference is deprecated in /home/tryangle/public_html/blog/wp-includes/query.php on line 21

Deprecated: Assigning the return value of new by reference is deprecated in /home/tryangle/public_html/blog/wp-includes/theme.php on line 507

Deprecated: Assigning the return value of new by reference is deprecated in /home/tryangle/public_html/blog/wp-content/plugins/codesnippet/codesnippet.php on line 248
Tryangled Dev » 2008 » February

Archive for February, 2008

How to add Mime-Types using .htaccess

Friday, February 29th, 2008

In case your web hosting account is not configured to server certain mime types with the proper content type. You can change this using .htaccess file.

For example if you need to configure your server to display ASX files:

AddType video/x-ms-asf asf asx

For windows media audio WMA

AddType audio/x-ms-wma .wma

There is one more useful feature of the AddType directive. Most of you most probably know that Internet Explorer opens MS Word, Excell, PDF and some other files inside a browser window. To force the browser to download the file you can use AddType to change the document type:

AddType application/octet-stream .doc .xls .pdf

Posted by Mahesh ( Tryangled )

The fastest way to see how many people are online at your site

Friday, February 29th, 2008

Php in most cases uses files to store session data. In general those files are stored in the /tmp directory (for unix based servers) and this is defined in the session.save_path php.ini directive.

To do this we will first need to create a directory which will hold the files. The important thing on this is to know the directory path in the filesystem. So if the directory is under our home dir, then we will need to know the path /usr/home/sessions This directory should have write permissions, so to be sure you can chmod it to 755.

Now we need to change some php directives in order to make this work. If your host provides you with a php.ini file for your site, then you should open it and edit it as follows:

Code:
session.save_handler = “files”
session.save_path = “/usr/home/sessions/”
session.auto_start = 1

If php.ini is not an option, then you can create (or edit) an .htaccess file in your web root (document root) and add the following:

Code:
php_value session.save_handler files
php_value session.save_path /usr/home/sessions/
php_value session.auto_start 1

Finally there is a third way to achieve this. Open a php file that is included in your whole web site, and add these lines in the beginning :

Code:
<?php
ini_set(’session.save_handler’, ‘files’);
ini_set(’session.save_path’, ‘/usr/home/sessions/’);
ini_set(’session.auto_start’, 1);
?>

Now that your site has each own session directory, you can easily get the number of online visitors by using something like this :

Code:
<?php
echo ((int)count(explode(”\n”,shell_exec(’ls /usr/home/sessions’)))) . ‘ users online’;
?>

Posted by Mahesh ( Tryangled )

Making Clean URLs

Friday, February 29th, 2008

First I think it’s best if I make it clear what a messy URL looks like:

http://www.tryangled.com/index.php?page=news&id=01

And here is what a clean URL could look like:

http://www.tryangled.com/news/first+blog+post/
http://www.tryangled.com/tutorial:easy+php+tutorial

Here are a few reasons to use clean URLs:

1. You can change where the page is but not lose any bookmarks (Thanks, to Mod_rewrite),
2. They are easy to remember,
3. Search engine’s prefer it (Did you know that yahoo, msn and loads of other search engines (except google, thankfully) just ignore a page with a “?” in the URL),
4. And of course they look a lot nicer.

First you open your code favourite editor and save a blank file called “.htaccess” and then add the line:

RewriteEngine On

This tells apache to turn Mod_rewrite on. Now we need to create our RewriteRule(s). My first examples rule will look like this

RewriteRule ^([a-zA-Z0-9]+)/([a-zA-Z0-9]+)$ index.php?page=$1&id=$2

* First we state that we’re creating a rewrite by starting the line with: “RewriteRule”,
* Then we use a “^” to state that we’re creating our rule,
* Then we use Regular expressions to state what characters are allowed in the variable which we express in the next part,
* Then we use a $ sign to state the end of the clean URL ready to convert it to the messy URL to be read by the server,
* We tell the server what the URL should read and use $1, $2, $3 etc. To display the variables.

You might also choose to add this line too:

RewriteRule ^([a-zA-Z0-9]+)/([a-zA-Z0-9]+)/$ index.php?page=$1&id=$2

Something you may want to consider is when you have spaces in the variables in the clean URL. By modifying the regular expression in the URL to:

([a-zA-Z0-9+]+)

You enable there to be “+”’s in the clean URL, then when you get the url try this php code to turn them back into spaces:

<?php
$page = $_GET[’page’];
$page = str_replace(”+”, ” “, $page);
echo $page;
?>

Posted by Mahesh ( Tryangled )

How to Create Your Own Exception Classes in PHP

Friday, February 29th, 2008

exceptions to create your own exception handler that will do your bidding when errors occur in third-party libraries:
class CustomException extends Exception
{
public function __construct($message, $code = 0)
{

parent::__construct($message, $code);

$msg .= __CLASS__ . “: [{$this->code}]: {$this->message}\n”;
$msg .= $this->getTraceAsString() . “\n”;
error_log($msg);
}

// overload the __toString() method to suppress any “normal” output
public function __toString() {
return $this->printMessage();
}

// map error codes to output messages or templates
public function printMessage() {

$usermsg = ”;
$code = $this->getCode();

switch ($code) {
case SOME_DEFINED_ERROR_CODE:
$usermsg = ‘Ooops! Sorry about that.’;
break;
case OTHER_DEFINED_ERROR_CODE:
$usermsg = “Drat!”;
break;
default:
$usermsg = file_get_contents(’/templates/general_error.html’);
break;
}
return $usermsg;
}

public static function exception_handler($exception) {
throw new CustomException($exception);
}

}

set_exception_handler(’CustomException’, ‘exception_handler’);

try {
$obj = new CoolThirdPartyPackage();
} catch (CustomException $e) {
echo $e;
}

Posted by Mahesh ( Tryangled )

How to Use PHP To Dynamically Resize an Image

Friday, February 29th, 2008

We’re going to make use of the PHP GD library to manipulate the image, and a $_GET parameter to tell it which image to re-size.

Let’s walk through using the GD library to re-size an image. Then we’ll see how to include that in your HTML to actually do the resizing for you.

First, we need to open up the original file and get it’s size and type characteristics.

$src_img = imagecreatefrompng(’image.png’);
$srcsize = getimagesize(’image.png’);

imagecreatfrompng() creates an image object and stores it in $src_image. If the file was a different type we could replace “png” with “jpeg” or “gif.” getimagesize() stores an array in $srcsize that contains the width of the image ($srcsize[0]), the height of the image ($srcsize[1]), and the filetype of the image ($srcsize[2]).

Now we need to create new dimensions for the new image and actually create an image. We’ll resize it to 200 pixels wide - and then adjust the height to maintain the ratio.

$dest_x = 200;
$dest_y = (200 / $srcsize[0]) * $srcsize[1];
$dst_img = imagecreatetruecolor($dest_x, $dest_y);

imagecreatetruecolor() creates a new image object for us with the given dimensions - which we will soon fill in with our resized image.

imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0,
$dest_x, $dest_y, $srcsize[0], $srcsize[1]);

header(”content-type: image/png”);
imagepng($dst_img);

imagecopyresampled() copies an image ($dst_img) into a new image ($src_img) with a set of given attributes (including our sizes). The “Header” line tells the browser that this is an image - so that it’s not displayed as a bunch of gibberish. Finally, the imagepng() function actually displays the image.

Now, we need to clean up and destroy the image objects. Otherwise, we could end up sapping a lot of memory from the server.

imagedestroy($src_img);
imagedestroy($dst_img);

Displaying the Script in HTML

If you load the script directly, you should simply see the image. It creates an image resource and displays it in the browser - as if “resize-image.php” was really “image.png.”

Therefore all we need to do to include this new image in an HTML page is use the php script as the src attribute of our <img> tag. Like so…

<img src=’resize-image.php’ />

Posted by Mahesh ( Tryangled )

How to prevent or allow directory listing?

Friday, February 29th, 2008

Having a listable directories on your site sometimes is useful. However, some times it can be considered a security issue. No, matter which option you prefer you can control this behavior of your site using 1 simple line:

Options +Indexes

The above line enables Directory listing.

Options –Indexes

Posted By:MaheshVembu

The above disables directory listing for your web site.

The .htaccess file gives more then simply enabling and disabling of a directory listing.
With .htaccess file you can control which files to be ignored when creating a directory list.
For example:

IndexIgnore *.gif *.zip *.txt

Will make the apache server to skip all gif, zip and txt files from the directory list.
Convenient, isn’t it.

IndexIngnore *

Posted by Mahesh ( Tryangled )

Enable CGI, SSI with .htaccess

Friday, February 29th, 2008

As .htaccess is a powerful tool. It gives you option to change the way the webserver serves your files. On most web hosting servers you can use SSI (Server Side Includes) in shtml, or shtm files.

However, you need to use SSI in your .html and htm files. There is an easy solution for this.
Just add the following line in your .htaccess file:

AddHandler server-parsed .html .htm

This line will tell the server to parse your .htm file as SSI and execute any SSI directives you have there.

You can also use .htaccess to enable CGI scripts execution as well as change the default extension for such files as well.

For Perl/CGI scripts you will need:

AddHandler cgi-script .cgi .pl

To make PHP files to be parsed as PHP when PHP is running as module

AddType application/x-httpd-php .html .htm

To make PHP files to be parsed as PHP when PHP is running as CGI (suexec, etc)

AddHandler application/x-httpd-php .html .htm

Posted by Mahesh ( Tryangled )

Make PHP to work in your HTML files with .htacess

Friday, February 29th, 2008

By default most web servers across the internet are configured to treat as PHP files only files that end with .php. In case you need to have your HTML files parsed as PHP (e.g .html) or even if you want to take it further and make your PHP files look like ASP, you can do the following:

For web servers using PHP as apache module:

AddType application/x-httpd-php .html .htm

For web servers running PHP as CGI:

AddHandler application/x-httpd-php .html .htm

In case you wish to do the ASP mimick:

For PHP as module:

AddType application/x-httpd-php .asp

OR

For PHP as CGI:

AddHandler application/x-httpd-php .asp

Posted by Mahesh ( Tryangled )

Redirect URLs using .htaccess

Friday, February 29th, 2008

The feature is very useful if you have recently redesigned your site but you wish to keep the old addresses working for various reasons (you have links to these pages from other sites, some users may have the old pages bookmarked, etc).
The Apache web server provides several way for setting up redirects.

The most simple one is using the “Redirect” directive:

Redirect /folder http://www.example.com/newfolder

Another useful directive is the RedirectMatch. With it you can use regular expressions in the redirect condition. For example

RedirectMatch “\.html$” http://www.example.com/index.php

This will redirect all requests to files that end with .html to the index.php file.

Posted by Mahesh ( Tryangled )

Using .htaccess to block referrer spam

Friday, February 29th, 2008

To block these spam referrers you need the following lines in your .htaccess file:
# set the spam_ref variable

SetEnvIfNoCase Referer “^http://(www.)?some-spammer.com” spam_ref=1

SetEnvIfNoCase Referer “^http://(www.)?other-spammer.com” spam_ref=1

SetEnvIfNoCase Referer “^casino-poker” spam_ref=1

# block all referres that have spam_ref set
<FilesMatch “(.*)”>
Order Allow,Deny
Allow from all
Deny from env=spam_ref
</FilesMatch>

The first lines “setenvifnocase” assign a span_ref environment variable. Then we deny all access to such referrers in the FilesMatch clause.

You can also use wildcards with the above .htaccess directives to match a variety of hosts. For example, you can use

SetEnvIfNoCase Referer “*some_word*” spam_ref=1

to match all referrers that contain the word ’some_word’.

Posted by Mahesh ( Tryangled )