Archive for the ‘PHP Programming’ Category

subquery - join using in mysql

Wednesday, April 23rd, 2008

SELECT sports_name
FROM sports
WHERE id
IN (

SELECT sports_id
FROM sports_key
WHERE user_id =1
)

In this query we have selected field(sports_id) from the table(sports_key) and also we checed the field(user_id) This process has been done in subquery. Then finally, we have selected field (sports_name) from the table (sports_key) according to receiving field (id) values from subquery.

Posted by

window open not working in Internet Explorer (javascript)

Wednesday, April 23rd, 2008

 <a href=”contactus.php?act=contactus” onclick=”javascript:window.open(’contactus.php?act=contactus’ ,’contactus‘,’width=564PX,height=600PX,scrollbars=yes,top=0,left=0′); return false;”>
Contact Us</a>

in the above code when the highlighted window name is given without space..

But by mistake if u give a space in between the name like “contact us” then this will not work in Internet Explorer  and the same will work in Mozilla Firefox

Posted by Suresh B

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 )

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 )

How to block users from accessing your site based on their IP address

Friday, February 29th, 2008

Blocking users by IP address is pretty simple with .htaccess.
So here it is the example:

Order allow, deny
Deny from 192.168.0.10
Deny from 212.155.
Deny from 1.2.3.4 5.6.7.8 127.0.0.1
Allow from all

The default Apache order is deny,allow. So you can skip the first line in your .htaccess file if you do not need to change the order in which the Deny and Allow rules are being evaluated by the web server.
So to keep the .htaccess simple you can just use:

Deny from 192.168.0.10
Deny from 212.155.

Basically you can use such rules in your .htaccess file to block a particular user, or a network from accessing your site.
You can put several IP address in a Deny or Allow rule. For example:

Deny from 1.2.3.4 5.6.7.9

The IP addresses must be separated by a space or tab.

You can put entire networks as

Deny from 212.155.

This will block all users which IP addresses start with 212.155

Or to block all access to your site:

Deny from all

And then add another line to enable access only for yourself:

Allow from 1.2.3.4

Where “1.2.3.4” should be replaced with your computer IP address.

Posted by Mahesh ( Tryangled )

array_chunk function in PHP

Friday, February 29th, 2008

array_chunk — Split an array into chunks

Description

array array_chunk ( array input, int size [, bool preserve_keys] )

Chunks an array into size large chunks. The last chunk may contain less than size elements.

Parameters

input

The array to work on
size

The size of each chunk
preserve_keys

When set to TRUE keys will be preserved. Default is FALSE which will reindex the chunk numerically

Return Values

Returns a multidimensional numerically indexed array, starting with zero, with each dimension containing size elements.

Errors/Exceptions

If size is less than 1 E_WARNING will be thrown and NULL returned.

Examples

<?php
$input_array = array(’a', ‘b’, ‘c’, ‘d’, ‘e’);
print_r(array_chunk($input_array, 2));
print_r(array_chunk($input_array, 2, true));
?>
The above example will output:

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
            [1] => d
        )

    [2] => Array
        (
            [0] => e
        )

)
Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [2] => c
            [3] => d
        )

    [2] => Array
        (
            [4] => e
        )

)
Posted by Mahesh ( Tryangled )

Using remote files in PHP

Friday, February 29th, 2008

allow_url_fopen is enabled in php.ini, you can use HTTP and FTP URLs with most of the functions that take a filename as a parameter. In addition, URLs can be used with the include(), include_once(), require() and require_once() statements. See Appendix O for more information about the protocols supported by PHP.

For example, you can use this to open a file on a remote web server, parse the output for the data you want, and then use that data in a database query, or simply to output it in a style matching the rest of your website.

Getting the title of a remote page

<?php
$file = fopen (”http://www.example.com/”, “r”);
if (!$file) {
echo “<p>Unable to open remote file.\n”;
exit;
}
while (!feof ($file)) {
$line = fgets ($file, 1024);
/* This only works if the title and its tags are on one line */
if (eregi (”<title>(.*)</title>”, $line, $out)) {
$title = $out[1];
break;
}
}
fclose($file);
?>

Example-Storing data on a remote server

<?php
$file = fopen (”ftp://ftp.example.com/incoming/outputfile”, “w”);
if (!$file) {
echo “<p>Unable to open remote file for writing.\n”;
exit;
}
/* Write the data here. */
fwrite ($file, $_SERVER[’HTTP_USER_AGENT’] . “\n”);
fclose ($file);
?>

Posted by Mahesh ( Tryangled )