Thursday, December 24, 2009

Error Handing in PHP

Here are some of the Error Handling Techniques

It is important to configure PHP's error reporting settings depending on which phase of development the web application is currently in. Generally, the programmer wants to see all warnings and errors in the web browser during the initial phase of development, and later, once the site has launched, send error messages to a log file so that visitors do not see them.
Error Reporting for Development

During development, you want to display all errors and warnings to the browser.

// Report all PHP errors
ini_set('error_reporting', E_ALL);

// Set the display_errors directive to On
ini_set('display_errors', 1);

Error Reporting for Production

In production, you may want to lower the error reporting level and not display errors to the browser.

// Report simple running errors
ini_set('error_reporting', E_ALL ^ E_NOTICE);

// Set the display_errors directive to Off
ini_set('display_errors', 0);

// Log errors to the web server's error log
ini_set('log_errors', 1);

Logging errors

You can use the PHP function error_log() to send errors to your own log file or an e-mail address. This is particularly important since most developers on campus do not have access to the web servers logs. Used in conjunction with a custom error handler, error_log() is especially useful.

// Destinations
define("ADMIN_EMAIL", "test@test.com");
define("LOG_FILE", "/error/errors.log");

// Destination types
define("DEST_EMAIL", "1");
define("DEST_LOGFILE", "3");

/* Examples */

// Send an e-mail to the administrator
error_log("Please fix this!", DEST_EMAIL, ADMIN_EMAIL);

// Write the error to our log file
error_log("Error", DEST_LOGFILE, LOG_FILE);

Create a custom error handler

It is possible to override PHP's default mechanism for handling errors. This option gives the programmer full control over what actions to take when an error is raised. Note that since this method completely replaces PHP's native functionality, it is important to pay special care when writing a custom error handler.

// Destinations
define("ADMIN_EMAIL", "test@test.com");
define("LOG_FILE", "/error/errors.log");

// Destination types
define("DEST_EMAIL", "1");
define("DEST_LOGFILE", "3");

/**
* my_error_handler($errno, $errstr, $errfile, $errline)
*
* Author(s): thanosb, ddonahue
* Date: May 11, 2008
*
* custom error handler
*
* Parameters:
* $errno: Error level
* $errstr: Error message
* $errfile: File in which the error was raised
* $errline: Line at which the error occurred
*/

function my_error_handler($errno, $errstr, $errfile, $errline)
{
switch ($errno) {
case E_USER_ERROR:
// Send an e-mail to the administrator
error_log("Error: $errstr \n Fatal error on line $errline in file $errfile \n", DEST_EMAIL, ADMIN_EMAIL);

// Write the error to our log file
error_log("Error: $errstr \n Fatal error on line $errline in file $errfile \n", DEST_LOGFILE, LOG_FILE);
break;

case E_USER_WARNING:
// Write the error to our log file
error_log("Warning: $errstr \n in $errfile on line $errline \n", DEST_LOGFILE, LOG_FILE);
break;

case E_USER_NOTICE:
// Write the error to our log file
error_log("Notice: $errstr \n in $errfile on line $errline \n", DEST_LOGFILE, LOG_FILE);
break;

default:
// Write the error to our log file
error_log("Unknown error [#$errno]: $errstr \n in $errfile on line $errline \n", DEST_LOGFILE, LOG_FILE);
break;
}

// Don't execute PHP's internal error handler
return TRUE;
}


// Use set_error_handler() to tell PHP to use our method
$old_error_handler = set_error_handler("my_error_handler");

Error Report levels

These error report levels are the different types of error the user-defined error handler can be used for:
Value Constant Description
2 E_WARNING Non-fatal run-time errors. Execution of the script is not halted
8 E_NOTICE Run-time notices. The script found something that might be an error, but could also happen when running a script normally
256 E_USER_ERROR Fatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function trigger_error()
512 E_USER_WARNING Non-fatal user-generated warning. This is like an E_WARNING set by the programmer using the PHP function trigger_error()
1024 E_USER_NOTICE User-generated notice. This is like an E_NOTICE set by the programmer using the PHP function trigger_error()
4096 E_RECOVERABLE_ERROR Catchable fatal error. This is like an E_ERROR but can be caught by a user defined handle (see also set_error_handler())
8191 E_ALL All errors and warnings, except level E_STRICT (E_STRICT will be part of E_ALL as of PHP 6.0)

Leia Mais…

Monday, December 7, 2009

Curl Setting in PHP

Below are the steps to configure the CURL option

1. Locate XAMPP install directory
2. open php/php.ini (probably C:\xampp\php\php.ini
or C:\ program files\apachefriends\xampp\php\php.ini)
3. do a search for the word ‘curl’ and uncomment (remove the leading semicolon) that line
before removing ;extension=php_curl.dll
after removing: extension=php_curl.dll
4. save & close
5. open apache/bin/php.ini (probably C:\xampp\apache\php.ini
or C:\ program files\apachefriends\xampp\apache\php.ini)
6. search for curl, uncomment as before (step 3)
7. save & close
8. Do not forget!javascript:void(0) restart apache

Leia Mais…

Monday, October 12, 2009

Using SimpleXML To Read & Parse XML in PHP

Using PHP we can read and execute the XML files. We can use the XML files to store the information as we do with the database.

PHP provides all the methods needed for the reading, writing and executing the XML files.Before that we need to know the XML.

An XML document comprises elements, attributes, processing instructions, comments, and entities

Element: Text delimited by an opening and a closing tag. A tag is a name enclosed within angle brackets.

Attribute: A piece of qualifying information for an element. An attribute consists of a name, an equals sign, and an attribute value delimited by either single-quotes or double-quotes.

Processing instruction: The software that is reading an XML document is referred to as a processor. A processing instruction is additional information embedded in the document to inform the processor and possibly change its behaviour.

Comment: An XML comment begins with the characters: less-than, exclamation mark, minus, minus; and ends with the characters: minus, minus, greater-than. Any text within a comment is intended for a human reader and is ignored by the processor.

Entity: An entity is a compact form that represents other text. Entities are used to specify problematic characters and to include slabs of text defined elsewhere. An entity reference consists of an ampersand, a name, and a semi-colon.

A simple XML file we will

<?xml version="1.0" encoding="utf-8" ?>

<people title="students"
>

<name1> student name 1
</name1>

<name2> student name 2
</name2>

<name3> student name 3
</name3>

</people>

Steps for reading this simple XML file is:

$xml = simplexml_load_file('names.xml');
This step will load the xml files. It Interprets an XML file into an object.Returns an object of class SimpleXMLElement with properties containing the data held within the XML document. On errors, it will return FALSE.

To read the data from the simple xml file we write code as
$xml = simplexml_load_file('names.xml');
print $xml->name1;
# Seperates outputs (easier to read & understand)
print "

";
# You call an attribute just like you would with an array: $array['arrayname/number']
print $xml['title'];

outputs : student name 1 ## Title output is -- name1

For an XML with multiple Items we write code as

<?xml version="1.0" encoding="utf-8" ?>
<student title="students">

<item id="1">
<name>
<first>ram</first>
<last>test</last>
</name>
<ageᡢ</age>
</item>

<item id="2">
<name>
<first>prince</first>
<last>kumar</last>
</name>
<ageᡃ </item>

<item id="3">
<name>
<first>raju</first>
<last>ramesh</last>
</name>
<ageᡍ</age>
</item>

</student>



# Load the test.xml file
$xml = simplexml_load_file('test.xml');
# Start a foreach loop. Translation: for every in the xml file put it into the var $item.
# now the $item can display all the elements inside the
foreach($xml->item as $item) {
# These three print's will display the attribute of the (ID), display the first and last name joined together
# and then the age. The
and

are for spacing out the results
print "ID: " . $item['id'] . "
";
print "Name: " . $item->name->first . " " . $item->name->last . "
";
print "Age: " . $item->age . "

";
}

If we want to provide the conditions when executing the XML files then the code will be

