Thursday, September 8, 2011

PHP hacking technique

1. Introduction

PHP (http://www.php.net) is a powerful server side web scripting solution. It has quickly grown in popularity and according to the 2000 January Netcraft Web Server Survey PHP is installed on 12.8% of all web sites. Much of its syntax is borrowed from C, Java and Perl with a couple of unique PHP-specific features thrown in. The goal of the language is to allow web developers to write dynamically generated pages quickly.

Being a good PHP hacker isn't just about writing single line solutions to complex problems. For example, web gurus know that speed of coding is much more important than speed of code. In this article we'll look at techniques that can help you become a better PHP hacker. We'll assume that you have a basic knowledge of PHP and databases.

If nothing else, you should leave here with the 3 key ideals for PHP hackers:

  • Laziness is a Virtue
  • Chameleon Coding
  • Speed of Coding, Not Speed of Code


2. Laziness is a Virtue

2.1. Introduction

It seems strange to think of a web programmer as lazy. Most of us work one hundred-hour week's in our quest to join the gold rush. In fact, we need to be lazy because we are so busy.

There are two key ways to be lazy. Firstly always use existing code when it is available, just integrate it into your standards and project. The second technique is to develop a library of helpful functions that let you be lazy in the future.

2.2. Use Other People's Code
We need to use laziness to our advantage and PHP is the perfect tool. PHP was born and raised in an open source environment. The community holds open source ideals close to its heart. As a result there are thousands of people on the mailing list willing to share their knowledge and code. There are also many open source PHP projects that you can tap into. I'm not suggesting that you spend all day asking people to write code for you. But through clever use of the knowledge base, mailing list archives and PHP projects you can save yourself a lot of time.

PHP Knowledge Base - http://php.faqts.com

PHP Mailing List Archive - http://www.progressive-comp.com/Lists/?l=php3-general&r=1&w=2

2.3. Helpful Functions and Classes
2.3.1. Introduction

In this section we will work at developing a library of PHP code which will aid us in future development. A small amount of work now let's us be lazy in the future.

Some of this code has been taken from open source PHP projects. Other parts from the mailing list archives. In fact, all the work I really needed to do was structure the code into a coherent library of functions.

2.3.2. Database Abstraction

One of the features / problems with PHP is that it does not have a uniform method for accessing databases. There are specialized functions for each database PHP is able to connect to. This is a feature because it allows you to optimize your database code. It is a problem because it makes your code less portable and increases the learning curve for newcomers.

A number of database wrapper classes have been developed to solve this problem. They provide a uniform set of functions for accessing any database. Personally I like them because I find it much easier to remember a few simple functions like query and next_record than having to think about database handles, connections and so on.

The most commonly used (and defacto standard) is PHPLib - http://phplib.netuse.de/

Metabase - http://phpclasses.UpperDesign.com/browse.html/package/20

There is also PHPDB - http://phpdb.linuxbox.com/

2.3.3. Session Management

The main purpose of PHPLib is session management. This allows you to associate data with visitors to your site for the duration of their stay. This can be useful for remembering options and so on.

PHP4 has session management features built into the PHP internal function library.

2.3.4. Debugging Variables

There is limited debugging support for PHP. This is no Smalltalk environment where you can browse objects and perform methods on them. Instead we need to make creative use of the old, reliable echo statement.

The first thing we need to be able to do is look at the value of variables. The loose typing of PHP lets us use most variables directly in strings. This is great for numbers and so on, but falls down when we are dealing with arrays and objects.

The other problem with debugging is that sometimes I'm not even sure what a variable is likely to contain. If I was, there be no need to debug.

So, lets be smart now and lazy for the rest of time. We can write a function that shows us the type and value of any variable.

function ss_array_as_string (&$array, $column = 0) {

    $str = "Array(<BR>\n";

    while(list($var, $val) = each($array)){

        for ($i = 0; $i < $column+1; $i++){

            $str .= "&nbsp;&nbsp;&nbsp;&nbsp;";

        }

        $str .= $var.' ==> ';

        $str .= ss_as_string($val, $column+1)."<BR>\n";

    }

    for ($i = 0; $i < $column; $i++){

        $str .= "&nbsp;&nbsp;&nbsp;&nbsp;";

    }

    return $str.')';

}



function ss_object_as_string (&$object, $column = 0) {

    if (empty($object->classname)) {

        return "$object";

    }

    else {

        $str = $object->classname."(<BR>\n";

        while (list(,$var) = each($object->persistent_slots)) {

            for ($i = 0; $i < $column; $i++){

                $str .= "&nbsp;&nbsp;&nbsp;&nbsp;";

            }

            global $$var;

            $str .= $var.' ==> ';

            $str .= ss_as_string($$var, column+1)."<BR>\n";

        }

        for ($i = 0; $i < $column; $i++){

            $str .= "&nbsp;&nbsp;&nbsp;&nbsp;";

        }

        return $str.')';

    }

}



function ss_as_string (&$thing, $column = 0) {

    if (is_object($thing)) {

        return ss_object_as_string($thing, $column);

    }

    elseif (is_array($thing)) {

        return ss_array_as_string($thing, $column);

    }

    elseif (is_double($thing)) {

        return "Double(".$thing.")";

    }

    elseif (is_long($thing)) {

        return "Long(".$thing.")";

    }

    elseif (is_string($thing)) {

        return "String(".$thing.")";

    }

    else {

        return "Unknown(".$thing.")";

    }

}


Note that these functions work together to correctly print, format and indent arrays. They are also able to print objects when they have been defined with the PHPLIB standard variables classname (the name of the class) and persistent_slots (an array of the variable names we care about).

Now we can see the state of any variable by just doing:

    echo ss_as_string($my_variable);

We can see the value of all variables currently defined in the PHP namespace with:
    echo ss_as_string($GLOBALS);

2.3.5. Log Functions

A great way to debug is through logging. It's even easier if you can leave the log messages through your code and turn them on and off with a single command. To facilitate this we will create a number of logging functions.

$ss_log_level = 0;

$ss_log_filename = '/tmp/ss-log';

$ss_log_levels = array(

    NONE  => 0,

    ERROR => 1,

    INFO  => 2,

    DEBUG => 3);



function ss_log_set_level ($level = ERROR) {

    global $ss_log_level;

    $ss_log_level = $level;

}



function ss_log ($level, $message) {

    global $ss_log_level, $ss_log_filename;

    if ($ss_log_levels[$ss_log_level] < $ss_log_levels[$level]) {

        // no logging to be done

        return false;

    }

    $fd = fopen($ss_log_filename, "a+");

    fputs($fd, $level.' - ['.ss_timestamp_pretty().'] - '.$message."\n");

    fclose($fd);

    return true;

}



function ss_log_reset () {

    global $ss_log_filename;

    @unlink($ss_log_filename);

}


There are 4 logging levels available. Log messages will only be displayed if they are at a level less verbose than that currently set. So, we can turn on logging with the following command:

    ss_log_set_level(INFO);

Now any log messages from the levels ERROR or INFO will be recorded. DEBUG messages will be ignored. We can have as many log entries as we like. They take the form:
    ss_log(ERROR, "testing level ERROR");

    ss_log(INFO, "testing level INFO");

    ss_log(DEBUG, "testing level DEBUG");

This will add the following entries to the log:
    ERROR - [Feb 10, 2000 20:58:17] - testing level ERROR

    INFO - [Feb 10, 2000 20:58:17] - testing level INFO

You can empty the log at any time with:
    ss_log_reset();

2.3.6. Optimization

We need a way to test the execution speed of our code before we can easily perform optimizations. A set of timing functions that utilize microtime() is the easiest method:

function ss_timing_start ($name = 'default') {

    global $ss_timing_start_times;

    $ss_timing_start_times[$name] = explode(' ', microtime());

}



function ss_timing_stop ($name = 'default') {

    global $ss_timing_stop_times;

    $ss_timing_stop_times[$name] = explode(' ', microtime());

}



function ss_timing_current ($name = 'default') {

    global $ss_timing_start_times, $ss_timing_stop_times;

    if (!isset($ss_timing_start_times[$name])) {

        return 0;

    }

    if (!isset($ss_timing_stop_times[$name])) {

        $stop_time = explode(' ', microtime());

    }

    else {

        $stop_time = $ss_timing_stop_times[$name];

    }

    // do the big numbers first so the small ones aren't lost

    $current = $stop_time[1] - $ss_timing_start_times[$name][1];

    $current += $stop_time[0] - $ss_timing_start_times[$name][0];

    return $current;

}

Now we can check the execution time of any code very easily. We can even run a number of execution time checks simultaneously because we have established named timers.

See the optimizations section below for the examination of echo versus inline coding for an example of the use of these functions.

2.3.7. Debugging and Optimizing Database Operations

The best way to gauge the stress you are placing on the database with your pages is through observation. We will combine the logging and timing code above to assist us in this process.

We will alter the query() function in PHPLib, adding debugging and optimizing capabilities that we can enable and disable easily.


function query($Query_String, $halt_on_error = 1) {

    $this->connect();

    ss_timing_start();

    $this->Query_ID = @mysql_query($Query_String,$this->Link_ID);

    ss_timing_stop();

    ss_log(INFO, ss_timing_current().' Secs - '.$Query_String);

    $this->Row   = 0;

    $this->Errno = mysql_errno();

    $this->Error = mysql_error();

    if ($halt_on_error && !$this->Query_ID) {

      $this->halt("Invalid SQL: ".$Query_String);

    }

    return $this->Query_ID;

}


3. Chameleon Coding

3.1. Introduction
A chameleon is a lizard that is well known for its ability to change skin color. This is a useful metaphor for web programming as it highlights the importance of separating well structured and stable backend code from the dynamic web pages it supports.

PHP is the perfect language for chameleon coding as it supports both structured classes and simple web scripting.

3.2. Structuring your PHP Code
3.2.1. Introduction

When writing PHP code we need to make a clear distinction between the code which does the principal work of the application and the code which is used to display that work to the user.

The backend code does the difficult tasks like talking to the database, logging, and performing calculations.

The pages that display the interface to these operations are part of the front end.

3.2.2. Dynamic, Hackable Frontend Code

Mixing programming code in with HTML is messy. We can talk about ways to format the code or structure your pages, but the end result will still be quite complicated.

We need to move as much of the code away from the HTML as possible. But, we need to do this so that we don't get lost in the interaction between our application and the user interface.

A web site is a dynamic target. It is continually evolving, improving and changing. We need to keep our HTML pages simple so that these changes can be made quickly and easily. The best way to do that is by making all calls to PHP code simple and their results obvious.

We shouldn't worry too much about the structure of the PHP code contained in the front end, it will change soon anyway.

That means that we need to remove all structured code from the actual pages into the supporting include files. All common operations should be encapsulated into functions contained in the backend.

3.2.3. Stable, Structured Backend Code In complete contrast to the web pages your backend code should be well designed, documented and structured. All the time you invest here is well spent, next time you need a page quickly hacked together all the hard parts will be already done waiting for you in backend functions.

Your backend code should be arranged into a set of include files. These should be either included dynamically when required, or automatically included in all pages through the use of the php3_auto_prepend_file directive.

If you need to include HTML in your backend code it should be as generic as possible. All presentation and layout should really be contained in the front end code. Exceptions to this rule are obvious when they arise, for example, the creation of select boxes for a date selection form.

PHP is flexible enough to let you design your code using classes and or functions. My object oriented background means that I like to create a class to represent each facet of the application. All database queries are encapsulated in these classes, hidden from the front end pages completely. This helps by keeping all database code in a single location and simplifying the PHP code contained in pages.

Twitter, Facebook & Google Plus Integration

Twitter
Twitter allows you to update your Twitter timeline by sending an email to a secret address. So go to TwitterMail.com and sign-in with your Twitter account credentials. In the Twittermail tab, find a button to setup your Twittermail account. Now simply, press the button “Set up your twittermail account now”.
In this Twitter setup page there is a unique email address which has been assigned to you to send the updates. Now, when you wish to share a post in Twitter from your Google plus profile, just add that email address in the visibility box along with other circle(s) and share the post as usual.
To avoid having to type that email address every time, create a circle and add that secret Twittermail address to that circle. Voila!
Facebook
Ditto except go to Facebook.com/mobile to get your facebook email address! For chrome users, just install the extension for your browser and you automatically get fb and twitter buttons in g+ to share your post with!

Thursday, July 21, 2011

Web service in php

Most of the times it seems like developer are little bit confused about the webservice.



Webservice is nothing but the output in such a format so the technology going to use your webservice can manage it. Here i have tried to provide your all two solutions regarding the PHP web-service.
With use of below code, you can generate your desire output in XML as well in JSON format.





You can call this file to get XML output format, by typing http://localhost/index.php?user=1&num=10


To get output in json format, you can type http://localhost/index.php?user=1&num=10&format=json


index.php





/* require the user as the parameter */
if(isset($_GET['user']) && intval($_GET['user'])) {

/* soak in the passed variable or set our own */
$number_of_posts = isset($_GET['num']) ? intval($_GET['num']) : 10; //10 is the default
$format = strtolower($_GET['format']) == 'json' ? 'json' : 'xml'; //xml is the default
$user_id = intval($_GET['user']); //no default

/* connect to the db */
$link = mysql_connect('DATBASE_HOST','DATABASE_USER','DATABASE_PASSWORD') or die('Cannot connect to the DB');
mysql_select_db('DATABASE_NAME',$link) or die('Cannot select the DB');

/* grab the posts from the db */
$query = "SELECT * FROM user WHERE userID = $user_id ORDER BY orderKey DESC LIMIT $number_of_posts";
$result = mysql_query($query,$link) or die('Errant query: '.$query);

/* create one master array of the records */
$posts = array();
if(mysql_num_rows($result)) {
while($post = mysql_fetch_assoc($result)) {
//print_r($post);
$posts[] = array('post'=>$post);
}
}


/* output in necessary format */
if($format == 'json') {
//header('Content-type: application/json');
echo json_encode(array('posts'=>$posts));
echo "
";
print_r(json_decode(json_encode(array('posts'=>$posts))));
}
else {
header('Content-type: text/xml');
echo '';
foreach($posts as $index => $post) {
if(is_array($post)) {
foreach($post as $key => $value) {
echo '<',$key,'>';
if(is_array($value)) {
foreach($value as $tag => $val) {
echo '<',$tag,'>',htmlentities($val),'';
}
}
echo '';
}
}
}
echo '
';
}

/* disconnect from the db */
@mysql_close($link);
}?>

Redirecting www to non-www Using .htaccess

The Apache Web server supports URL rewriting with the mod_rewrite engine. Placing custom rules in an .htaccess file lets you do all sorts of useful things to keep your URLs tidy. One really handy thing you can do for search engines and visitors is redirecting traffic from www to non-www version of your domain (and vice versa).



Some people prefer to use www.somesite.com, but some people prefer the shorter somesite.com. There isn't really a right or wrong way to do it, but whatever you choose you can make sure all of your visitors get sent to the same place. With a few simple rules on the server you can choose from non-www to www, or redirecting from www to non-www.


If you already have a file named .htaccess on your Website you can add to it. If not, create one (yes, include the period at the beginning). Add either of the following rules and save. Replace yourdomain.com with your actual domain name.


Redirect www to non-www:


RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www.yourdomain.com [NC]
RewriteRule ^(.*)$ http://yourdomain.com/$1 [L,R=301]

Redirect non-www to www:


RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^yourdomain.com [NC]
RewriteRule ^(.*)$ http://www.yourdomain.com/$1 [L,R=301]


Both of these rules send a full search engine friendly 301 HTTP redirect. They also preserve the entire URL (so yoursite.com/about redirects to www.yoursite.com/about).


Search engines can usually figure out which format is preferred, but since you're showing the same page for www and non-www URLs it can't hurt to be consistent about it.

Thursday, June 16, 2011

cron job tutorial

Setting up cron jobs in Unix and Solaris


Whenever you think about the cron job, you will get one question at very first in your mind that from where we can set the Cron?


You can set Cron job from your control panel, Cpanel Homepage->Advanced->Cron Jobs


cron is a unix, solaris utility that allows tasks to be automatically run in the background at regular intervals by the cron daemon. These tasks are often termed as cron jobs in unix , solaris.  Crontab (CRON TABle) is a file which contains the schedule of cron entries to be run and at specified times.


This document covers following aspects of Unix cron jobs

1. Crontab Restrictions

2. Crontab Commands

3. Crontab file – syntax


4. Crontab Example

5. Crontab Environment

6. Disable Email

7. Generate log file for crontab activity


1. Crontab Restrictions

You can execute crontab if your name appears in the file /usr/lib/cron/cron.allow. If that file does not exist, you can use

crontab if your name does not appear in the file /usr/lib/cron/cron.deny.

If only cron.deny exists and is empty, all users can use crontab. If neither file exists, only the root user can use crontab. The allow/deny files consist of one user name per line.


2. Crontab Commands



export EDITOR=vi ;to specify a editor to open crontab file.


crontab -e    Edit your crontab file, or create one if it doesn’t already exist.

crontab -l      Display your crontab file.

crontab -r      Remove your crontab file.

crontab -v      Display the last time you edited your crontab file. (This option is only available on a few systems.)



3. Crontab file

Crontab syntax :

A crontab file has five fields for specifying day , date and time followed by the command to be run at that interval.









*     *     *   *    *        command to be executed
-     -    -   -  -
|     |     |   |    |
|     |     |   |    +----- day of week (0 - 6) (Sunday=0)
|     |     |   +------- month (1 - 12)
|     |     +--------- day of month (1 - 31)
|     +----------- hour (0 - 23)
+------------- min (0 - 59)



* in the value field above means all legal values as in braces for that column.

The value column can have a * or a list of elements separated by commas. An element is either a number in the ranges shown above or two numbers in the range separated by a hyphen (meaning an inclusive range).

Notes

A. ) Repeat pattern like /2 for every 2 minutes or /10 for every 10 minutes is not supported by all operating systems. If you try to use it and crontab complains it is probably not supported.


