Wednesday, July 21, 2010

Session Time out in PHP - Simple Example

session_start();

// 10 mins in seconds
$inactive = 600;

$session_life = time() - $_session['timeout'];

if($session_life > $inactive)
{ session_destroy(); header("Location: logoutpage.php"); }

S_session['timeout']=time();

Tuesday, July 20, 2010

File System Functions Quick Reference

basename() Returns the filename component of a path

copy() Copies a file

delete() See unlink() or unset()

fclose() Closes an open file

feof() Tests for end-of-file on an open file

fgetcsv() Parses a line from an open file, checking for CSV fields

fgets() Returns a line from an open file

file() Reads a file into an array

file_exists() Checks whether or not a file or directory exists

file_get_contents() Reads a file into a string

file_put_contents Writes a string to a file

filesize() Returns the file size

fopen() Opens a file or URL

fputs() Alias of fwrite()

unlink() Deletes a file

fread() Reads from an open file


Example: Read csv file:

Ref: http://php.net/manual/en/function.fgetcsv.php

$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "

$num fields in line $row:

\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "
\n";
}
}
fclose($handle);
}

Proportional Thumbnail Image Creation

Example #2 Resampling an image proportionally
This example will display an image with the maximum width, or height, of 200 pixels.
// The file
$filename = 'test.jpg';

// Set a maximum height and width
$width = 200;
$height = 200;

// Content type
header('Content-type: image/jpeg');

// Get new dimensions
list($width_orig, $height_orig) = getimagesize($filename);

$ratio_orig = $width_orig/$height_orig;

if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}

// Resample
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);

// Output
imagejpeg($image_p, null, 100);
?>

REF: http://www.php.net/manual/en/function.imagecopyresampled.php

Thursday, July 15, 2010

How to run PHP 4 and PHP 5 at the same time on Apache for Windows

Whilst the majority of web applications are hosted on Linux, most developers use Windows. Installing Apache, PHP, and MySQL on your Windows PC is recommended and has become much easier. However, few developers can test their pages in PHP 4 and PHP 5 on the same machine at the same time – but it is possible…
Environment overview

This article will not describe every step in detail, but it should give you enough information to create your own multi-PHP web development environment:

1. We’ll define the domains http://test/ and http://test4/. Both will navigate to the same php files located in C:\WebPages\
2. PHP 5 will be installed as an Apache SAPI module and will be used for pages in the domain http://test/.
3. PHP 4 will be installed as a CGI binary. PHP files will be executed using PHP 4 by changing the domain to http://test4/ or accessing via port 81, e.g. http://test:81/

Note that the latest versions of PHP 5 run very slowly if you use the CGI binary. Defining it as a module solves this issue.
Installation ingredients

The freeware/open source software you’ll need is:

* Apache HTTP server for Windows. Stick with version 2.0.x – although 2.2 is available, PHP doesn’t work with it yet.
* The latest PHP 4 and PHP 5 Windows binaries. Although installers are available, I’d recommend you download the ZIP packages.
* Optionally, a copy of the Windows MySQL database.
* A decent text editor – I recommend Notepad++.

Both Apache and MySQL provide Windows installers, so just run them. All going well, you should then be able to navigate to http://localhost/ in your browser.

Extract PHP 4 to C:\php\php4 and PHP 5 to C:\php\php5. Follow the instructions for configuring your php.ini file, but ignore the Apache setup details for now – we’ll cover that below. One setting that may catch you out is extension_dir – for PHP 5 use: extension_dir = "C:\php\php5\ext"

and for PHP 4 use: extension_dir = "C:\php\php4\extensions\"

You can now uncomment any extensions you wish to use, e.g. extension=php_mysql.dll in PHP 5’s php.ini.
Windows system setup


Now all the files are in place, we’ll define the local domains test and test4. This is done by editing the hosts file, located in %WINDOWS%/system32/drivers/etc. Add the following lines: 127.0.0.1 test 127.0.0.1 test4

You can update your system using the command ‘nbtstat -R’, but you’ll need a reboot soon so don’t worry about it!

Now go to the Control Panel, open System, click the Advanced tab, and click Environment Variables. In the System variables section, click “Path” in the list followed by Edit. Add “;C:\php\php4;C:\php\php5″ to the end of the Variable value line.

Now reboot to make sure the settings are applied.
Configuring Apache

The Apache configuration file is normally located at %PROGRAMS%\Apache Group\Apache2\conf\httpd.conf You’ll need to locate and edit the following settings.

Set the server to listen on port 80 (the default) and port 81: Listen 80 Listen 81

Ensure your root folder is set correctly (note the forward slash): DocumentRoot "C:/WebPages"

Add php files to the directory index, e.g. DirectoryIndex index.html index.php

Just before the Virtual Hosts section, define PHP 5 as a SAPI module: # PHP5 module LoadModule php5_module "c:/php/php5/php5apache2.dll" AddType application/x-httpd-php .php PHPIniDir "C:/php/php5"

