Archive for February, 2008

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 )

HTTP authentication with PHP

Friday, February 29th, 2008

The HTTP Authentication hooks in PHP are only available when it is running as an Apache module and is hence not available in the CGI version. In an Apache module PHP script, it is possible to use the header() function to send an “Authentication Required” message to the client browser causing it to pop up a Username/Password input window.

Once the user has filled in a username and a password, the URL containing the PHP script will be called again with the predefined variables PHP_AUTH_USER, PHP_AUTH_PW, and AUTH_TYPE set to the user name, password and authentication type respectively. These predefined variables are found in the $_SERVER and $HTTP_SERVER_VARS arrays. Only “Basic” authentication is supported.

<?php
if (!isset($_SERVER[’PHP_AUTH_USER’])) {
header(’WWW-Authenticate: Basic realm=”My Realm”‘);
header(’HTTP/1.0 401 Unauthorized’);
echo ‘Text to send if user hits Cancel button’;
exit;
} else {
echo “<p>Hello {$_SERVER[’PHP_AUTH_USER’]}.</p>”;
echo “<p>You entered {$_SERVER[’PHP_AUTH_PW’]} as your password.</p>”;
}
?>

HTTP Authentication example forcing a new name/password

<?php
function authenticate() {
header(’WWW-Authenticate: Basic realm=”Test Authentication System”‘);
header(’HTTP/1.0 401 Unauthorized’);
echo “You must enter a valid login ID and password to access this resource\n”;
exit;
}

if (!isset($_SERVER[’PHP_AUTH_USER’]) ||
($_POST[’SeenBefore’] == 1 && $_POST[’OldAuth’] == $_SERVER[’PHP_AUTH_USER’])) {
authenticate();
}
else {
echo “<p>Welcome: {$_SERVER[’PHP_AUTH_USER’]}<br>”;
echo “Old: {$_REQUEST[’OldAuth’]}”;
echo “<form action=’{$_SERVER[’PHP_SELF’]}’ METHOD=’POST’>\n”;
echo “<input type=’hidden’ name=’SeenBefore’ value=’1′>\n”;
echo “<input type=’hidden’ name=’OldAuth’ value=’{$_SERVER[’PHP_AUTH_USER’]}’>\n”;
echo “<input type=’submit’ value=’Re Authenticate’>\n”;
echo “</form></p>\n”;
}
?>

Posted by Mahesh ( Tryangled )

Serializing objects in PHP

Friday, February 29th, 2008

serialize() returns a string containing a byte-stream representation of any value that can be stored in PHP.
unserialize() can use this string to recreate the original variable values. Using serialize to save an object will save all variables in an object. The functions in an object will not be saved, only the name of the class.

In order to be able to unserialize() an object, the class of that object needs to be defined. That is, if you have an object $a of class A on page1.php and serialize this, you’ll get a string that refers to class A and contains all values of variabled contained in $a. If you want to be able to unserialize this on page2.php, recreating $a of class A, the definition of class A must be present in page2.php. This can be done for example by storing the class definition of class A in an include file and including this file in both page1.php and page2.php.

<?php
// classa.inc:

class A {
var $one = 1;

function show_one() {
echo $this->one;
}
}

// page1.php:

include(”classa.inc”);

$a = new A;
$s = serialize($a);
// store $s somewhere where page2.php can find it.
$fp = fopen(”store”, “w”);
fwrite($fp, $s);
fclose($fp);

// page2.php:

// this is needed for the unserialize to work properly.
include(”classa.inc”);

$s = implode(”", @file(”store”));
$a = unserialize($s);

// now use the function show_one() of the $a object.
$a->show_one();
?>

Posted by Mahesh ( Tryangled )

Constructors in PHP

Friday, February 29th, 2008

Constructors are functions in a class that are automatically called when you create a new instance of a class with new. A function becomes a constructor, when it has the same name as the class. If a class has no constructor, the constructor of the base class will be called, if it exists.

<?php
class Auto_Cart extends Cart {
function Auto_Cart() {
$this->add_item(”10″, 1);
}
}
?>

Posted by Mahesh ( Tryangled )

mailparse_msg_create function in PHP

Friday, February 29th, 2008

mailparse_msg_create — Create a mime mail resource

Description

resource mailparse_msg_create ( void )

Create a MIME mail resource.

Return Values

Returns a handle that can be used to parse a message.

Posted by Mahesh ( Tryangled )

hide and deny files in .htaccess

Friday, February 29th, 2008

.ht_anything files generally have server directives and passwords and stuff in them, most servers will have something like this in their main configuration..

Standard setting..
<Files ~ “^\.ht”>
Order allow,deny
Deny from all
Satisfy All
</Files>

which instructs the server to deny access to any file beginning with .ht, effectively protecting our .htaccess and other files. The “.” at the start prevents them being displayed in an index, and the .ht prevents them being accessed. This version..

ignore what you want
<Files ~ “^.*\.([Ll][Oo][Gg])”>
Order allow,deny
Deny from all
Satisfy All
</Files>

To tells the server to deny access to *.log files. You can insert multiple file types into each rule, separating them with a pipe “|”, and you can insert multiple blocks into your .htaccess file, too.

the whole lot
# deny all .htaccess, .DS_Store $hî†é and ._* (resource fork) files
<Files ~ “^\.([Hh][Tt]|[Dd][Ss]_[Ss]|[_])”>
Order allow,deny
Deny from all
Satisfy All
</Files>

# deny access to all .log and .comment files
<Files ~ “^.*\.([Ll][Oo][Gg]|[cC][oO][mM][mM][eE][nN][tT])”>
Order allow,deny
Deny from all
Satisfy All
</Files>

would cover all ._* resource fork files, .DS_Store files (which the Mac Finder creates all over the place) *.log files, *.comment files and of course, our .ht* files. You can add whatever file types you need to protect from direct access.

Posted by Mahesh ( Tryangled )

Error Messages in handling fileupload

Friday, February 29th, 2008

PHP returns an appropriate error code along with the file array. The error code can be found in the error segment of the file array that is created during the file upload by PHP. In other words, the error might be found in $_FILES[’userfile’][’error’].

UPLOAD_ERR_OK

Value: 0; There is no error, the file uploaded with success.

UPLOAD_ERR_INI_SIZE

Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.

UPLOAD_ERR_FORM_SIZE

Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
UPLOAD_ERR_PARTIAL
Value: 3; The uploaded file was only partially uploaded.PLOAD_ERR_NO_FILE

Value: 4; No file was uploaded.
UPLOAD_ERR_NO_TMP_DIR

Value: 6; Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.
UPLOAD_ERR_CANT_WRITE

Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0.
UPLOAD_ERR_EXTENSION

Value: 8; File upload stopped by extension. Introduced in PHP 5.2.0.

Posted by Mahesh ( Tryangled )

virtual Apache-specific function in PHP

Friday, February 29th, 2008

virtual — Perform an Apache sub-request

Description

int virtual (string filename)

virtual() is an Apache-specific function which is equivalent to <!–#include virtual…–> in mod_include. It performs an Apache sub-request. It is useful for including CGI scripts or .shtml files, or anything else that you would parse through Apache. Note that for a CGI script, the script must generate valid CGI headers. At the minimum that means it must generate a Content-type header. For PHP files, you need to use include() or require(); virtual() cannot be used to include a document which is itself a PHP file.

Posted by Mahesh ( Tryangled )