B.) The specification of days can be made in two fields: month day and weekday. If both are specified in an entry, they are cumulative meaning both of the entries will get executed .


4. Crontab Example


A line in crontab file like below removes the tmp files from /home/someuser/tmp each day at 6:30 PM.


30     18     *     *     *         rm /home/someuser/tmp/*


Changing the parameter values as below will cause this command to run at different time schedule below :































































minhourday/monthmonthday/week Execution time
30011,6,12*– 00:30 Hrs  on 1st of Jan, June & Dec.
020*101-5–8.00 PM every weekday (Mon-Fri) only in Oct.
001,10,15**– midnight on 1st ,10th & 15th of month
5,10010*1– At 12.05,12.10 every Monday & on 10th of every month
:

Note : If you inadvertently enter the crontab command with no argument(s), do not attempt to get out with Control-d. This removes all entries in your crontab file. Instead, exit with Control-c.


5. Crontab Environment

cron invokes the command from the user’s HOME directory with the shell, (/usr/bin/sh).

cron supplies a default environment for every shell, defining:


HOME=user’s-home-directory

LOGNAME=user’s-login-id

PATH=/usr/bin:/usr/sbin:.

SHELL=/usr/bin/sh


Users who desire to have their .profile executed must explicitly do so in the crontab entry or in a script called by the entry.


6. Disable Email

By default cron jobs sends a email to the user account executing the cronjob. If this is not needed put the following command At the end of the cron job line .


>/dev/null 2>&1



7. Generate log file

To collect the cron execution execution log in a file :


30 18 * * * rm /home/someuser/tmp/* > /home/someuser/cronlogs/clean_tmp_dir.log

Javascript validation

I have posted the code of validate positive integer and floating point value in javascript.


You can remove condition parseInt(value)<=0 and parseFloat(value)<=0 respectively to allow positive as well negative integer and floating values to your customer.


function checkforInteger(value)

{

//alert(parseInt(value));

if (parseInt(value) != value || parseInt(value)<=0)

{

return false;

}

else

{

return true;

}

}

//Returns true if given input is valid float else return false

function checkforPrice(value)

{

if (isNaN(parseFloat(value)) || parseFloat(value)<=0)

{

return false;

}

else

{

return true;

}

}


Enjoy!

read xml php

I have posted the PHP code to read XML file.


Below is a sample XML file,


<?xml version="1.0" encoding="ISO-8859-1"?>

<note>

<to>Tove</to>

<from>Jani</from>

<heading>Reminder</heading>

<body>Don't forget me this weekend!</body>

</note>


<?php

$xml = simplexml_load_file("test.xml");


echo $xml->getName() . "<br />";


foreach($xml->children() as $child)

{

echo $child->getName() . ": " . $child . "<br />";

}

?>

Friday, June 3, 2011

Add image layer in photoshop with javascript

















Create Image Layer
I have just developed the code to add image as a layer in photoshop with the help of javascript

It is quite easy to do so, here is the code to work with







var fileRef = new File(app.path.toString() + "/Samples/test.jpg"); // 'samples' is a folder resides in Program Files\Adobe\Adobe Photoshop CS5\samples

//open (fileRef);

var doc = open(fileRef);

// get document name (and remove file extension)

var name = tempName[0];

// convert to RGB; convert to 8-bpc; merge visible

doc.changeMode(ChangeMode.RGB);

doc.bitsPerChannel = BitsPerChannelType.EIGHT;

doc.artLayers.add();

doc.mergeVisibleLayers();

// rename layer; duplicate to new document

var layer = doc.activeLayer;

layer.name = tempName[0];

layer.duplicate(newDoc, ElementPlacement.PLACEATBEGINNING);

// close imported document

doc.close(SaveOptions.DONOTSAVECHANGES);

Just go and try it.

Enjoy


Text Layer add in Photoshop with Javascript















Add Text Layer
I have just developed the code to add text layer in photoshop with the help of javascript

It is quite easy to do so, here is the code to work with


var docRef = activeDocument;

// Now create a text layer at the front
var myLayerRef = docRef.artLayers.add();
//myLayerRef.rotate (180)
myLayerRef.kind = LayerKind.TEXT;
myLayerRef.name = "Filename";

var myTextRef = myLayerRef.textItem;

// strip the extension off
var fileNameNoExtension = docRef.name;
fileNameNoExtension = fileNameNoExtension.split( "." );
if ( fileNameNoExtension.length > 1 ) {
fileNameNoExtension.length--;
}
fileNameNoExtension = fileNameNoExtension.join(".");

myTextRef.contents = tempName[5];

// off set the text to be in the middle
myTextRef.position = new Array( docRef.width / 2, docRef.height / 2 );
myTextRef.size = Number(tempName[7]);
myTextRef.font=tempName[6];
//myTextRef.underline.UnderlineType.UNDERLINELEFT;
//set position of text LINE NO 221
myTextRef.justification = Justification.CENTER;
myTextRef.kind = TextType.PARAGRAPHTEXT;
myTextRef.width= docRef.width;
myTextRef.height= docRef.height/ 2;
myTextRef.position= [Number(tempName[1]), Number(tempName[2])];


////////////////////// CODE TO ADD TEXT IN LAYER ENDS /////////////////////////


Just go and try it.

Enjoy

Read xml node and their attribute with javascript

























Javascript code to read XML file
I have just developed the code to read XML file node and their attributes with javascriptIt is quite easy to do so, here is the code to work with
XML file

<tempXml> <background> <backgroundImage isImage="true" url="1.jpg" height="600"

width="600" ind="0" xx="0" yy="0"/>

</background> <clipArts> <clipArt url="b.jpg" id="IDMon Mar 28 11:37:01 2011 UTC" ind="1" xx="300" yy="300"

imgType="clipArt"

height="150" width="150" itemType="imageType"/>

<clipArt url="a.jpg" id="IDMon Mar 28 11:37:01 2011 UTC" ind="2" xx="150" yy="250"

imgType="clipArt" itemType="imageType"

height="150" width="150"/>

<clipArt url="1290173945_4ce67df9514b6.jpg" ind="3"

id="IDMon Mar 28 11:37:01 2011 UTC" xx="100" yy="100" imgType="clipArt"

itemType="imageType" height="200" width="200"/>

</clipArts>

<images>

<image url="111.png" id="IDTue Mar 29 05:14:46 2011 UTC" ind="4" xx="150" yy="150"

imgType="image"

itemType="imageType" height="500" width="500"/>

<image url="112.png" id="IDTue Mar 29 05:14:46 2011 UTC" ind="5" xx="200" yy="200"

imgType="image"

itemType="imageType" height="400" width="400"/>

<image url="113.png" id="IDTue Mar 29 05:14:46 2011 UTC" ind="6"

xx="250" yy="250" imgType="image" itemType="imageType"

height="300" width="300"/>

</images>

<texts>

<text url="undefined" id="txt1" itemType="textType" text="TEST"

ind="8" font="Verdana" size="72" bold="false" italic="false"

underLine="false" textAllignment="0" color="255" backgroundColor="16777215" borderColor="16777215"

TextColor="undefined" xx="500" yy="200" alpha="undefined"

width="50" height="30" name="undefined"/>

<text url="undefined" id="txt1" itemType="textType" text="TEST!@" ind="7" font="Verdana"

size="72" bold="false" italic="false" underLine="false" textAllignment="0" color="255" backgroundColor="16777215"

borderColor="16777215" TextColor="undefined" xx="50" yy="50"

alpha="undefined" width="50" height="30" name="undefined"/>

</texts>

</tempXml>

Now to read this XML file you just need to use javascript code as below,







function getImageArray()
{
var f = new File('~/Desktop/test3.xml');
f.open('r');
var xml = new XML( f.read() );var imageArray=new Array();var background=xml.child('background') ;var imageNames=new Array();
imageArray[0]=background.backgroundImage.@url+"-"+background.backgroundImage.@xx
+"-"+background.backgroundImage.@yy
+"-"+background.backgroundImage.@height+"-"+background.backgroundImage.@width;
// CODE TO READ `IMAGES` TAG AND THEIR SUBNODE ATTRIBUTES STARTS //
var images=xml.child('images');var tempCount=images.elements().length();
var tempCnt=0;
for(var j=0;j {imageArray[images.image[j].@ind]=images.image[j].@url+"-"+images.image[j].@xx+"-"
+images.image[j].@yy
+"-"+images.image[j].@height+"-"+images.image[j].@width;

// new added code for the height and width ends //

// recently comment to merge everything in one element ends //
tempCnt=tempCnt+1;

}

// CODE TO READ `IMAGES` TAG AND THEIR SUBNODE ATTRIBUTES ENDS //
// CODE TO READ `CLIPART` TAG AND THEIR SUBNODE ATTRIBUTES STARTS //
var clipArts=xml.child('clipArts');
var tempCount=clipArts.elements().length();
for(var j=0;j {

imageArray[clipArts.clipArt[j].@ind]=clipArts.clipArt[j].@url+"-"+clipArts.clipArt[j].@xx+"-"
+clipArts.clipArt[j].@yy+"-"+clipArts.clipArt[j].@height+"-"+clipArts.clipArt[j].@width;
imageNames[tempCnt]=clipArts.clipArt[j].@url;

// recently comment to merge everything in one element ends //

}
// CODE TO READ `CLIPART` TAG AND THEIR SUBNODE ATTRIBUTES ENDS //
// CODE TO READ `TEXT` TAG AND THEIR SUBNODE ATTRIBUTES STARTS //

var texts=xml.child('texts');
var tempCount=texts.elements().length();
for(var j=0;j {

imageArray[texts.text[j].@ind]=texts.text[j].@url+"-"+texts.text[j].@xx+"-"+texts.text[j].@yy
+"-"+texts.text[j].@height+"-"+texts.text[j].@width+"-"+texts.text[j].@text+"-"+texts.text[j].@font
+"-"+texts.text[j].@size+"-"+texts.text[j].@bold+"-"+texts.text[j].@italic+"-"
+texts.text[j].@underLine+"-"+texts.text[j].@textAllignment+"-"+texts.text[j].@color+"-"
+texts.text[j].@backgroundColor+"-"+texts.text[j].@borderColor+"-"+texts.text[j].@TextColor;
imageNames[tempCnt]=texts.text[j].@url;

// recently comment to merge everything in one element ends //

}

// CODE TO READ `TEXT` TAG AND THEIR SUBNODE ATTRIBUTES ENDS //
return imageArray;
f.close();
}
getImageArray();

Enjoy

UPS address verification system(XAV)

Code to check about address validation for the UPS shipping.

Below code can be use to check whether customer shipping address is valid according to the UPS/USPS database or not.

//STREET LEVEL ADDRESS VARIFICATION REQUEST

$xmlRequest1='<?xml version="1.0"?>
<AccessRequest xml:lang="en-US">
<AccessLicenseNumber>ACCESS LICENCE NUMBER</AccessLicenseNumber>
<UserId>UPS USERNAME</UserId>
<Password>UPS PASSWORD</Password>
</AccessRequest>
<?xml version="1.0"?>
<AddressValidationRequest xml:lang="en-US">
<Request>
<TransactionReference>
<CustomerContext>Your Test Case Summary Description</CustomerContext>
<XpciVersion>1.0</XpciVersion>
</TransactionReference>
<RequestAction>XAV</RequestAction>
<RequestOption>3</RequestOption>
</Request>

<AddressKeyFormat>
<AddressLine>AIRWAY ROAD SUITE 7</AddressLine>
<PoliticalDivision2>SAN DIEGO</PoliticalDivision2>
<PoliticalDivision1>CA</PoliticalDivision1>
<PostcodePrimaryLow>92154</PostcodePrimaryLow>
<CountryCode>US</CountryCode>
</AddressKeyFormat>
</AddressValidationRequest>';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://wwwcie.ups.com/ups.app/xml/XAV");
// uncomment the next line if you get curl error 60: error setting certificate verify locations
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
// uncommenting the next line is most likely not necessary in case of error 60
// curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlRequest1);
curl_setopt($ch, CURLOPT_TIMEOUT, 3600);

//if ($this->logfile) {
// error_log("UPS REQUEST: " . $xmlRequest . "\n", 3, $this->logfile);
//}
echo $xmlResponse = curl_exec ($ch); // SHIP CONFIRMATION RESPONSE
$xml = $xmlResponse;

preg_match_all( "/\<AddressValidationResponse\>(.*?)\<\/AddressValidationResponse\>/s",
$xml, $upsRes );

foreach( $upsRes[1] as $res )
{
preg_match_all( "/\<ResponseStatusCode\>(.*?)\<\/ResponseStatusCode\>/",
$res, $response ); // XAV CODE


preg_match_all( "/\<ResponseStatusDescription\>(.*?)\<\/ResponseStatusDescription\>/",
$res, $responseMsg ); // XAV MESSAGE

preg_match_all( "/\<AddressLine\>(.*?)\<\/AddressLine\>/",
$res, $address ); // Possible Address Line

preg_match_all( "/\<Region\>(.*?)\<\/Region\>/",
$res, $Region ); // Possible region

preg_match_all( "/\<PoliticalDivision2\>(.*?)\<\/PoliticalDivision2\>/",
$res, $city );

preg_match_all( "/\<PoliticalDivision1\>(.*?)\<\/PoliticalDivision1\>/",
$res, $state );

preg_match_all( "/\<PostcodePrimaryLow\>(.*?)\<\/PostcodePrimaryLow\>/",
$res, $postCode );

preg_match_all( "/\<PostcodeExtendedLow\>(.*?)\<\/PostcodeExtendedLow\>/",
$res, $extenCode );

}
for($i=0;$i<count($address[1]);$i++)
{
echo $address[1][$i];
echo "<br>";
echo $Region[1][$i];
echo "<br>";
echo $city[1][$i];
echo "<br>";
echo $state[1][$i];
echo "<br>";
echo $postCode[1][$i];
echo "<br>";
echo $extenCode[1][$i];
echo "<br>";
echo "<hr>";
}

UPS shipping confirmation code in php

Here is the code to generate UPS digest which will use to generate UPS label<Br /><BR />

Replace credential detail with the correct one and use with your customer address details<br /><Br />
// SHIP CONFIRMATION REQUEST

$xmlRequest1='<?xml version="1.0"?>
<AccessRequest xml:lang="en-US">
<AccessLicenseNumber>ACCESS LICENCE NUMBER</AccessLicenseNumber>
<UserId>UPS USERNAME</UserId>
<Password>UPS PASSWORD</Password>
</AccessRequest>
<?xml version="1.0"?>
<ShipmentConfirmRequest xml:lang="en-US">
<Request>
<TransactionReference>
<CustomerContext>Customer Comment</CustomerContext>
<XpciVersion/>
</TransactionReference>
<RequestAction>ShipConfirm</RequestAction>
<RequestOption>validate</RequestOption>
</Request>
<LabelSpecification>
<LabelPrintMethod>
<Code>GIF</Code>
<Description>gif file</Description>
</LabelPrintMethod>
<HTTPUserAgent>Mozilla/4.5</HTTPUserAgent>
<LabelImageFormat>
<Code>GIF</Code>
<Description>gif</Description>
</LabelImageFormat>
</LabelSpecification>
<Shipment>
<RateInformation>
<NegotiatedRatesIndicator/>
</RateInformation>
<Description/>
<Shipper>
<Name>TEST</Name>
<PhoneNumber>111-111-1111</PhoneNumber>
<ShipperNumber>SHIPPER NUMBER</ShipperNumber>
<TaxIdentificationNumber>1234567890</TaxIdentificationNumber>
<Address>
<AddressLine1>AIRWAY ROAD SUITE 7</AddressLine1>
<City>SAN DIEGO</City>
<StateProvinceCode>CA</StateProvinceCode>
<PostalCode>92154</PostalCode>
<PostcodeExtendedLow></PostcodeExtendedLow>
<CountryCode>US</CountryCode>
</Address>
</Shipper>
<ShipTo>
<CompanyName>Yats</CompanyName>
<AttentionName>Yats</AttentionName>
<PhoneNumber>123.456.7890</PhoneNumber>
<Address>
<AddressLine1>AIRWAY ROAD SUITE 7</AddressLine1>
<City>SAN DIEGO</City>
<StateProvinceCode>CA</StateProvinceCode>
<PostalCode>92154</PostalCode>
<CountryCode>US</CountryCode>
</Address>
</ShipTo>
<ShipFrom>
<CompanyName>Ship From Company Name</CompanyName>
<AttentionName>Ship From Attn Name</AttentionName>
<PhoneNumber>1234567890</PhoneNumber>
<TaxIdentificationNumber>1234567877</TaxIdentificationNumber>
<Address>
<AddressLine1>AIRWAY ROAD SUITE 7</AddressLine1>
<City>SAN DIEGO</City>
<StateProvinceCode>CA</StateProvinceCode>
<PostalCode>92154</PostalCode>
<CountryCode>US</CountryCode>
</Address>
</ShipFrom>
<PaymentInformation>
<Prepaid>
<BillShipper>
<AccountNumber>SHIPPER NUMBER</AccountNumber>
</BillShipper>
</Prepaid>
</PaymentInformation>
<Service>
<Code>02</Code>
<Description>2nd Day Air</Description>
</Service>
<Package>
<PackagingType>
<Code>02</Code>
<Description>Customer Supplied</Description>
</PackagingType>
<Description>Package Description</Description>
<ReferenceNumber>
<Code>00</Code>
<Value>Package</Value>
</ReferenceNumber>
<PackageWeight>
<UnitOfMeasurement/>
<Weight>60.0</Weight>
</PackageWeight>
<LargePackageIndicator/>
<AdditionalHandling>0</AdditionalHandling>
</Package>
</Shipment>
</ShipmentConfirmRequest>
';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://wwwcie.ups.com/ups.app/xml/ShipConfirm");
// uncomment the next line if you get curl error 60: error setting certificate verify locations
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
// uncommenting the next line is most likely not necessary in case of error 60
// curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlRequest1);
curl_setopt($ch, CURLOPT_TIMEOUT, 3600);

//if ($this->logfile) {
// error_log("UPS REQUEST: " . $xmlRequest . "\n", 3, $this->logfile);
//}
echo $xmlResponse = curl_exec ($ch); // SHIP CONFORMATION RESPONSE
//echo curl_errno($ch);

$xml = $xmlResponse;

preg_match_all( "/\<ShipmentConfirmResponse\>(.*?)\<\/ShipmentConfirmResponse\>/s",
$xml, $bookblocks );

foreach( $bookblocks[1] as $block )
{
preg_match_all( "/\<ShipmentDigest\>(.*?)\<\/ShipmentDigest\>/",
$block, $author ); // SHIPPING DIGEST

//echo( $author[1][0]."\n" );
}

<br><br />
Enjoy!!!

PHP code to get UPS shipping rates

I have prepared this code to become helpfull for the developer who wants to integrate UPS in their customer website.

You just needs to make appropriate changes in credential detail and you are with the shipping rates.

//GET RATE FROM UPS API

$xmlRequest1='<?xml version="1.0"?>
<AccessRequest xml:lang="en-US">
<AccessLicenseNumber>ACCESSLICENCENUMBER</AccessLicenseNumber>
<UserId>USERID</UserId>
<Password>UPS PASSWORD</Password>
</AccessRequest>
<?xml version="1.0"?>
<RatingServiceSelectionRequest xml:lang="en-US">
<Request>
<TransactionReference>
<CustomerContext>Rating and Service</CustomerContext>
<XpciVersion>1.0</XpciVersion>
</TransactionReference>
<RequestAction>Rate</RequestAction>
<RequestOption>Rate</RequestOption>
</Request>
<PickupType>
<Code>07</Code>
<Description>Rate</Description>
</PickupType>
<Shipment>
<Description>Rate Description</Description>
<Shipper>
<Name>TEST</Name>
<PhoneNumber>888-748-7446</PhoneNumber>
<ShipperNumber>SHIPPER NUMBER</ShipperNumber>
<TaxIdentificationNumber>1234567877</TaxIdentificationNumber>
<Address>
<AddressLine1>AIRWAY ROAD SUITE 7</AddressLine1>
<City>SAN DIEGO</City>
<StateProvinceCode>CA</StateProvinceCode>
<PostalCode>92154</PostalCode>
<PostcodeExtendedLow></PostcodeExtendedLow>
<CountryCode>US</CountryCode>
</Address>
</Shipper>
<ShipTo>
<CompanyName>Yats</CompanyName>
<AttentionName>Yats</AttentionName>
<PhoneNumber>866.345.7638</PhoneNumber>
<Address>
<AddressLine1>AIRWAY ROAD SUITE 7</AddressLine1>
<City>SAN DIEGO</City>
<StateProvinceCode>CA</StateProvinceCode>
<PostalCode>92154</PostalCode>
<CountryCode>US</CountryCode>
</Address>
</ShipTo>
<ShipFrom>
<CompanyName>Ship From Company Name</CompanyName>
<AttentionName>Ship From Attn Name</AttentionName>
<PhoneNumber>1234567890</PhoneNumber>
<TaxIdentificationNumber>1234567877</TaxIdentificationNumber>
<Address>
<AddressLine1>AIRWAY ROAD SUITE 7</AddressLine1>
<City>SAN DIEGO</City>
<StateProvinceCode>CA</StateProvinceCode>
<PostalCode>92154</PostalCode>
<CountryCode>US</CountryCode>
</Address>
</ShipFrom>
<Service>
<Code>02</Code>
</Service>
<PaymentInformation>
<Prepaid>
<BillShipper>
<AccountNumber>Ship Number</AccountNumber>
</BillShipper>
</Prepaid>
</PaymentInformation>
<Package>
<PackagingType>
<Code>00</Code>
<Description>Customer Supplied</Description>
</PackagingType>
<Dimensions>
<UnitOfMeasurement>
<Code>IN</Code>
</UnitOfMeasurement>
<Length>30</Length>
<Width>34</Width>
<Height>34</Height>
</Dimensions>
<Description>Rate</Description>
<PackageWeight>
<UnitOfMeasurement>
<Code>LBS</Code>
</UnitOfMeasurement>
<Weight>150</Weight>
</PackageWeight>
</Package>
<ShipmentServiceOptions>
<OnCallAir>
<Schedule>
<PickupDay>02</PickupDay>
<Method>02</Method>
</Schedule>
</OnCallAir>
</ShipmentServiceOptions>
</Shipment>
</RatingServiceSelectionRequest>';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://wwwcie.ups.com/ups.app/xml/Rate");
// uncomment the next line if you get curl error 60: error setting certificate verify locations
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
// uncommenting the next line is most likely not necessary in case of error 60
// curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlRequest1);
curl_setopt($ch, CURLOPT_TIMEOUT, 3600);
echo $xmlResponse = curl_exec ($ch); // SHIP RATE RESPONSE

UPS label print with PHP

Code to print UPS label.


For generating UPS label you just need to pass shipping digest which you will get once you get ship confirmation response.


// SHIP ACCEPT REQUEST

$xmlRequest1='<?xml version="1.0" encoding="ISO-8859-1"?>

<AccessRequest>

<AccessLicenseNumber>ACCESS LICENCE NUMBER</AccessLicenseNumber>

<UserId>UPS USERNAME</UserId>

<Password>UPS PASSWORD</Password>

</AccessRequest>

<?xml version="1.0" encoding="ISO-8859-1"?>

<ShipmentAcceptRequest>

<Request>

<TransactionReference>

<CustomerContext>Customer Comment</CustomerContext>

</TransactionReference>

<RequestAction>ShipAccept</RequestAction>

<RequestOption>1</RequestOption>

</Request>

<ShipmentDigest>SHIPMENT DIGEST</ShipmentDigest>

</ShipmentAcceptRequest>

';


$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://wwwcie.ups.com/ups.app/xml/ShipAccept");

// uncomment the next line if you get curl error 60: error setting certificate verify locations

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

// uncommenting the next line is most likely not necessary in case of error 60

// curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($ch, CURLOPT_HEADER, 0);

curl_setopt($ch, CURLOPT_POST, 1);

curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlRequest1);

curl_setopt($ch, CURLOPT_TIMEOUT, 3600);


//if ($this->logfile) {

// error_log("UPS REQUEST: " . $xmlRequest . "\n", 3, $this->logfile);

//}

$xmlResponse = curl_exec ($ch); // SHIP ACCEPT RESPONSE

//echo curl_errno($ch);


$xml = $xmlResponse;


preg_match_all( "/\<ShipmentAcceptResponse\>(.*?)\<\/ShipmentAcceptResponse\>/s",

$xml, $bookblocks );


foreach( $bookblocks[1] as $block )

{

preg_match_all( "/\<GraphicImage\>(.*?)\<\/GraphicImage\>/",

$block, $author ); // GET LABEL


preg_match_all( "/\<TrackingNumber\>(.*?)\<\/TrackingNumber\>/",

$block, $tracking ); // GET TRACKING NUMBER

//echo( $author[1][0]."\n" );

}


echo '<img src="data:image/gif;base64,'. $author[1][0]. '"/>';

javascript validation for credit card

<!-- TWO STEPS TO INSTALL CREDIT CARD VALIDATION:


1. Copy the coding into the HEAD of your HTML document

2. Add the last code into the BODY of your HTML document -->


<!-- STEP ONE: Paste this code into the HEAD of your HTML document -->


<HEAD>


<SCRIPT LANGUAGE="JavaScript">


<!-- Begin

var Cards = new makeArray(8);

Cards[0] = new CardType("MasterCard", "51,52,53,54,55", "16");

var MasterCard = Cards[0];

Cards[1] = new CardType("VisaCard", "4", "13,16");

var VisaCard = Cards[1];

Cards[2] = new CardType("AmExCard", "34,37", "15");

var AmExCard = Cards[2];

Cards[3] = new CardType("DinersClubCard", "30,36,38", "14");

var DinersClubCard = Cards[3];

Cards[4] = new CardType("DiscoverCard", "6011", "16");

var DiscoverCard = Cards[4];

Cards[5] = new CardType("enRouteCard", "2014,2149", "15");

var enRouteCard = Cards[5];

Cards[6] = new CardType("JCBCard", "3088,3096,3112,3158,3337,3528", "16");

var JCBCard = Cards[6];

var LuhnCheckSum = Cards[7] = new CardType();


/*************************************************************************\

CheckCardNumber(form)

function called when users click the "check" button.

\*************************************************************************/

