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!!!