# Load the test.xml file
$xml = simplexml_load_file('test.xml');
# Start a foreach loop. Translation: for every in the xml file put it into the var $item.
# now the $item can display all the elements inside the
foreach($xml->item as $item) {
$age = $item->age;
if ($age >= 10) {
if ($age <= 21) {
# These three print's will display the attribute of the (ID), display the first and last name joined together
# and then the age. The
and

are for spacing out the results
print "ID: " . $item['id'] . "
";
print "Name: " . $item->name->first . " " . $item->name->last . "
";
print "Age: " . $item->age . "

";
}
}
}

Leia Mais…

Monday, October 5, 2009

Download functionality in PHP

The common usable component in any of the website is to provide the user with the download option. when providing the download option we cannot restrict the user with one the specific type like doc or ppt or pdf... We need to provide the most convenient way to the user so that the user can easily download the files.

Below is such script where we can have the multiple options provided.

$filename is the file name which we want to download

$file_extension = strtolower(substr(strrchr($filename,"."),1));

$folderpath="foldername/".$filename;

if( $filename == "" )
{
echo "No File Found";
exit;
} elseif ( ! file_exists( $folderpath ) )
{
echo "File Not Found";
exit;
};

// If file exits then it is ready for download.

switch( $file_extension )
{
case "pdf": $ctype="application/pdf"; break;
case "exe": $ctype="application/octet-stream"; break;
case "zip": $ctype="application/zip"; break;
case "doc": $ctype="application/msword"; break;
case "xls": $ctype="application/vnd.ms-excel"; break;
case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
case "gif": $ctype="image/gif"; break;
case "png": $ctype="image/png"; break;
case "jpeg":
case "jpg": $ctype="image/jpg"; break;
default: $ctype="application/force-download";
}

// Decides the header... which type if download you are providing to the user.