function CheckCardNumber(form) {

var tmpyear;

if (form.CardNumber.value.length == 0) {

alert("Please enter a Card Number.");

form.CardNumber.focus();

return;

}

if (form.ExpYear.value.length == 0) {

alert("Please enter the Expiration Year.");

form.ExpYear.focus();

return;

}

if (form.ExpYear.value > 96)

tmpyear = "19" + form.ExpYear.value;

else if (form.ExpYear.value < 21)

tmpyear = "20" + form.ExpYear.value;

else {

alert("The Expiration Year is not valid.");

return;

}

tmpmonth = form.ExpMon.options[form.ExpMon.selectedIndex].value;

// The following line doesn't work in IE3, you need to change it

// to something like "(new CardType())...".

// if (!CardType().isExpiryDate(tmpyear, tmpmonth)) {

if (!(new CardType()).isExpiryDate(tmpyear, tmpmonth)) {

alert("This card has already expired.");

return;

}

card = form.CardType.options[form.CardType.selectedIndex].value;

var retval = eval(card + ".checkCardNumber(\"" + form.CardNumber.value +

"\", " + tmpyear + ", " + tmpmonth + ");");

cardname = "";

if (retval)


// comment this out if used on an order form

alert("This card number appears to be valid.");


else {

// The cardnumber has the valid luhn checksum, but we want to know which

// cardtype it belongs to.

for (var n = 0; n < Cards.size; n++) {

if (Cards[n].checkCardNumber(form.CardNumber.value, tmpyear, tmpmonth)) {

cardname = Cards[n].getCardType();

break;

}

}

if (cardname.length > 0) {

alert("This looks like a " + cardname + " number, not a " + card + " number.");

}

else {

alert("This card number is not valid.");

}

}

}