Finally, we’ll define the localhost, test, and test4 virtual domain settings for ports 80 and 81. Where PHP 4 is required (test4 domain or port 81), it is defined as a CGI binary that will override the PHP5 module.

NameVirtualHost *:80
NameVirtualHost *:81

# localhost:80 - PHP5


DocumentRoot C:/WebPages


# localhost:81 - PHP4


DocumentRoot C:/WebPages
ScriptAlias /php/ "c:/php/php4/"
Action application/x-httpd-php4 "/php/php.exe"
AddHandler application/x-httpd-php4 .php


# test:80 - PHP5


ServerName test DocumentRoot C:/WebPages


# test:81 - PHP4


ServerName test
DocumentRoot C:/WebPages
ScriptAlias /php/ "c:/php/php4/"
Action application/x-httpd-php4 "/php/php.exe"
AddHandler application/x-httpd-php4 .php


# test4:80 - PHP4


ServerName test4
DocumentRoot C:/WebPages
ScriptAlias /php/ "c:/php/php4/"
Action application/x-httpd-php4 "/php/php.exe"
AddHandler application/x-httpd-php4 .php


# test4:81 - PHP4


ServerName test4
DocumentRoot C:/WebPages
ScriptAlias /php/ "c:/php/php4/"
Action application/x-httpd-php4 "/php/php.exe"
AddHandler application/x-httpd-php4 .php


You’ll now need to restart Apache. It may be best to use “net stop apache2″ followed by “net start apache2″ on the command line. This will allow you to see any configuration error messages, but several other helpful tools are provided in the Apache program group.
Testing your environment

Create a new file phpinfo.php in C:\WebPages\. Edit the file and add the line:

Save it, then visit the following addresses in your browser:

* http://test/phpinfo.php – should show PHP 5
* http://test4/phpinfo.php – should show PHP 4
* http://test:81/phpinfo.php – should show PHP 4

And that’s all there is to it!

Ref: http://www.optimalworks.net/blog/2007/web-development/php/php-apache-windows

Tuesday, July 13, 2010

JQuery, Javascript Qustions

What is Jquery?

JQuery is Java Script library or Java Script Framework which helps in how to traverse HTML documents, do some cool animations, and add Ajax interaction to any web page. It mainly helps programmer to reduce lines of code as huge code written in Java Script, can be done easily with JQuery in few lines.


1. What are the different type of selectors in Jquery?

1. CSS Selector

Examples:

Hide all Paragraph elements that contain a class attribute:

$("p[@class]").hide();

Show the first paragraph on the page:

$("p:eq(0)").show();

Hide all divs that are currently showing:

$("div:visible").hide();


2. XPath Selector (XML Path)

* Relative to the entire HTML document

$("/html/body//p")
$("body//p")
$("p/../div")


3. Custom Selector

Examples:

$("p:first").css("fontWeight","bold");
$("div:hidden").show();
$("/div:contains('test')", this).hide();


More Reference: http://docs.jquery.com/DOM/Traversing/Selectors#XPath_Selectors

4. Tell some methods of JQuery used to provide effects?

1. Show()
2. Hide()
3. Toggle()
4. FadeIn()
5. FadeOut()


5. Whats the Features of Jquery?

1. One can easily provide effects and can do animations.
2. Applying / Changing CSS.
3. Cool plugins.
4. Ajax support
5. DOM selection events
6. Event Handling

6. Whats the onload function in JQuery?

$(document).ready(function() {
// put all your jQuery goodness in here.
});

* Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded.

7. What is build in data types in Javascript?

a) String, Number, Boolean, Object, Array,

8. What is the usage of jQuery noConflict?

* jQuery.noConflict( [ removeAll ] )
* removeAll Boolean indicating whether to remove all jQuery variables from the global scope (including jQuery itself).

Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $. If we need to use another JavaScript library alongside jQuery, we can return control of $ back to the other library with a call to $.noConflict():









jQuery Events
« Previous Next Chapter »

jQuery is tailor made to handle events.
jQuery Event Functions

The jQuery event handling functions are core functions in jQuery.

Event handlers are functions that are called when "something happens" in HTML. The term "triggered (or "fired") by an event" is often used.

It is common to put jQuery code into event handler functions in the "head" section:
Example
<html>
<head>






From w3schools.com

jQuery Name Conflicts

jQuery uses the $ sign as a shortcut for jQuery.

Some other JavaScript libraries also use the dollar sign for their functions.

The jQuery noConflict() method specifies a custom name (like jq), instead of using the dollar sign.


jQuery Events

$(document).ready(function)
Binds a function to the ready event of a document (when the document is finished loading)
$(selector).click(function)
Triggers, or binds a function to the click event of selected elements
$(selector).dblclick(function)
Triggers, or binds a function to the double click event of selected elements
$(selector).focus(function)
Triggers, or binds a function to the focus event of selected elements
$(selector).mouseover(function)
Triggers, or binds a function to the mouseover event of selected elements


jQuery Selectors
*** Selectors allow you to manipulate DOM elements as a group or as a single node.


jQuery Element Selectors