header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers
header("Content-Type: $ctype");
// change, added quotes to allow spaces in filenames, by Rajkumar Singh
header("Content-Disposition: attachment; filename=\"".basename($filename)."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filename));
readfile("$folderpath");
exit();


Copy the above code if you want to download any type of the file in the given options

Leia Mais…

Friday, September 25, 2009

Php Arrays

An array is a data structure that stores one or more values in a single value.An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible

Each element in the array has its own index so that it can be easily accessed.

In PHP, there are three kind of arrays:

* Numeric array - An array with a numeric index
* Associative array - An array where each ID key is associated with a value
* Multidimensional array - An array containing one or more arrays

Numeric array
A numeric array stores each array element with a numeric index.

Example:

General:
$example=array("abc",123,"xyz","test");

In the following example we assign the index manually:
$example[0]="abc";
$example[1]=123;
$example[2]="xyz";
$example[3]="test";

we call the Indexed array as
echo $example[0] . " and " . $example[1] ;

or

foreach ($example as $i => $value) {
echo $value;
}

Associative Array
An associative array, each ID key is associated with a value.

Initializing an Associative Array

The following code creates an associative array with product names as keys and prices as values.

$prices = array( 'test1'=>100,
'test2'=>10, 'test3'=>4,'test4'=>5 );

There are different ways we can initialize the associative array

$prices = array( 'test1'=>100 );
$prices['test2'] = 10;
$prices['test3'] = 4;

Using Loops with Associative Arrays
Because the indices in this associative array are not numbers, we cannot use a simple counter in a for loop to work with the array. We can use the foreach loop or the list() and each() constructs.

The foreach loop has a slightly different structure when using associative arrays. We can use it exactly as we did in the previous example, or we can incorporate the keys as well:

foreach ($prices as $key => $value)
echo $key.'=>'.$value.'
';

The following code lists the contents of our $prices array using the each() construct:

while( $element = each( $prices ) )
{
echo $element[ 'key' ];
echo ' - ';
echo $element[ 'value' ];
echo '
';
}

Some of the Usefull methods are:

$b = array_values($a);

This will assign the the array a to the b and b will be considered as a array.

unset($arr[5]);
This will removes the particular element in the array

Leia Mais…

Friday, September 11, 2009

Why File Upload Forms are a major security threat part2

Case 4: Double extensions (part 1)

This case’s security measures, as a concept are very similar to that one used in case 3. Though instead of simply checking the extension string present in the filename, the developer is extracting the file extension by looking for the ‘.’ character in the filename, and extracting the string after the dot character.

The method used to bypass this approach is a bit more complicated, but still realistic. First, let’s have a look at how Apache handles files with multiple extensions. A quote from the Apache manual states:

“Files can have more than one extension, and the order of the extensions is normally irrelevant. For example, if the file welcome.html.fr maps onto content type text/html and language French then the file welcome.fr.html will map onto exactly the same information. If more than one extension is given which maps onto the same type of meta-information, then the one to the right will be used, except for languages and content encodings. For example, if .gif maps to the MIME-type image/gif and .html maps to the MIME-type text/html, then the file welcome.gif.html will be associated with the MIME-type text/html.”

Therefore a file named ‘filename.php.123’, will be interpreted as a PHP file and will be executed. This only works if the last extension (in our case .123), is not specified in the list of mime-types known to the web server. Web developers, usually are not aware of such ‘feature’ in Apache, which can be very dangerous for a number of reasons. Knowing this, an attacker can upload a file named shell.php.123 and bypass the file upload form protection. The script will compute the last extension (.123), and concludes that this extension is not in the list of dangerous extension. Having said that, it is impossible to predict all the possible random extensions a malicious user will use to be able to upload a file on your web server.

Case 5: Double extensions (part 2)

A better approach to securing file upload forms is the white list approach. In this case, the developer defines a list of known/accepted extensions and does not allow extensions that are not specified in the list.

However, in some cases this approach will not work as expected. When Apache is configured to execute PHP code, there are 2 ways one can specify this: to use the AddHandler directive, or to use the AddType directive. If AddHandler directive is used, all filenames containing the ‘.php’ extension (e.g. ‘.php’, ‘.php.jpg’) will be executed as a PHP script. Therefore, if your Apache configuration file contains the following line, you may be vulnerable:

AddHandler php5-script .php

An attacker can upload a file named ‘filename.php.jpg’ and bypass the protection, and will be able to execute the code.

Case 6: Checking the image header

When images only are allowed to be uploaded, developers usually validate the image header by using the PHP function called getimagesize. When called, this function will return the size of an image. If the image validation is invalid, which means that the header is incorrect, the function will return a false. Therefore a developer typically checks if the function returns a true or false, and validate the uploaded file using this information. So, if a malicious user tries to upload a simple PHP shell embedded in a jpg file, the function will return false and he won’t be allowed to upload the file. However, even this approach can be easily bypassed. If a picture is opened in an image editor, like Gimp, one can edit the image comment, where PHP code is inserted, as shown below.



The image will still have a valid header; therefore it bypasses the getimagesize PHP check. As seen in the screen shot below, the PHP code inserted in the image comments still gets executed when the image is requested from a normal web browser:



Case 7: Protecting the upload folder with .htaccess

Another popular way of securing file upload forms, is to protect the folder where the files are uploaded using .htaccess file. The idea is to restrict execution of script files in this folder. A .htaccess file typically contains the below code when used in this kind of scenario:

AddHandler cgi-script .php .php3 .php4 .phtml .pl .py .jsp .asp .htm .shtml .sh .cgi
Options –ExecCGI

The above is another type of blacklist approach, which in itself is not very secure. In the PHP manual, in the move_uploaded_file section, there is a warning which states ‘If the destination file already exists, it will be overwritten.’

Because uploaded files can and will overwrite the existing ones, a malicious user can easily replace the .htaccess file with his own modified version. This will allows him to execute specific scripts which can help him compromise the server.

Case 8: Client-side validation

Another common type of security used in file upload forms, is client-side validation of files to be uploaded. Typically, such approach is more common in ASP.NET applications, since ASP.NET offers easy to use validation controls.
A malicious user can easily bypass this type of validation. It is possible to write a short client side script that will do the validation instead of the script provided by the web application. Without using a web browser, the attacker can use an application that allows sending of HTTP POST requests to be able to upload the file.

Suggested Solution

Below is a list of best practices that should be enforced when file uploads are allowed on websites and web applications. These practices will help you securing file upload forms used in web applications;

*
Define a .htaccess file that will only allow access to files with allowed extensions.
*
Do not place the .htaccess file in the same directory where the uploaded files will be stored. It should be placed in the parent directory.
*
A typical .htaccess which allows only gif, jpg, jpeg and png files should include the following (adapt it for your own need). This will also prevent double extension attacks.


deny from all

<Files ~ "^\w+\.(gif|jpe?g|png)$">

order deny,allow

allow from all

</Files>

*
If possible, upload the files in a directory outside the server root.
*
Prevent overwriting of existing files (to prevent the .htaccess overwrite attack).
*
Create a list of accepted mime-types (map extensions from these mime types).
*
Generate a random file name and add the previously generated extension.
*
Don’t rely on client-side validation only, since it is not enough. Ideally one should have both server-side and client-side validation implemented.

Leia Mais…

Thursday, September 10, 2009

Why File Upload Forms are a major security threat

To allow an end user to upload files to your website, is like opening another door for a malicious user to compromise your server. Even though, in today’s modern internet web applications, it is a common requirement, because it helps in increasing your business efficiency. File uploads are allowed in social network web applications, such as Facebook and Twitter. They are also allowed in blogs, forums, e-banking sites, YouTube and also in corporate support portals, to give the opportunity to the end user to efficiently share files with corporate employees.

Users are allowed to upload images, videos, avatars and many other types of files.
The more functionality provided to the end user, the greater is the risk of having a vulnerable web application and the chance that such functionality will be abused from malicious users, to gain access to a specific website, or to compromise a server is very high.

While testing several web applications, we noticed that a good number of well known web applications, do not have secure file upload forms. Some of these vulnerabilities were easily exploited, and we could gain access to the file system of the server hosting these web applications. In this whitepaper, we present you with 8 common ways we encountered of securing file upload forms. We also show how a malicious user, can easily bypass such security measures.

Below are the sample cases:

Case 1: Simple file upload form with no validation

<form enctype="multipart/form-data" action="uploader.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="uploadedfile" type="file" />
<input type="submit" value="Upload File" />
</form>

we use php code for saving the uploaded file is
* $_FILES[‘uploadedfile’][‘name’]: The original name of the file on the client machine
* $_FILES[‘uploadedfile’][‘type’]: The mime type of the file
* $_FILES[‘uploadedfile’][‘size’]: The size of the file in bytes
* $_FILES[‘uploadedfile’][‘tmp_name’]: The temporary filename in which the uploaded file was stored on the server.

In this simple example, there are no restrictions about the type of files allowed for upload and therefore an attacker can upload a PHP or .NET file with malicious code that can lead to a server compromise.

This might look like a naïve example, but we did encounter such code in a number of web applications.

Case 2: Mime Type validation

Another common mistake web developers do when securing file upload forms, is to only check for mime type returned from PHP. When a file is uploaded to the server, PHP will set the variable $_FILES[‘uploadedfile’][‘type’] to the mime-type provided by the web browser the client is using. However, a file upload form validation cannot depend on this value only. A malicious user can easily upload files using a script or some other automated application that allows sending of HTTP POST requests, which allow him to send a fake mime-type.

Case 3: Block dangerous extensions

In other cases, we encountered file upload forms using a blacklist approach, as a security measure. A list of dangerous extensions is compiled from the developer, and the access is denied if the extension of the file being uploaded is on the compiled list.

One main disadvantage of using black listing of file extensions, is that it is almost impossible to compile a list that includes all possible extensions that an attacker can use. E.g. If the code is running in a hosted environment, usually such environments allow a large number of scripting languages, such as Perl, Python, Ruby etc, and the list can be endless.

A malicious user can easily bypass such check by uploading a file called “.htaccess”, which contains a line of code similar to the below:

AddType application/x-httpd-php .jpg

The above line of code, instructs Apache web server to execute jpg images as if they were PHP scripts. The attacker can now upload a file with a jpg extension, which contains PHP code. As seen in the screen shot below, requesting a jpg file which includes the PHP command phpinfo() from a web browser, it is still executed from the web server:



Source taken from http://www.acunetix.com

Leia Mais…

Tuesday, September 8, 2009

New features in PHP 5.3 & Improvements in Object oriented concepts

Late static binding

One of the more annoying things about PHP before V5.3 is how static methods and members are dealt with. Up until now, static references, such as those made with self or __CLASS__, are resolved in the class scope in which the function was defined. The problem is that the reference would be incorrect if the class was extended and the call was made from the new child class. Late static binding has been added in PHP V5.3 to alleviate this problem. To better illustrate, let's create a class with a static method below.

Class Foo with static method test()


class Foo
{
protected static $name = 'Foo';

public static function test()
{
return self::$name;
}
}


Let's extend this class. We'll redefine the member $name in this child class.

Child class Bar that extends parent class Foo


class Bar extends Foo
{
protected static $name = 'Bar';
}


We make the static call below example.

Static method call test()


echo Bar::test();


What is output from that call would be the string Foo. This is because the self::$name reference made in the test() method is done with the Foo class. The binding occurs this way because this is where the function is defined.

PHP V5.3 has added the keyword static to allow you to make a reference against the current class. So you will change the Foo class above to use this keyword in next example, and we'll see that Bar will instead be output.

Using the static keyword


class Foo
{
protected static $name = 'Foo';

public static function test()
{
return static::$name;
}
}

class Bar
{
protected static $name = 'Bar';
}

echo Bar::test(); // outputs 'Bar'


One thing to note about the static keyword is that it doesn't work the same as how this works in the nonstatic context. This means that the normal inheritance rules do not apply to static calls. The static keyword will simply try to resolve the call in the current class instead of the class the function was defined in. This is an important thing to note.

Now that we have seen some enhancements with static methods and members, let's take a look at some new classes added to a very useful part of PHP V5: the Standard PHP Library.



Standard PHP Library


The Standard PHP Library (SPL) is a collection of interfaces and classes added in PHP V5 designed to solve standard problems. These problems include having an object be iterateable, letting an object behave as if it was an array, or implementing a linked list. The advantage of using these classes and methods is that they are native to PHP, which means they are faster than if they were implemented in PHP itself. They also, in many instances, allow many of the internal functions of PHP to use these objects directly, such as how the Iterator interface allows you to use the foreach construct to iterate over the object.

PHP V5.3 adds a few more classes to SPL. One we referenced earlier is the implementation of a doubly linked list in the SPL class SplDoublyLinkedList. It is used by two other new SPL classes: SplStack, which implements a stack, and SplQueue, which implements a queue.

Let's take a look at how you can use the SplStack class to implement a stack.

Using SplStack

$stack = new SplStack();

// push a few new items on the stack
$stack->push('a');
$stack->push('b');
$stack->push('c');

// see how many items are on the stack
echo count($stack); // returns 3

// iterate over the items in the stack
foreach ( $stack as $item )
echo "[$item],";
// the above outputs: [c],[b],[a]

// pop an item off the stack
echo $stack->pop(); // returns 'c'

// now see how many items are on the stack
echo count($stack); // returns 2


The SqlQueue works in a similar fashion, but it works like a queue would (first item in, first item out; instead of last item in, first item out, like the stack). In addition, a heap implementation exists (SplHeap), as well as specific queue and heap implementations for certain situations (SplMinHeap, SplMaxHeap, and SplPriorityQueue).

Another useful addition is the SplFixedArray class, which, as the name implies, is a fixed-size array implementation. It is, however, rather fast — actually so fast that it's been benchmarked to be 10-30 percent faster than the built-in array implementation in PHP. This speedup is due to the fact that the array is a fixed size, not a variable-sized one like the default PHP one is, and that non-numeric indexes are not allowed. Listing 10 shows how it's used.

SplFixedArray

$array = new SplFixedArray(3);
$array[0] = 'dog';
$array[1] = 'cat';
$array[2] = 'bird';
$a->setSize(4); // increase the size on the fly
$array[3] = 'mouse';
foreach ( $array as $value )
echo "[$value],";

Output:
[dog],[cat],[bird],[mouse]


In addition, a few new iterator classes have been added: FilesystemIterator and GlobIterator. These work the same as the other iterator classes in PHP, but they are specially designed for certain instances.

One other change with SPL is that it is always enabled now in PHP V5.3. In previous versions of PHP V5, you could disable SPL at compile time, but as of PHP V5.3, this is no longer possible.

The new additions to SPL add some useful functionality to PHP that is easy to use, as well as implementations of data structures, such as doubly linked lists, stacks, heaps, and queues. These classes can be used to replace user space implementations you may have, which will gain increased speed and better integration with various PHP functions and constructs.

Now that we have seen some new additions to SPL, let's see how OOP in PHP V5.3 has gained an important performance and memory usage improvement with the addition of circular garbage collection.



Circular garbage collection

One problem PHP developers run into from a performance standpoint is garbage collection. PHP has a pretty simple garbage collector, which basically will garbage collect an object when it no longer is in scope. The way it does this internally is by using a reference counter, so that when the counter reaches zero (meaning no more references to this object are available), the object will be garbage collected and expunged from memory.

This works fairly well, but can become a problem in situations where one object references another in a parent-child relationship. In this situation, the reference counter for those object are not collected, so the memory used by these objects stays in unreferenced memory and is not unallocated until the end of the request. Let's take a look at an example of when this problem occurs.

Parent-child class relationship not properly garbage collected in PHP V5.2 and earlier

class Parent
{
public function __construct()
{
$this->child = new Child($this);
}
}

class Child
{
public function __construct(
Parent $parent
)
{
$this->parent = $parent;
}
}


In this instance, every time you create an instance of the Parent class and then subsequently the instance goes out of scope, the memory is never released, so the script will grow and grow in memory usage. There are a few user space solutions to this problem, such as creating a destructor for the parent class that will release the child object directly. This destructor would have to be called specifically before unsetting the parent class reference. While doing all of this works, it complicates your code quite a bit.

In PHP V5.3, the garbage collector will detect these circular references and is able to free up the memory used by them, so the PHP memory usage will remain flat as the script is executed. As each reference to the Parent class is removed, the Child class reference inside the Parent class will also be garbage collected.

This article is taken from https://www.ibm.com/

Leia Mais…

New features in PHP 5.3

Comparing to the PHP previous version php5.3 has many improved features. There are so many changes in the object interface.Php5.3 added several needed improvements, such as class visibility, proper constructors and destructors, type hinting, and a class-reflection API. It opened the door for advanced objected-oriented programming in PHP, and allowed you to implement many design patterns much easier, along with better design classes and APIs.

Improved static method and member handling
One useful addition made in PHP V5 was the ability to specify a method or member of a class as static. PHP 4 did support static access to methods and members of class, but not the ability to specify that the method or member is designed for static access. Static access is especially useful for implementing the singleton design pattern, where only one instance of class exists.

PHP5.3 has added several features to enhance the support for static members and methods within a class. A newly added magic method: __callStatic().

The _callStatic() magic method

PHP V5 has several specially defined methods that can be used inside classes known as magic methods. When defined in the class, these methods provide special functionality, and enable overloading (the ability to allow a method to accept different types of parameters) and polymorphism (the ability to allow different data types to use the same interface). They also open the door to using different types of OOP programming methods and design patterns with PHP easily.

In PHP V5.3, a new magic method is added: __callStatic(). This works similar to the __call() magic method, which is designed to handle method calls for methods that aren't defined or visible in the class. However, __callStatic() is designed for handling static method calls, which gives us the ability to better design our method overloading. An example of how to use this method is below.


class Foo
{
public static function __callStatic(
$name,
$args
)
{
echo "Called method $name statically";
}

public function __call(
$name,
$args
)
{
echo "Called method $name";
}
}

Foo::dog(); // outputs "Called method dog statically"
$foo = new Foo;
$foo->dog(); // outputs "Called method dog"

Dynamic static calls

One nice feature of PHP is variable variables. What this means is you can use the string value of a variable to specify the name of another variable. In other words, you could do something like what is shown below.

Variable variables

$x = 'y';
$$x = 'z';
echo $x; // outputs 'y'
echo $y; // outputs 'z'
echo $$x; // outputs 'z'


The same concept can be used with functions, or even class methods, as shown below.

Variable function and class method names


class Dog
{
public function bark()
{
echo "Woof!";
}
}

$class = 'Dog'
$action = 'bark';
$x = new $class(); // instantiates the class 'Dog'
$x->$action(); // outputs "Woof!"


New to PHP V5.3 is the ability to have the name of the class when specified be a variable when making a static call. This opens up a few new possibilities, as shown below.


Variable class naming


class Dog
{
public static function bark()
{
echo "Woof!";
}
}

$class = 'Dog';
$action = 'bark';
$class::$action(); //outputs "Woof!"


This addition makes the variable-variables feature of PHP complete, allowing them to be used in just about every situation with PHP.

This article is taken from https://www.ibm.com/

Leia Mais…

Monday, September 7, 2009

How To Install Apache 2.0/PHP 4.3 and MySQL 5.0 on Redhat

* Uninstall previous versions of apache and mysql

rpm -e httpd mysql

* Download and install RPM packages of MySQL's server, client and dynamic shared libraries from mysql.com. do not opt to change the password on MySQL database unless you know what you're doing (I don't). If requested at first installation attempt, download the appropriate version of perl-dbi from rpmfind.net.

rpm -ivh MySQL-client-5.0.20-0.glibc23.i386.rpm MySQL-server-5.0.20-0.glibc23.i386.rpm MySQL-shared-5.0.20-0.glibc23.i386.rpm

* Initialize mysql database after installation by typing..

mysql_install_db

* Make sure /etc/ld.so.conf contains:

/usr/lib

* Run ldconfig

/sbin/ldconfig

* Download, unpack, and install Apache 2.0 from source at apache.org

mv httpd-2.0.55.tar.gz /usr/local/; cd /usr/local/
tar -xzvf httpd-2.0.55.tar.gz
cd httpd-2.0.55
./configure --enable-so
make
make install

* Ensure Apache functions properly by starting, testing, and stopping it.

/usr/local/apache2/bin/apachectl start
http://localhost/

/usr/local/apache2/bin/apachectl stop

* Download, unpack, and install the newest 4.4.x version of PHP from php.net

mv php-4.4.1.tar.gz /usr/local/; cd /usr/local/
tar -xzvf php-4.4.1.tar.gz; cd php-4.4.1/
./configure --with-apxs2=/usr/local/apache2/bin/apxs --with-mysql
make
make install

* Add the following to your httpd.conf file:

LoadModule php4_module modules/libphp4.so
AddType application/x-httpd-php .php .phtml
AddType application/x-httpd-php-source .phps

* Modify httpd.conf again, and then restart the httpd (/usr/local/apache2/bin/apachectl restart):

DirectoryIndex index.html index.php

* To test your accomplishments, drop the following text into an index.php file within your DocumentRoot directory:

< ?php
phpinfo();
?>

Leia Mais…

Monday, August 31, 2009

Model View Controller - PHP

The MVC(Model View Controller) design breaks an application into three distinct layers:

1. Data management
2. User Interface
3. Logic

Model
Users, products, prices, messages catalogs, sitemaps e.t.c, it's all just data. You make sure the data is what you want, it goes into a database, then you have to get it back out. It will be useful for all the data-handling aspects to live in one place. That where model comes in.

Model is primarily concerned with handling data. Getting data from a database, inserting data into a database, validating data — all of this takes place within the model.

Best example is you have a User class, having variables such as username, password, email address, and other things. Some of its methods might be a new user creation function, a login function, an authentication function, and a logout function.
Later on, we will see how User objects will be used in the Controller part of your application. The Model, in essence, tells you what methods are available — what can you do to the data in the database. I thought I should just clarify (if it wasn’t clear already) — this should be all PHP code, just as what you should do in OO-programming even without MVC. There should be no HTML or any kinds of outputs (redirection, etc.) here. If doing an action means that a redirection is needed or some output is needed, pass it as an argument or a return value.

Here’s an example of the Model part of your code.

class student
{
var $name;
var $password;
var $class;
function student($u, $p, $e) // constructor
{
$this->name = $u;
$this->password = $p;
$this->class = $e;
}
function create()
{
// creates user in the db
}
function login()
{
// checks against db, does login procedures
}
static function authenticate($u, $p)
{
// checks against db
}
function logout()
{
// does logout procedures
}
}

View

Being able to save, retrieve, and validate your data is pretty useless without some means of displaying the data. By putting all display and presentation code in one place, you can change the look and feel of your application without having to work around application logic and data-related code.
View is primarily concerned with formatting data for presentation to the user. The view represents any and all UI work, including all templates and HTML.
Note:It is important that whatever PHP code in here is only what needs to be used to display the interface correctly. No additional “action” code belongs to the View — that is the Controller’s job, which we’ll see next.

<?php
require_once('student.php');
// Checking wherther student has been logged in or not
if (User::authenticate($_COOKIE['name'], $_COOKIE['password']))
{
header(”Location:/studentprofile.php”);
exit();
}
?>

<h1>Login</h1>
<?
if ($_GET['error'] == 1)
{
echo ‘Login incorrect. Please try again. ’;
}
?>
<form action=”login_action.php” method=”post”>
Student Name: <input type=”text” name=”name” />
Student Password: <input type=”password” name=”password” />
<input type=”submit” value=”Login” />

Controller
With data handling all contained within in the model, and the presentation layer all contained within the view, the rest of the application is going to live in the controller. This is where the application 'does' things — logic, decision-making, workflow, etc. The model manages your data, the view shows it to you, the controller does everything else.
The controller manages server requests. It accepts user input (URL requests, form POSTs, GET requests, etc.), applies logic where necessary, invokes models where data handling is required, and sends output through the appropriate view.Generally, a controller will manage logic for a single model. A controller contains any number of functions, referred to as actions. An action typically applies logic and displays a view.

For example you have a login page setup. The login HTML form has to submit to somewhere, right? (Even if you’re using AJAX) You don’t submit directly to the Model class file (say, User.php), because that file only contains the class code, and no actual procedural code is there, so it won’t do anything. You certainly don’t submit directly back to the View file (say, login.php), even if it ends with a .php extension! Because its job is only to display the interface.

This is what the Controller is. Your form will submit to a file, say, login_action.php. In this file, you create an instance of the User class, running whatever initialization you need, and calling the appropriate methods that need to be run (login).

<?php
require_once('student.php');
// in reality, a lot more error checking needs to be done.
$currentuser = new User($_POST['username'], $_POST['password'], ”);
if ($currentuser->login())
{
// set cookies for login info
header(”Location:/studentprofile.php”);
exit();
}
else
{
header(”Location:/login.php?error=1″);
exit();
}
?>

Leia Mais…

Tuesday, August 18, 2009

Read post array data

When working with the forms we are required to get all the form fields names and values at some point of time. In PHP the form values are returned in the form of array. We need to retrieve all the values in the form of pair(name,value) type.
This type of task will be used when we have hundred of variabes in a single form and we are confused with what form name the value is associated.

There are two ways to find the solutions:

1 method:

if ($_POST) {
echo htmlspecialchars(print_r($_POST, true));
}

2 Method:

foreach (array_keys($_POST) as $key) {
$$key = $_POST[$key];
print "$key is ${$key}
";
}

Leia Mais…

Monday, August 10, 2009

Php hacking techniques part 1

Techniques for securing user input, then extended those techniques to applications where database input and output is required, looking at some SQL security issues. next is to deal with file operations and file uploads, looking specifically at the security issues involved with accessing files based on some user supplied filename, and user-supplied files (uploaded files).


What Are Sessions?
Sessions are a PHP construct allowing persistent data to be retained across HTTP connections. In English, sessions allow you to store the values of certain variables across page visits. This is achieved by serializing the data (converting it to some binary representation) and writing it out to a file (or a database, or wherever you tell it), when a page is finished processing in PHP. When the next page (or that same page some time later) is processed, and PHP is told to start a session, it will check if the user already has a session, and read their data back in, unserializing it and assigning the variables. This allows you to keep track of a user across multiple visits, or while browsing multiple pages on your site.

For example, you can create a shopping cart using sessions, storing an array of items added to the cart in a session variable, and loading it on every page. When the user clicks 'Add to cart' you can add the item to the array, and it will be saved for the next page the user goes to. The whole array can be fetched on your checkout page and appropriate processing will take place.

How Do Sessions Work?
As many probably know, HTTP is a stateless protocol. By stateless, I mean that any HTTP connection is unaware of previous connections made by the same client, to the same server (persistent connections excepting). There are two useful ways in which PHP can pass identification information between pages in order to uniquely associate a user with a session.

PHP can use cookies to store a session ID. The cookie value is sent on every request, so PHP can match that up to its session data and retrieve the correct set of variables for that user. Another way is to pass the session ID in URLs. In order to do this, URL rewriting must be enabled.

Passing session data in URLs is not recommended since it is possible to pass your session onto another user if you give them a link which contains your session ID, and the session ID data is more easily attackable than in a cookie. URL-based session tracking should be used only where cookies cannot.

Using $_SESSION
PHP provides a super-global variable named $_SESSION. By super-global I mean it is a global variable which you may access without going via $_GLOBALS or stating global $_SESSION within a function. In this way, it behaves like $_GET and $_POST.

$_SESSION is, in fact, an associative array. The keys are variable names, and the values are the stored session data for that variable name.

Using $_SESSION is preferred over the use of session_register() to register ordinary global variables as session variables, especially when register_globals is enabled, since global variables may be more easily changed inadvertently than the contents of $_SESSION. It is still possible to alias ordinary global variables to their equivalents within $_SESSION,

$username = &$_SESSION["username"];

Here, the & indicates a reference, or alias. It is then possible to use $username instead of $_SESSION["username"], but note that $username is an ordinary variable, and you will have to access as $_GLOBALS["username"] or global $username from within a function.

Trusting Session Data
Since a session ID can be spoofed, it is always wise to perform some extra validation where possible. The simplest mechanism would be to store the IP address of the client to whom the session ID was issued, and compare the client IP against that stored IP every session. This will prevent the basic security problems associated with passing links between computers (though not if the computers are on a private network and share a single public IP address).

Session data is also stored in files on the server. The default location is /tmp on UNIX, or the system temporary file directory on Windows. If /tmp is world-writable (or, in some cases, world-readable), or there are multiple websites hosted on a single server, storing session data in a public location is not secure. PHP provides a way to change the way session data is stored.

Changing The Session File Path
The location in which PHP saves session data can be set using the php.ini directive session.save_path, or the string below in httpd.conf or a virtual host configuration.

php_value session.save_path "/home/test/sessions/"

It is important to ensure that your session data path is included in the paths allowed by open_basedir, if you have open_basedir settings or PHP Safe Mode enabled.

The data representation used for saving session data to files can be controlled with the session.serialize_handler directive in php.ini. By default, PHP uses its own built in format, but the WDDX ( http://www.wddx.org ) format can be used also. Set the type using one of the lines below.

(in php.ini ...)

session.serialize_handler wddx

or

session.serialize_handler php

(or in httpd.conf ...)

php_value session.serialize_handler wddx

or

php_value session.serialize_handler php

Storing Session Data In A Database
When you use on-disk files to store session data, those files must be readable and writeable by PHP. On a multi-user hosting system, it is possible for other users to access your session data through the PHP process (but see the commentary on open_basedir in part 5 of this series. The best way to secure your session data is to store it in a database.

Unfortunately, there is no direct way to store session data in a database using the php.ini directives, but luckily PHP provides a mechanism for customised session storage handlers. The function session_set_save_handler() allows you to register handler functions for session management. These functions must be written in PHP (or made available as a PHP extension).

session_set_save_handler(open_fn, close_fn, read_fn, write_fn,

destroy_fn, gc_fn)

To use these user-supplied session storage handlers, you must set session.save_handler to the value user, and the value of session.save_path should be the name of the database into which you're saving session data (so that the session save handler functions you define can locate and use that database). The value of session.name can be used as the name of the table within the database.

(httpd.conf)



php_value session.save_handler user

php_value session.save_path dbname

php_value session.name session_data



Next, a table for storing session data must exist in the database. At the minimum, your session handler should keep track of the session ID, the expiration time, and the serialized session data. The SQL below creates a simple table for storing this data.

CREATE TABLE session_data (

sessionid text not null PRIMARY KEY,

expiration timestamp,

sessiondata text not null

);

The final task is to create the functions which manage this session store, and register them with session_set_save_handler(). The open_fn must open the database connection, the close_fn must close it and perform any associated cleanup tasks, and the read_fn and write_fn functions must read and write session data respectively. destroy_fn is called when a session ends and is destroyed, and gc_fn is called when session data is garbage collected. These operations must be mapped into database queries by your PHP code. The prototypes for the functions are given below, and parameters passed are explained.

function open_fn($save_path, $session_name)

$save_path is the value of session.save_path, $session_name is the value of session.name

function close_fn()

Takes no arguments

function read_fn($session_id, $data)

$session_id is the session ID for which PHP requests the associated session data to be returned

function write_fn($session_id)

$session_id is the session ID for which PHP requests that $data be associated with in the session store (database)

function destroy_fn($session_id)

$session_id is the ID of a session which may be removed from the store

function gc_fn($max_time)

$max_time is the oldest last modified time to retain in the session store. Sessions with an older modified time than this are to be removed from the store.
-- Continued in Next pPrt

Leia Mais…

Friday, August 7, 2009

Php check File exists

When we are working with the directory structure we are in need of checking the files whether the file exists in the particular directory structure or not. In PHP we have the predefined function called file_exists() which checks the directory structure and returns a Boolean variable as the output. We can also check the file extension of the selected file also.
Here we may need only certain type of files to be displayed in a list of files. Like we may have the file name starting with "testing".

Below is an example which demonstrates the file_exists function and if the file exists then it checks for the file extension condition.


//==========
// Configuration
//==========
$directory = '/var/www/'; //Folder path
$lookingfor = 'testing'; //what to look for


$flag = false;
$ext = array( '.jpg' , '.gif' , '.png' );
for( $i = 0; count( $ext ) > $i; $i++ )
{
if( file_exists( $directory . $lookingfor . $ext[$i] ) )
{
$flag = true;
$name = $lookingfor . $ext[$i];
}
}

if( $flag == true )
{
echo 'found file!';
//echo $name;
}
?>

Leia Mais…

Saturday, July 18, 2009

php explode and implode

Explode
Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter .

Note:If delimiter is an empty string (""), explode() will return FALSE. If delimiter contains a value that is not contained in string and a negative limit is used, then an empty array will be returned. For any other limit , an array containing string will be returned.

Example:
// Example 1
$example = "test1 test2 test3 test4 test5 test6";
$pieces = explode(" ", $example);
echo $pieces[0]; // test1
echo $pieces[1]; // test2

// Example 2
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data);
echo $user; // foo
echo $pass; // *

?>

limit parameter examples

$str = 'one|two|three|four';

// positive limit
print_r(explode('|', $str, 2));

// negative limit (since PHP 5.1)
print_r(explode('|', $str, -1));
?>

Output is
Array
(
[0] => one
[1] => two|three|four
)
Array
(
[0] => one
[1] => two
[2] => three
)


Implode
Returns a string containing a string representation of all the array elements in the same order, with the glue string between each element.

Note: implode() can, for historical reasons, accept its parameters in either order. For consistency with explode(), however, it may be less confusing to use the documented order of arguments.

Syntax:
string implode ( string $glue , array $pieces )
string implode ( array $pieces )

Example:

$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);

echo $comma_separated; // lastname,email,phone

?>

Leia Mais…

Thursday, July 2, 2009

Advantages and disadvantages of PHP

What is PHP?
You will find this extension .php or the .php3 file extension in some of the popular sites too. Let us see that is this file extension, which language this extension refers to. Let us see what the main high lights of these language.

Hypertext preprocessor is the exact expansion of PHP, tough it doesn’t, fit to the exact spell, and it is adjusted to the word of mouth, called as PHP. PHP is a web scripting language. Let us see some the basic queries, which we come across php.

Who Wrote PHP?
Rasmus wrote PHP. PHP was started off accidentally, Rasmus was designing his web site, and he had planed to put a hit counter for his site. He decided to write a combination of Perl.

There were many enquires about the script which he used. Likewise, it slowly improved on and won the hearts of many programmers.

What type of scripting is PHP client or a server side?
PHP is a server side scripting language; server side scripting language is one, which has the capability of executing the script on the server and serving the output as a HTML File, server side script has the main advantage of interacting with the databases and to perform all types of server manipulations directly. Server side scripting language is responsible for manipulating the data which is filled in the entire web forms, any where in the net.

But this is not the case of a client side script. Some of the client side scripting languages is the JavaScript and VB script, but there are exceptions where, client side script can also be used for server side scripting, which is limited to some extent.

Can I use PHP with HTML?
Sure you can very well use HTML with PHP, like the other scripting languages you can do so. It is not a compulsory act for you to use PHP with the HTML. You can very well get the output with PHP alone. But the expected output, which is exhibited by PHP, is not that attractive for display. By attractive, I mean the formatting done by PHP.

Lets us take an example. You have a server side interaction with the database, which is used to manipulate and fetch a certain type of data based on the query, which is given out. Now, if you are going to display these data using PHP, which is fetched by PHP. The quality of output like the font face, font coloring and display areas are all disturbed, as well as being painful to locate and place the data. If HTML is used to present these data, the outlook of the data exhibited is gorgeous.

Can I Run PHP on the Windows Operating System?
You can very well run PHP on a windows machine. PHP is a cross platform support language, which means, PHP can run on various platforms like the Linux, Windows etc. Your web servers PWS, IIS, Apache can be configured to work PHP.

Is it easy migrating from any other server side scripting languages to PHP?
If you are aware of programming concepts and the application of the logic, then, you will find it ok to code any programming language if you simply understand the syntax. At the same, other scripting languages and PHP, have virtually the same function methodology. The only thing that matters is your requirement, how you are going to apply the logic and code php to your logic.

The main area lies while migrating is the syntax understanding. PHP’s syntax is similar to the C language. People with basic knowledge of C will find it very easy migrating as well as other aspects, an easy task.

I am new to programming, is it easy to learn PHP?
If you are very blind to programming then it is difficult to learn PHP because you may need to learn the programming concepts. This means you require an understanding of the logic, and to be able to troubleshoot the program. If you happen to know at least one programming language, then it is very easy to learn PHP. PHP it is pretty easy compared to other scripting languages.

What are the databases that support PHP?
PHP is very much compatible with MYSQL and POSTGRESQL Databases. PHP also can be programmed to interact with any database right from a simple text file to DB2. It is believed that php interacting with the database has the highest performance, unlike the other scripting languages.

How fast is PHP compared with other scripting languages?
PHP is believed to be fast when compared with other programming languages because of execution speed. In the case of large interactions with the database PHP really plays a good role of execution in performing the interaction. Now, today’s major web sites have been migrating to PHP because of the performance.

PHP is open source. Will this work properly?
PHP is the only scripting language, which has won the hearts of many web servers, has been moving on enormously day-by-day, The main advantages of the open source is that, if there is a problem that particular problem is shared my millions of programmers across the world. But in the case of a licensed version scripting languages, it is very limited to a set of a small community.

As innovative ideas are studied from all the programmers across the world, new ideas are implemented then and there making the language strong.

There is no problem in using PHP, which is open source.

I shall conclude by saying that, all the scripting languages have its own merits and demerits. So, it is up to you to decide for a partial migration or a full migration.

What are the main Advantages of PHP?
Let us see some of the important advantages of PHP. There are a lot of advantages of PHP. When it is compared with other scripting languages, some of the important highlights are as follows.

Speed

PHP is considered to be the fastest, as stated previously, when compared with other programming languages. You can really feel the speed when you are going to, implement live over the web.

Normally when you try to connect a database and fetch certain data, it usually takes time to connect the database, execute the statement, and get the data across. When these operations are performed by PHP it is really faster when compared with other types of scripting languages. Not only for the speed when connecting the database but also while using over other important applications.

Because of its high performance of speed, PHP is being used for some of the important administrations like the server administration over the web, mail functionalities.

Open Source

PHP is open source, open source is one where the user is given a free license to remodel or recode PHP, according to their wish. You might wonder if you can I do these things without source code. Yes would be the answer. Source code is shipped with PHP. It is open source remember.

Multi Platform

PHP supports various platforms, which mean PHP can be installed on almost every operating system, like the window-x, Linux, etc. You may choose the appropriate version and follow the instructions accordingly given in the Manual.

Easy Syntax

PHP syntax is quite easy to code, all the syntax are similar to the C language syntax, If you are very new to the programming environment then it will be a bit difficult task for you to code the PHP.

What are the main disadvantages of PHP?
Every language or scripting language has its own advantages or the disadvantages. Likewise, PHP has some of its own disadvantages.

But these disadvantages can be overcome using advantage methods.

Some people say it is a direct disadvantage, while some people say an indirect disadvantage.

Disadvantage indirectly means some of the aspects and functionalities in PHP, which are not being able to complete using the direct functionality. This particular disadvantage can be overcome using an advantage method.

Let us take a simple example, say redirection. Writing a piece of code from the client side or the server side - in some of the scripting languages there is a single task to achieve this - a single function will do so. But in the case of PHP it is done indirectly.

One more disadvantage is the Error Handling. It is believed that PHP has very poor handling errors qualities. Even this disadvantage can be over come using a feasible advantage solution.

These are some of the disadvantages. Note again, that this disadvantage can be overcome by using the advantage solution.

It is up to you to decide, whether to migrate or learn PHP.

PHP is great in the terms of performance of speed, which is the main factor, which people expect these days.

Leia Mais…

Monday, June 15, 2009

Cropping in PHP

When an image is uploaded, Complete image will be displayed, But there may be a situation where we need to have only part of the image to be displayed instead of complete image. So in that scenario's we use the concept called CROPPING.
The croppping option is the apt solution for such type of queries. This provides with same many options to the user. User can easily select the area, Which area he wants to crop. By providing the options user feels free to use the website.

The below downloading code is the basic version of the cropping. The downloading folder will contain the 2 folder and 2 files.

1. JS folder which contains the javascript function needed for the cropping option.
2. upload_pic which contains the uploaded images and the cropped images. When the
images are cropped, Then the images are saved in this folder.
3. Cropping document.txt which contains all the data related to the cropping like
where to change the width and height of the cropped area, where the files are
saving etc.
4. upload_crop.php contains the php code.

Code Explanation:

resizeThumbnailImage() This function is used to save the cropped image,It takes the thumb image name , height , width, starting height,starting width, scale .

getWidth,getHeight These methods are used for getting the uploaded image width and the height.

Leia Mais…

Monday, June 1, 2009

Upload Image With PHP

This example provides the uploaded image width and height before uploading the image which will be useful to restrict the users from uploading the large images.

//checks if the form has been submitted
if(isset($_POST['submit']))
{
//upload directory where the file will be stored
$uploaddir = 'uploads/';

$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

$uploadfiles = basename($_FILES['userfile']['name']);

list($width, $height, $type, $attr) =
getimagesize($_FILES['userfile']['tmp_name']);

if (file_exists($uploadfile)) {
//print error message
echo $uploadfiles;
echo "- file already exists");
die();
} else {
echo "The file $uploadfiles does not exist
";
}


if ($width > 80 || $height > 80)
{
//print error message
echo "Maximum allowed size is 80x80 pixels";
die();
}


if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "
Image Uploaded Successfully!

";

echo "
Image Width: ";
echo $width;
echo "
Image Height: ";
echo $width;
echo "
Image type: ";
echo $type;
echo "
Attribute: ";
echo $attr;
echo "
";
} else {
//print error message
echo "
File was not successfully uploaded

";
die();
}

}else{

?>

<form enctype="multipart/form-data" method="post" action="index.php">
<TABLE><TR><TD>
//define a maxim size for the uploaded images
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
Send this file: <input name="userfile" type="file">
</TD></TR><TR><TD>
<input type="submit" name="submit" value="upload">
</form>
</TD></TR></TABLE>

}
?>