/*************************************************************************\

Object CardType([String cardtype, String rules, String len, int year,

int month])

cardtype : type of card, eg: MasterCard, Visa, etc.

rules : rules of the cardnumber, eg: "4", "6011", "34,37".

len : valid length of cardnumber, eg: "16,19", "13,16".

year : year of expiry date.

month : month of expiry date.

eg:

var VisaCard = new CardType("Visa", "4", "16");

var AmExCard = new CardType("AmEx", "34,37", "15");

\*************************************************************************/

function CardType() {

var n;

var argv = CardType.arguments;

var argc = CardType.arguments.length;


this.objname = "object CardType";


var tmpcardtype = (argc > 0) ? argv[0] : "CardObject";

var tmprules = (argc > 1) ? argv[1] : "0,1,2,3,4,5,6,7,8,9";

var tmplen = (argc > 2) ? argv[2] : "13,14,15,16,19";


this.setCardNumber = setCardNumber; // set CardNumber method.

this.setCardType = setCardType; // setCardType method.

this.setLen = setLen; // setLen method.

this.setRules = setRules; // setRules method.

this.setExpiryDate = setExpiryDate; // setExpiryDate method.


this.setCardType(tmpcardtype);

this.setLen(tmplen);

this.setRules(tmprules);

if (argc > 4)

this.setExpiryDate(argv[3], argv[4]);


this.checkCardNumber = checkCardNumber; // checkCardNumber method.

this.getExpiryDate = getExpiryDate; // getExpiryDate method.

this.getCardType = getCardType; // getCardType method.

this.isCardNumber = isCardNumber; // isCardNumber method.

this.isExpiryDate = isExpiryDate; // isExpiryDate method.

this.luhnCheck = luhnCheck;// luhnCheck method.

return this;

}