jQuery uses CSS selectors to select HTML elements.

$("p") selects all

elements.

$("p.intro") selects all

elements with class="intro".

$("p#demo") selects the first

element with id="demo".

jQuery Attribute Selectors

jQuery uses XPath expressions to select elements with given attributes.

$("[href]") select all elements with an href attribute.

$("[href='#']") select all elements with an href value equal to "#".

$("[href!='#']") select all elements with an href attribute NOT equal to "#".

$("[href$='.jpg']") select all elements with an href attribute that ends with ".jpg".

jQuery CSS Selectors

jQuery CSS selectors can be used to change CSS properties for HTML elements.

The following example changes the background-color of all p elements to yellow:
Example
$("p").css("background-color","yellow");

Monday, July 12, 2010

Payment Gateway Related

Paypal Recurring Payment Gateway Process:

PayPal Recurring Payments allows you to bill a buyer for a fixed amount of money on a fixed schedule. The buyer signs up for recurring payments during checkout from your site. Consider the following examples:

A buyer purchases a subscription to a magazine or newsletter from your site and agrees to pay a monthly fee. A buyer agrees to pay an Internet Service Provider a flat fee on a semi-annual basis to host a website. These examples represent payment transactions that reoccur periodically and are for a fixed amount. When you create recurring payments for a buyer, you create a recurring payments profile. The profile contains information about the recurring payments, including details for an optional trial period and a regular payment period. Each of these subscription periods contains information about the payment frequency and payment amounts, including shipping and tax, if applicable.

After a profile is created, PayPal automatically queues payments based on the billing start date, billing frequency, and billing amount, until the profile expires or is canceled by the merchant. The buyer can also cancel the recurring payment profile for profiles creating using Express Checkout.

Note that for profiles created using Express Checkout, the queued payments are funded using the normal funding source hierarchy within the buyer's PayPal account.

After the recurring payments profile is created, you can view recurring payments details or cancel the recurring payments profile from your PayPal account.You can also access recurring payments reports from the PayPal Business Overview page.

More information about recurring payment is available at
https://www.paypal.com/IntegrationCenter/ic_recurringpayment
s.html

File upload and configuration

1. Who will be the owner of the uploaded file ?

ANS: Apache will be the owner of the uploaded file.

2. What permission you will give for an uploaded file ?

ANS: It depends upon the scenario on which we're going to use
the uploaded file(s), by default it's 660 file permission.

3. What is mean by user, group and others and what kind of
permission you will give for each user and explain the
reason?

ANS: Basically a file in linux has permissions related to the
user (owner), group (owner group) and others (rest of the
users/groups). So accordingly we provide the permissions to
a file(s). Also, permission are basically related to READ,
WRITE and EXECUTE operations.


File Upload Configuration:

* List of configuration check list items given below for your better idea.

* file_uploads
* upload_max_filesize
* max_input_time
* memory_limit
* max_execution_time
* post_max_size

The first one is fairly obvious if you set this off, uploading is disabled for your installation. We will cover the rest of the configuration settings in detail below.

upload_max_filesize and post_max_size

Files are usually POSTed to the webserver in a format known as 'multipart/form-data'. The post_max_size sets the upper limit on the amount of data that a script can accept in this manner. Ideally this value should be larger than the value that you set for upload_max_filesize.

It's important to realize that upload_max_filesize is the sum of the sizes of all the files that you are uploading. post_max_size is the upload_max_filesize plus the sum of the lengths of all the other fields in the form plus any mime headers that the encoder might include. Since these fields are typically small you can often approximate the upload max size to the post max size.

According to the PHP documentation you can set a MAX_UPLOAD_LIMIT in your HTML form to suggest a limit to the browser. Our understanding is that browsers totally ignore this directive and the only solution that can impose such a client side restriction is our own Rad Upload Applet
memory_limit
When the PHP engine is handling an incoming POST it needs to keep some of the incoming data in memory. This directive has any effect only if you have used the --enable-memory-limit option at configuration time. Setting too high a value can be very dangerous because if several uploads are being handled concurrently all available memory will be used up and other unrelated scripts that consume a lot of memory might effect the whole server as well.
max_execution_time and max_input_time
These settings define the maximum life time of the script and the time that the script should spend in accepting input. If several mega bytes of data are being transfered max_input_time should be reasonably high. You can override the setting in the ini file for max_input_time by calling the set_time_limit() function in your scripts.


Additonal Comments

Apache Settings

The apache webserver has a LimitRequestBody configuration directive that restricts the size of all POST data regardless of the web scripting language in use. Some RPM installations sets limit request body to 512Kb. You will need to change this to a larger value or remove the entry altogether.
Other Options

If you expect to handle a large number of concurrent file transfers on your website consider using a perl or java server side component. PHP happens to be our favourite web programming language as well but perl and Java are just slightly ahead when it comes to file upload.

Most installations of perl as an apache module can accept in excess of 32 megabytes out of the box. Compare this against the 2MB default for PHP. The downside is that perl coding takes just a bit more effort than PHP but it's worth it.