Leia Mais…

Thursday, May 7, 2009

Watermarking on Images

One of the things you can do with PHP's many functions for image handling and manipulation is create an image watermarking class. This will allow you to add a watermark to images, which can be useful for a number of purposes.PHP features a wide array of functions for image handling and manipulation.

The main important of watermarking the image is to protect the images in a particular site. We may have the important images displayed and we donot want to redistribute the images to any other web sites. For such type of tasks the watermarking class is the best solution.

Through the watermarking we can restrict the image by placing our website name on the image and show the image while displaying to the user.One more thing that we need to save the watermarking and display, Just at the time of displaying the image we will make the image to be displayed by placing the watermarking text, By doing this we can have the original image with us and protect the image displayed to the user end as we imagecreatetruecolorare watermarking the image with the website name.

The main function used for creating the class is:

watermarkImage
This function takes the 3 parameters source file , destination file and the watermark text. if you want to save the file then you need to give the desitnation file path of not you can just simply leave it by empty paratemers.

imagesx outputs the width of the image.

imagesy outputs the height of the image.

imagecopyresampled copies a rectangular portion of one image to another image, smoothly interpolating pixel values so that, in particular, reducing the size of an image still retains a great deal of clarity.

imagettftext rites the given text into the image using TrueType fonts.

imagecreatetruecolorreturns an image identifier representing a black image of the specified size