/*************************************************************************\

boolean checkCardNumber([String cardnumber, int year, int month])

return true if cardnumber pass the luhncheck and the expiry date is

valid, else return false.

\*************************************************************************/

function checkCardNumber() {

var argv = checkCardNumber.arguments;

var argc = checkCardNumber.arguments.length;

var cardnumber = (argc > 0) ? argv[0] : this.cardnumber;

var year = (argc > 1) ? argv[1] : this.year;

var month = (argc > 2) ? argv[2] : this.month;


this.setCardNumber(cardnumber);

this.setExpiryDate(year, month);


if (!this.isCardNumber())

return false;

if (!this.isExpiryDate())

return false;


return true;

}

/*************************************************************************\

String getCardType()

return the cardtype.

\*************************************************************************/

function getCardType() {

return this.cardtype;

}

/*************************************************************************\

String getExpiryDate()

return the expiry date.

\*************************************************************************/

function getExpiryDate() {

return this.month + "/" + this.year;

}

/*************************************************************************\

boolean isCardNumber([String cardnumber])

return true if cardnumber pass the luhncheck and the rules, else return

false.

\*************************************************************************/

function isCardNumber() {

var argv = isCardNumber.arguments;

var argc = isCardNumber.arguments.length;

var cardnumber = (argc > 0) ? argv[0] : this.cardnumber;

if (!this.luhnCheck())

return false;


for (var n = 0; n < this.len.size; n++)

if (cardnumber.toString().length == this.len[n]) {

for (var m = 0; m < this.rules.size; m++) {

var headdigit = cardnumber.substring(0, this.rules[m].toString().length);

if (headdigit == this.rules[m])

return true;

}

return false;

}

return false;

}