imagejpegcreates a JPEG file from the given image .

There is a small difference between the imagejepg function

// Output the image
imagejpeg($im);

// Save the image as 'simpletext.jpg'
imagejpeg($im, 'simpletext.jpg');

if 1 parameter is provided then it directly shows the image and if you provide the file name then it saves the image with that particular file name.

Preview:



Leia Mais…

Wednesday, April 29, 2009

Paging in PHP

Paging is the concept which will be mostly used in any language like in java or dotnot or php. The main use of the paging will limit the number of records from displaying and make the user more clear about the records displayed. The concept of paging will be same in all the languages. You may take the dotnet or jsp or php the overall concept remains the same.
This may be the new concept but we may need the simpler version in writing the code. Here i am attachingthe code which may feel will be the simpler version, Any one can use this code.

In the downloaded files you will have the 2 php files and 1 database file. Run the script of the MYsql.

$start=$_GET['start']; // To take care global variable if OFF
if(!($start > 0)) { // This variable is set to zero for the first page
$start = 0;
}

$eu = ($start -0);
$limit = 8; // No of records to be shown per page.
$this1 = $eu + $limit;
$back = $eu - $limit;
$next = $eu + $limit;

Here we can change the no of records per page by changing the value of limit.



Leia Mais…

Friday, April 24, 2009