/*************************************************************************\

boolean isExpiryDate([int year, int month])

return true if the date is a valid expiry date,

else return false.

\*************************************************************************/

function isExpiryDate() {

var argv = isExpiryDate.arguments;

var argc = isExpiryDate.arguments.length;


year = argc > 0 ? argv[0] : this.year;

month = argc > 1 ? argv[1] : this.month;


if (!isNum(year+""))

return false;

if (!isNum(month+""))

return false;

today = new Date();

expiry = new Date(year, month);

if (today.getTime() > expiry.getTime())

return false;

else

return true;

}


/*************************************************************************\

boolean isNum(String argvalue)

return true if argvalue contains only numeric characters,

else return false.

\*************************************************************************/

function isNum(argvalue) {

argvalue = argvalue.toString();


if (argvalue.length == 0)

return false;


for (var n = 0; n < argvalue.length; n++)

if (argvalue.substring(n, n+1) < "0" || argvalue.substring(n, n+1) > "9")

return false;


return true;

}


/*************************************************************************\

boolean luhnCheck([String CardNumber])

return true if CardNumber pass the luhn check else return false.


\*************************************************************************/

function luhnCheck() {

var argv = luhnCheck.arguments;

var argc = luhnCheck.arguments.length;


var CardNumber = argc > 0 ? argv[0] : this.cardnumber;


if (! isNum(CardNumber)) {

return false;

}


var no_digit = CardNumber.length;

var oddoeven = no_digit & 1;

var sum = 0;


for (var count = 0; count < no_digit; count++) {

var digit = parseInt(CardNumber.charAt(count));

if (!((count & 1) ^ oddoeven)) {

digit *= 2;

if (digit > 9)

digit -= 9;

}

sum += digit;

}

if (sum % 10 == 0)

return true;

else

return false;

}


/*************************************************************************\

ArrayObject makeArray(int size)

return the array object in the size specified.

\*************************************************************************/

function makeArray(size) {

this.size = size;

return this;

}


/*************************************************************************\

CardType setCardNumber(cardnumber)

return the CardType object.

\*************************************************************************/

function setCardNumber(cardnumber) {

this.cardnumber = cardnumber;

return this;

}


/*************************************************************************\

CardType setCardType(cardtype)

return the CardType object.

\*************************************************************************/

function setCardType(cardtype) {

this.cardtype = cardtype;

return this;

}


/*************************************************************************\

CardType setExpiryDate(year, month)

return the CardType object.

\*************************************************************************/

function setExpiryDate(year, month) {

this.year = year;

this.month = month;

return this;

}


/*************************************************************************\

CardType setLen(len)

return the CardType object.

\*************************************************************************/

function setLen(len) {

// Create the len array.

if (len.length == 0 || len == null)

len = "13,14,15,16,19";


var tmplen = len;

n = 1;

while (tmplen.indexOf(",") != -1) {

tmplen = tmplen.substring(tmplen.indexOf(",") + 1, tmplen.length);

n++;

}

this.len = new makeArray(n);

n = 0;

while (len.indexOf(",") != -1) {

var tmpstr = len.substring(0, len.indexOf(","));

this.len[n] = tmpstr;

len = len.substring(len.indexOf(",") + 1, len.length);

n++;

}

this.len[n] = len;

return this;

}


/*************************************************************************\

CardType setRules()

return the CardType object.

\*************************************************************************/