How to read html content in PHP and append the text

In php we have code for reading a file. But in some scenarios we may need to rad the html and in the html file we need to append certain variables with the external variables.

For example:
We need to send an email in a particular website. We will design the mail format in the html and save it. In the html file we will declare the dynamic variables with the special characters(like #username#). These are the dynamic variables which will change, depends on the user side functionality.

This is the sample code for obtaining the above task.

$txtsubject="Your new password";
$g_phpMailer_method = 2; // You will define the your mailer method
$g_smtp_host = 'XX.XX.XXX.XXX'; // you will define the host name
$g_smtp_username = 'XXXXX'; // Your SMTP admin name
$g_smtp_password = 'XXXXX'; // Your SMTP admin password
$to="testmail@gmail.com"; // To email address
$email="testmail@gmail.com"; // From email address
$subject="Your test subject";
$myFile = "tempfolder/mailformat.html";
$fh = fopen($myFile, 'r');
$body = fread ($fh, filesize($myFile));
$body= str_replace( '#mysubject#', $subject , $body);
$body = str_replace( '#myemail#', $email , $body);
$from="from email address";
$headers = 'MIME-Version: 1.0' . "\r\n".'Content-type: text/html; charset=iso-8859-1' . "\r\n".
'From:'.$from."\r\n" .'X-Mailer: PHP/' . phpversion();
if(mail($to, $txtsubject, $body, $headers))
{
echo "Mail sent";
}

Here we use fopen to open the html file and fread to read the html content into some variable. str_replace method is used to replace the ## between variables with the dynamic variables.

Leia Mais…

Saturday, April 18, 2009

Top 10 PHP Frameworks

Development of PHP scripts without a preconceived plan to manage them is asking for a headache. The goal of a framework is to make the process of writing web-based applications simpler.

An application designed around MVC is easier to manage because it is split into tiers, which allow for independent development. This promotes code reusability by building models, which are reusable throughout the application.

What makes a good framework?

A good framework is easy to learn, simple to use, intuitive to work with, easy to extend or to modify, rapid to build (maintain) applications with and of course stable.

Top 10 PHP MVC Frameworks:


1. YII



Yii is a component-based high-performance PHP framework for developing large-scale Web applications. Yii is written in strict OOP and comes with thorough class reference and comprehensive tutorials. From MVC, DAO/ActiveRecord, widgets, caching, hierarchical RBAC, Web services, to theming, I18N and L10N, Yii provides nearly every feature needed by today’s Web 2.0 application development. And all these come without incurring much overhead. As a matter of fact, Yii is one of the most efficient PHP frameworks around.

2. CodeIgniter



CodeIgniter is an Application Development Framework - a toolkit - for people who build web sites using PHP. Its goal is to enable you to develop projects much faster than you could if you were writing code from scratch, by providing a rich set of libraries for commonly needed tasks, as well as a simple interface and logical structure to access these libraries. CodeIgniter lets you creatively focus on your project by minimizing the amount of code needed for a given task.

3. CakePHP



CakePHP is a rapid development framework for PHP which uses commonly known design patterns like ActiveRecord, Association Data Mapping, Front Controller and MVC. Our primary goal is to provide a structured framework that enables PHP users at all levels to rapidly develop robust web applications, without any loss to flexibility.

4. PHPDevShell



PHPDevShell is an Open Source (GNU/LGPL) Rapid Application Development framework written using only PHP with no Javascript and comes with a complete GUI admin interface. It is aimed at developing admin based applications as plugins, where speed, security, stability and flexibility are essentials. It is designed to have a very easy learning curve without complicated new terms to learn. The need for a light, fully functional GUI with limitless configuration brought forward PHPDevShell. We strive to keep direction and focus in our development according to our moto.

5. Akelos



The Akelos PHP Framework is a web application development platform based on the MVC (Model View Controller) design pattern. Based on good practices, it allows you to:

* Write views using Ajax easily
* Control requests and responses through a controller
* Manage internationalized applications
* Communicate models and the database using simple conventions.

Your Akelos based applications can run on most shared hosting service providers since Akelos only requires that PHP be available at the server. This means that the Akelos PHP Framework is the ideal candidate for distributing standalone web applications as it does not require any non-standard PHP configuration to run.

6. Symfony



Symfony is a web application framework for PHP5 projects.

It aims to speed up the creation and maintenance of web applications, and to replace the repetitive coding tasks by power, control and pleasure.

The very small number of prerequisites make symfony easy to install on any configuration; you just need Unix or Windows with a web server and PHP 5 installed. It is compatible with almost every database system. In addition, it has a very small overhead, so the benefits of the framework don’t come at the cost of an increase of hosting costs.

Using symfony is so natural and easy for people used to PHP and the design patterns of Internet applications that the learning curve is reduced to less than a day. The clean design and code readability will keep your delays short. Developers can apply agile development principles (such as DRY, KISS or the XP philosophy) and focus on applicative logic without losing time to write endless XML configuration files.

Symfony is aimed at building robust applications in an enterprise context. This means that you have full control over the configuration: from the directory structure to the foreign libraries, almost everything can be customized. To match your enterprise’s development guidelines, symfony is bundled with additional tools helping you to test, debug and document your project.

7. Prado



The PRADO group is a team of PRADO enthusiasts who develop and promote the PRADO framework and the related projects.
Team Members

* Qiang Xue - founder of PRADO framework, core development
* Xiang Wei Zhuo - core development (javascripts, active controls, DB controls, tests)
* Jason Ragsdale - site and forum administration
* Knut Urdalen - test, marketing
* Carl G. Mathisen - design and document comment system
* Christophe Boulain - component development, test
* Michael Hartl - component development, test
* Eirik Hoem - core development
* Yves Berkholz - core development

Past Team Members

Alex Flint, Brian Luft, John Teague, Todd Patrick, Pim van der Zwet, Tim Evans, Alban Hanry, Marcus Nyeholt
History of PRADO

The very original inspiration of PRADO came from Apache Tapestry. During the design and implementation, I borrowed many ideas from Borland Delphi and Microsoft ASP.NET. The first version of PRADO came out in June 2004 and was written in PHP 4. Driven by the Zend PHP 5 coding contest, I rewrote PRADO in PHP 5, which proved to be a wise move, thanks to the new object model provided by PHP 5. PRADO won the grand prize in the Zend contest, earning high votes both from the public and from the judges’ panel.

In August 2004, PRADO was hosted on SourceForge as an open source project. Soon after, the project site xisc.com was announced to public. With the fantastic support of PRADO developer team and PRADO users, PRADO evolved to version 2.0 in mid 2005. In this version, Wei Zhuo contributed to PRADO with the excellent I18 and L10N support.

In May 2005, we decided to completely rewrite the PRADO framework to resolve a few fundamental issues found in version 2.0 and to catch up with some cool features available in Microsoft ASP.NET 2.0. After nearly a year’s hard work with over 50,000 lines of new code, version 3.0 was finally made available in April 2006.

Starting from version 3.0, significant efforts are allocated to ensure the quality and stability of PRADO. If we say PRADO v2.x and v1.x are proof-of-concept work, we can say PRADO 3.x has grown up to a serious project that is suitable for business application development.

8. Zend



Extending the art & spirit of PHP, Zend Framework is based on simplicity, object-oriented best practices, corporate friendly licensing, and a rigorously tested agile codebase. Zend Framework is focused on building more secure, reliable, and modern Web 2.0 applications & web services, and consuming widely available APIs from leading vendors like Google, Amazon, Yahoo!, Flickr, as well as API providers and cataloguers like StrikeIron and ProgrammableWeb.
Expanding on these core themes, we have implemented Zend Framework to embody extreme simplicity & productivity, the latest Web 2.0 features, simple corporate-friendly licensing, and an agile well-tested code base that your enterprise can depend upon.

9. ZooP



The Zoop Object Oriented Php Framework (The Zoop PHP Framework for short). A framework written in and for php.

The Zoop PHP Framework is stable, scalable and portable. It has been in production use for the last 5 years and has been used in many production environments. The Zoop PHP Framework is designed to be fast, efficient and clean. It is easily extendable and you choose to include only the functionality you use.

With Zoop an inexperienced coder can make secure web applications quickly. A more experienced coder will really appreciate how flexible The Zoop PHP Framework is. Both experienced and inexperienced coders alike will appreciate the automations that are at his/her disposal to handle mundane tasks.

The Zoop PHP Framework encourages separation of display, logic and data layers(MVC).

The Zoop PHP Framework is made up of many components and integrates many different projects including smarty (http://smarty.php.net) and the prototype AJAX framework. It also makes use of PEAR modules (http://pear.php.net). The efficient core components handle many of the functions you would have to code yourselves. Zoop’s integrated error handling can be configured to log errors for production environments, and is highly informative and readable which makes bugs easy to find and squash.

Zoop has been designed to make the developers life easier by providing tools to make efficient use of his/her time. On of our more unique and notable features is our implementation of GuiControls, a revolutionary idea in PHP that provides many form widgets with validation completely integrated, as well as a framework to develop your own guiControls extremely easily.

10. QPHP



QPHP stands for Quick PHP and is a MVC framework similar as architecture to ASP.NET.

I, as the author of the project, have spent the last 8 years working on web projects using various Java frameworks, ASP.NET and PHP. This framework tries to get the best of the above platforms as well as to avoid the problematic parts. Basically it:

* Brings the elegance of Java and C#
* Drops all Perl like bizzare statements that other PHP frameworks use
* Relies extensively on OOP concepts

Code-behind approach is used, so every webpage consists of 2 files:

* .PHP - presentation logic
* .PHP.SCRIPT - business/programming logic

FACTS ABOUT QPHP

* Less than 70 classes
* Less than 300K in size
* 3 years of internal use
* Works with PHP4/PHP5
* Easy database access
* Fast and stable
* Event driven, component based
* AJAX compatible
* I18N support
* View/Session/Application states
* Simple input validation
* 5 menu controls

Source taken from http://php.dzone.com

Leia Mais…