function setRules(rules) {

// Create the rules array.

if (rules.length == 0 || rules == null)

rules = "0,1,2,3,4,5,6,7,8,9";


var tmprules = rules;

n = 1;

while (tmprules.indexOf(",") != -1) {

tmprules = tmprules.substring(tmprules.indexOf(",") + 1, tmprules.length);

n++;

}

this.rules = new makeArray(n);

n = 0;

while (rules.indexOf(",") != -1) {

var tmpstr = rules.substring(0, rules.indexOf(","));

this.rules[n] = tmpstr;

rules = rules.substring(rules.indexOf(",") + 1, rules.length);

n++;

}

this.rules[n] = rules;

return this;

}

// End -->

</script>

</HEAD>


<!-- STEP TWO: Copy this code into the BODY of your HTML document -->


<BODY>


<center>

<form name="ThisForm">

Card Number: <input name="CardNumber" size="16" maxlength="19"><br>

Card Type:

<select name="CardType">

<option value="MasterCard">MasterCard

<option value="VisaCard">Visa

<option value="AmExCard">American Express

<option value="DinersClubCard">Diners Club

<option value="DiscoverCard">Discover

<option value="enRouteCard">enRoute

<option value="JCBCard">JCB

</select>

<br>

Expiration Date: Month

<select name="ExpMon">

<option value="1" selected>1

<option value="2">2

<option value="3">3

<option value="4">4

<option value="5">5

<option value="6">6

<option value="7">7

<option value="8">8

<option value="9">9

<option value="10">10

<option value="11">11

<option value="12">12

</select>

Year <input name="ExpYear" size="2" maxlength="2">(Range: 1997~2020)<br>

<input type="button" value="Check" OnClick="CheckCardNumber(this.form)"><br>

</form>

</center>

UPS tracking with php

Code to track shipped order.


Below code will help you to track your shipped order with UPS.


// UPS SHIP ORDER TRACKING

$xmlRequest1='<?xml version="1.0"?>

<AccessRequest xml:lang="en-US">

<AccessLicenseNumber>ACCESS LICENCE NUMBER</AccessLicenseNumber>

<UserId>UPS USERNAME</UserId>

<Password>UPS PASSWORD</Password>

</AccessRequest>

<?xml version="1.0"?>

<TrackRequest xml:lang="en-US">

<Request>

<TransactionReference>

<CustomerContext>Your Test Case Summary

Description</CustomerContext>

<XpciVersion>1.0</XpciVersion>

</TransactionReference>

<RequestAction>Track</RequestAction>

<RequestOption>activity</RequestOption>

</Request>

<TrackingNumber>W23WSDFFE23443</TrackingNumber>

</TrackRequest>';


$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://wwwcie.ups.com/ups.app/xml/Track");

// uncomment the next line if you get curl error 60: error setting certificate verify locations

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

// uncommenting the next line is most likely not necessary in case of error 60

// curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($ch, CURLOPT_HEADER, 0);

curl_setopt($ch, CURLOPT_POST, 1);

curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlRequest1);

curl_setopt($ch, CURLOPT_TIMEOUT, 3600);


//if ($this->logfile) {

// error_log("UPS REQUEST: " . $xmlRequest . "\n", 3, $this->logfile);

//}

echo $xmlResponse = curl_exec ($ch); // TRACKING RESPONSE

Read email from mail server in php

Below is a code to read your email within php file.


What you have to do is, change '$host' with your pop3 server, enter your email address and password in imap_open function and you are done with reading your email within your website.


// Change to your mail server

$host = "mail.XXXX.com";


// Connecting to POP3 email server.

$connection = imap_open("{" . $host . ":110/pop3/notls}", 'XXX@XXXX.com', 'XXXXX');


// Total number of messages in Inbox

$count = imap_num_msg($connection);

echo $count . " messages found<br />";


// Read Messages in Loop, Forward it to Actual User email and than delete it from current email account.

for ($i = 1; $i <= $count; $i++) {

$headers = imap_headerinfo($connection, $i);


$subject = $headers->subject;


$from = $headers->from[0]->mailbox . '@' . $headers->from[0]->host;

if ($headers->cc[0]->mailbox)

$cc = $headers->cc[0]->mailbox . '@' . $headers->cc[0]->host;

$subject = $headers->subject;


$structure = imap_fetchstructure($connection, $i);

//$type = $this->get_mime_type($structure);


// GET HTML BODY

// $body = $this->get_part($connection, $i, "");


echo $raw_body = imap_body($connection, $i);


$attachments = array();


if (isset($structure->parts) && count($structure->parts)) {

for ($e = 0; $e < count($structure->parts); $e++) {

$attachments[$e] = array('is_attachment' => false, 'filename' => '', 'name' => '', 'attachment' => '');


if ($structure->parts[$e]->ifdparameters) {

foreach ($structure->parts[$e]->dparameters as $object) {

if (strtolower($object->attribute) == 'filename') {

$attachments[$e]['is_attachment'] = true;

$attachments[$e]['filename'] = $object->value;

} //if (strtolower($object->attribute) == 'filename')

} //foreach ($structure->parts[$e]->dparameters as $object)

} //if ($structure->parts[$e]->ifdparameters)


if ($structure->parts[$e]->ifparameters) {

foreach ($structure->parts[$e]->parameters as $object) {

if (strtolower($object->attribute) == 'name') {

$attachments[$e]['is_attachment'] = true;

$attachments[$e]['name'] = $object->value;

} //if (strtolower($object->attribute) == 'name')

} //foreach ($structure->parts[$e]->parameters as $object)

} //if ($structure->parts[$e]->ifparameters)


if ($attachments[$e]['is_attachment']) {

$attachments[$e]['attachment'] = @imap_fetchbody($connection, $i, $e + 1);

if ($structure->parts[$e]->encoding == 3) {

// 3 = BASE64

$attachments[$e]['attachment'] = base64_decode($attachments[$e]['attachment']);

} //if ($structure->parts[$e]->encoding == 3)

elseif ($structure->parts[$e]->encoding == 4) {

// 4 = QUOTED-PRINTABLE

$attachments[$e]['attachment'] = quoted_printable_decode($attachments[$e]['attachment']);

} //elseif ($structure->parts[$e]->encoding == 4)

} //if ($attachments[$e]['is_attachment'])


if ($attachments[$e]['is_attachment']) {

$filename = $attachments[$e]['filename'];

$filename = $attachments[$e]['name'];

$filecontent = $attachments[$e]['attachment'];

} //if ($attachments[$e]['is_attachment'])

} //for ($e = 0; $e < count($structure->parts); $e++)

} //if (isset($structure->parts) && count($structure->parts))

/**** ****/


/*echo "<pre>";

echo "From: " . $headers->Unseen . "<br />";

echo "From: " . $from . "<br />";

echo "Cc: " . $cc . "<br />";

echo "Subject: " . $subject . "<br />";

echo "Content Type: " . $type . "<br />";

echo "Body: " . $body . "<br />";*/

$mail = new Zend_Mail();


$mail->settype(Zend_Mime::MULTIPART_MIXED);


for ($k = 0; $k < count($attachments); $k++) {

$filename = $attachments[$k]['name'];

$filecontent = $attachments[$k]['attachment'];


if ($filename && $filecontent) {

$file = $mail->createAttachment($filecontent);

$file->filename = $filename;

} //if ($filename && $filecontent)

} //for ($k = 0; $k < count($attachments); $k++)


$mail->setFrom($from);

$mail->addTo('XXX@XXXX.com');

if ($cc)

$mail->addCc($cc);

$mail->setSubject($subject);

$mail->setBodyHtml($body);

$mail->send();


// Mark the email messages once read

//imap_delete($mbox, 1);

} //for ($i = 1; $i <= $count; $i++)

// Delete all marked message from current email account.

imap_expunge($mbox);


Enjoy!!!

Tuesday, May 24, 2011

Paypal integration PHP