Saturday, December 8, 2012

How to transfer files via SFTP in PHP

It's been a long time since my last post and good I'm back again. Anyway, below is my simple script to transfer files via SFTP in PHP. Hope this helps.

<?php

// set your sftp credential (host, port, username, password)
// local file (source file)
// remote file (destination file)


$host = '<host server to connect>';
$port = '<port to connect>';
$user = '<username to sftp>';
$pass = '<password to sftp>';
$lfile = '/path/to/local/file';
$rfile = '/path/to/remote/file';

// use ssh2 php module to connect

// if ssh2 is not installed/enable, please install/enable)
$connection = ssh2_connect($host, $port);
ssh2_auth_password($connection, $user, $pass);

// use sftp to connect
$sftp = ssh2_sftp($connection);

// open stream connection to remote server
$stream = @fopen('ssh2.sftp://'.$sftp.$rfile, 'w');

try {
    if (!$stream) throw new Exception("Could not open remote file: $rfile");

    // get data of the local file
    $data = @file_get_contents($lfile);
    if ($data === false) throw new Exception("Could not open local file: $lfile.");

    // write the data to stream remote file
    if (@fwrite($stream, $data) === false) throw new Exception("Could not send data from file: $lfile.");
    echo 'done!';

} catch (Exception $e) {
    // echo error message
    echo $e->getMessage();
}

// closing the stream
fclose($stream);

?>


Hope this helps and please leave a post if you like it. Thanks!!

Sunday, September 16, 2012

CSS 101: Display inline-block not working on IE

Below is a simple post to help you with your IE problem.

There's a problem on IE when displaying element as inline that works perfectly on other browser. On IE, it will only works on elements that are relatively inline like span element.

For inline to work on other elements with IE, you just need to put safe on your display then set the zoom to 1. Please see tricks below.

.yourelement {
   display: inline-block;
   *display: inline;
   zoom:1;
}


Hope this helps on your IE issues. Happy coding!!

Sunday, August 12, 2012

How to get Longitude / Latitude in PHP using Google Maps API

This post is just a simple script I did, built in PHP that will get the coordinates of specific location.

The script uses google maps web service that returns XML data in which we need parse to get the information we need.

Take note also of the URL I used, you just need to add your google maps key.
http://maps.google.com/maps/geo?output=xml&oe=utf-8&key=enter+your+key+here&q=enter+your+query+here

<?php

$key = 'AIzaSyCrPl5vXuNjPU1fgHF69YPxEopT_NziA4o'; // your google maps key
$param = 'T2G 0S7'; // the location you want to look for, this can be postal code, map id, address, etc.

$geoinfo = get_longlat($key, $param);
var_dump($geoinfo);

function get_longlat($key='', $param='') {
        $request_url = "http://maps.google.com/maps/geo?output=xml&key=$key&oe=utf-8&q=".urlencode($param);
        $xml = simplexml_load_file($request_url);

        $geoinfo = array();
        if (!empty($xml->Response)) {
                $point = $xml->Response->Placemark->Point;
                if (!empty($point)) {
                        $coordinates = explode(",", $point->coordinates);
                        $geoinfo = array(
                                'lon' => $coordinates[0],
                                'lat' => $coordinates[1]
                        );
                }
        }

        return $geoinfo;
}

?>

You can also get other information by parsing the XML returned by the google maps web service. Please see below for the sample XML return.

<kml>
<Response>
    <name>t2g 0s7</name>
    <Status>
        <code>200</code>
        <request>geocode</request>
    </Status>
    <Placemark id="p1">
        <address>Calgary, AB T2G 0S7, Canada</address>
        <AddressDetails Accuracy="5">
            <Country>
                <CountryNameCode>CA</CountryNameCode>
                <CountryName>Canada</CountryName>
                <AdministrativeArea>
                    <AdministrativeAreaName>AB</AdministrativeAreaName>
                    <Locality>
                        <LocalityName>Calgary</LocalityName>
                        <PostalCode>
                            <PostalCodeNumber>T2G 0S7</PostalCodeNumber>
                        </PostalCode>
                    </Locality>
                </AdministrativeArea>
            </Country>
        </AddressDetails>
        <ExtendedData>
            <LatLonBox north="51.0439997" south="51.0413017" east="-114.0367519" west="-114.0394858"/>
        </ExtendedData>
        <Point>
            <coordinates>-114.0380127,51.0426718,0</coordinates>
        </Point>
    </Placemark>
</Response>
</kml>

Saturday, July 21, 2012

Setting up shadow boxes on your website.

This is just a short post for you to put shadow inside and outside of your website's page elements such as input text box, text area, buttons, images, etc..

Inside Shadows:

.in-shadow {
        box-shadow: inset 1px 1px 1px #a2a2a2;
        -moz-box-shadow: inset 1px 1px 1px #a2a2a2;
        -webkit-box-shadow: inset 1px 1px 1px #a2a2a2;
}


Outside Shadows:

.out-shadow {
        box-shadow: inset 1px 1px 1px #a2a2a2;
        -moz-box-shadow: inset 1px 1px 1px #a2a2a2;
        -webkit-box-shadow: inset 1px 1px 1px #a2a2a2;
}


Hope you like this. Happy coding!!

Thursday, July 19, 2012

iContact API Integration on PHP

This post will teach you how to integrate your app with iContact. The API requires JSON for doing requests and responses. On this implementation, I used CURL which I commonly use when doing API call.

First thing we need to do is to register on iContact then get an API credential. Register your app and get your application id, folder id, username and password - https://app.icontact.com/icp/core/registerapp

Once we have all the credentials, we are now ready to start building our codes.

First, we need to create a function that we will commonly use such as the headers, please see function I created for setting the headers.

function set_headers($app_id, $user, $pass) {
        $headers = array(
                'Accept: application/json',
                'Content-Type: application/json',
                'Api-Version: 2.0',
                'Api-AppId: ' . $app_id,
                'Api-Username: ' . $user,
                'Api-Password: ' . $pass
        );

        return $headers;


Next is to get information from our iContact account. Since we need the account id for all our API call, we will first request for our account information.

This function will return JSON response which we need to parse to get the information we need.

$app_id = '<put your app id>';
$user = '<put your username/email address>';
$pass = '<put your password>';
$folder_id = '<put your folder id>';

$data = get_account_info($app_id, $user, $pass);
var_dump($data);

function get_account_info($app_id, $user, $pass) {
        $headers = set_headers($app_id, $user, $pass);

        $ch = curl_init("https://app.icontact.com/icp/a");
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $json = curl_exec($ch);

        if (curl_errno($ch)) echo curl_error($ch);
        curl_close($ch);

        return $json;
}


Sample output will be like this, which is a JSON response.

string(582) "{"accounts":[{"billingStreet":"","billingCity":"","billingState":"","billingPostalCode":"","billingCountry":"","city":"Caloocan","accountId":"#######","companyName":"Hotshots Point of View","country":"Philippines","email":"paulgonzaga80@gmail.com","enabled":"1","fax":"","firstName":"Paul","lastName":"Gonzaga","multiClientFolder":"0","multiUser":"0","phone":"639213189673","postalCode":"1421","state":"NCR","street":"#409 B1 L5, Bagumbong Itaas, Progressive Village, Novaliches Caloocan City1","title":"","accountType":"1","subscriberLimit":"500"}],"total":1,"limit":20,"offset":0}"

This will return our account information which we will use for other API call. Once we have the Account ID, we can call now our client folders, though we get it already upon registration but just for the benefit of this post, we will try to get it via API call. The parameters we passed on this function is came from above call and credentials.

$data = json_decode($data);
$account_id = $data->accounts[0]->accountId;

$data = get_client_folders($app_id, $user, $pass, $account_id);
var_dump($data);

function get_client_folders($app_id, $user, $pass, $account_id) {
        $headers = set_headers($app_id, $user, $pass);

        $ch = curl_init("https://app.icontact.com/icp/a/$account_id/c/");
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $json = curl_exec($ch);

        if (curl_errno($ch)) echo curl_error($ch);
        curl_close($ch);

        return $json;
}


Sample output will be like this which is the same folder id when we do our registration.

string(69) "{"clientfolders":[{"clientFolderId":"####","logoId":null}],"total":1}"

After this, we can now proceed adding contact, getting contact information, list all our contacts, subscriptions, etc..

The sample script I made below will help you be able to move forward with other functions. Happy coding!!

<?php

$app_id = '<put your app id>';
$user = '<put your username/email address>';
$pass = '<put your password>';
$folder_id = '<put your folder id>';

$data = get_account_info($app_id, $user, $pass);
var_dump($data);

$data = json_decode($data);
$account_id = $data->accounts[0]->accountId;

$data = get_client_folders($app_id, $user, $pass, $account_id);
var_dump($data);


function set_headers($app_id, $user, $pass) {
        $headers = array(
                'Accept: application/json',
                'Content-Type: application/json',
                'Api-Version: 2.0',
                'Api-AppId: ' . $app_id,
                'Api-Username: ' . $user,
                'Api-Password: ' . $pass
        );

        return $headers;
}

function get_account_info($app_id, $user, $pass) {
        $headers = set_headers($app_id, $user, $pass);

        $ch = curl_init("https://app.icontact.com/icp/a");
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $json = curl_exec($ch);

        if (curl_errno($ch)) echo curl_error($ch);
        curl_close($ch);

        return $json;
}

function get_client_folders($app_id, $user, $pass, $account_id) {
        $headers = set_headers($app_id, $user, $pass);

        $ch = curl_init("https://app.icontact.com/icp/a/$account_id/c/");
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $json = curl_exec($ch);

        if (curl_errno($ch)) echo curl_error($ch);
        curl_close($ch);

        return $json;
}

function add_contact($app_id, $user, $pass, $account_id, $folder_id, $email, $fname, $lname, $status='normal') {
        $headers = set_headers($app_id, $user, $pass);

        $data = array(
                'contact' => array(
                        'email'         => $email,
                        'firstName'     => $fname,
                        'lastName'      => $lname,
                        'status'        => $status
                )
        );

        $data = json_encode($data);

        $ch = curl_init("https://app.icontact.com/icp/a/$account_id/c/$folder_id/contacts/");
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $json = curl_exec($ch);

        if (curl_errno($ch)) echo curl_error($ch);
        curl_close($ch);

        return $json;
}

function get_contact_info($app_id, $user, $pass, $account_id, $folder_id, $email) {
        $headers = set_headers($app_id, $user, $pass);

        $ch = curl_init("https://app.icontact.com/icp/a/$account_id/c/$folder_id/contacts/?email=".urlencode($email));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $json = curl_exec($ch);

        if (curl_errno($ch)) echo curl_error($ch);
        curl_close($ch);

        return $json;
}

function get_contact_info_by_id($app_id, $user, $pass, $account_id, $folder_id, $contact_id) {
        $headers = set_headers($app_id, $user, $pass);

        $ch = curl_init("https://app.icontact.com/icp/a/$account_id/c/$folder_id/contacts/?contactId=".urlencode($contact_id));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $json = curl_exec($ch);

        if (curl_errno($ch)) echo curl_error($ch);
        curl_close($ch);

        return $json;
}

function list_contacts($app_id, $user, $pass, $account_id, $folder_id) {
        $headers = set_headers($app_id, $user, $pass);

        $ch = curl_init("https://app.icontact.com/icp/a/$account_id/c/$folder_id/contacts/");
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $json = curl_exec($ch);

        if (curl_errno($ch)) echo curl_error($ch);

        if (curl_errno($ch)) echo curl_error($ch);
        curl_close($ch);

        return $json;
}

function subscribe($app_id, $user, $pass, $account_id, $folder_id, $email, $list_id) {
        $json = get_contact_info($app_id, $user, $pass, $account_id, $folder_id, $email);
        $obj = json_decode($json);
        $contact_id = $obj->contacts[0]->contactId;

        $headers = set_headers($app_id, $user, $pass);

        $data = array(
                'subscription' => array(
                        'contactId'     => $contact_id,
                        'listId'        => $list_id,
                        'status'        => 'normal'
                )
        );

        $data = json_encode($data);

        $ch = curl_init("https://app.icontact.com/icp/a/$account_id/c/$folder_id/subscriptions/");
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $json = curl_exec($ch);

        if (curl_errno($ch)) echo curl_error($ch);
        curl_close($ch);

        return $json;
}

function unsubscribe($app_id, $user, $pass, $account_id, $folder_id, $email, $list_id) {
        $json = get_contact_info($app_id, $user, $pass, $account_id, $folder_id, $email);
        $obj = json_decode($json);
        $contact_id = $obj->contacts[0]->contactId;

        $headers = set_headers($app_id, $user, $pass);

        $data = array(
                'subscription' => array(
                        'contactId'     => $contact_id,
                        'listId'        => $list_id,
                        'status'        => 'unsubscribed'
                )
        );

        $data = json_encode($data);

        $ch = curl_init("https://app.icontact.com/icp/a/$account_id/c/$folder_id/subscriptions/");
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $json = curl_exec($ch);

        if (curl_errno($ch)) echo curl_error($ch);
        curl_close($ch);

        return $json;
}

function list_subscribers($app_id, $user, $pass, $account_id, $folder_id) {
        $headers = set_headers($app_id, $user, $pass);

        $ch = curl_init("https://app.icontact.com/icp/a/$account_id/c/$folder_id/subscriptions/");
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $json = curl_exec($ch);

        if (curl_errno($ch)) echo curl_error($ch);
        curl_close($ch);

        return $json;
}


?>

Thursday, July 12, 2012

Freshbooks API Integration on PHP

This post will teach you how to integrate your website with Freshbooks API. There is actually two ways of integrating with Freshbooks, one is via OAuth and the other one is Token-Based method.

For the Token-Based method, this is very simple. You only need to compose an XML request, use your API url and Token from Freshbooks - http://developers.freshbooks.com, then use curl to execute the request. You can check out below on how I do it by calling create client and list clients request.

<?php

$apiurl = 'https://sample.freshbooks.com/api/2.1/xml-in';
$token = '<your token here>';

create_client($apiurl, $token);
list_clients($apiurl, $token);

function create_client($apiurl='', $token='') {
        $xmldata = "<?xml version=\"1.0\" encoding=\"utf-8\"?>
                <request method=\"client.create\">
                <client>
                        <first_name>Jane</first_name>
                        <last_name>Doe</last_name>
                        <organization>ABC Corp5</organization>
                        <email>janedoe@freshbooks.com</email>
                </client>
                </request>";

        $output = xml_request($apiurl, $token, $xmldata);
        var_dump($output);
}

function list_clients($apiurl='', $token='') {
        $xmldata = "<?xml version=\"1.0\" encoding=\"utf-8\"?>
                <request method=\"client.list\">
                        <folder>active</folder>
                </request>";

        $output = xml_request($apiurl, $token, $xmldata);
        var_dump($output);
}

function xml_request($apiurl='', $token='', $xmldata='') {
        $output = '';

        system("curl -u $token:X $apiurl -d '$xmldata'", $output);
        return $output;
}

?>


For the OAuth method, this is pretty much complex than the Token-Based method. Please see below on the implementation I did. I also use plaintext signature method, the same method I used on my previous post - Dropbox OAuth API Integration on PHP

The first and important thing we need to have is the App key and App secret which we will use for authentication. I believed you will need an approval from Freshbooks to be able to get this information.

Once we have these credentials, we are now ready to start the coding part.

To start with, since we will be posting request to API url, I created a function in doing post request. We will be using this for request token and access token process.

function post_request($url='', $param='') {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_VERBOSE, 1);

        // disable ssl verification
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);

        // submit post request parameters
        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);

        // getting response from server
        $output = curl_exec($ch);

        return $output;
}


Now we can start requesting for a token. On this request, we need the callback url for freshbooks to redirect after the authorization was made. Once we get the token, we will submit it to authorization url for users to authorize our application.

$key = '<your oauth key here>';
$secret = '<your oauth secret here>';

// call request token here and pass the App key and App secret
request_token($key, $secret);

function request_token($key='', $secret='') {
        $timestamp = time();
        $nonce = md5(time());
                $key = $this->data['key'];
                $secret = $this->data['secret'];
        $sig = $secret."%26";
        $method = "PLAINTEXT";

        $callback = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; // put your callback url
        $url = "https://$key.freshbooks.com/oauth/oauth_request.php";
        $param = "oauth_consumer_key=$key".
                 "&oauth_signature_method=$method".
                 "&oauth_signature=$sig".
                 "&oauth_timestamp=$timestamp".
                 "&oauth_nonce=$nonce".
                 "&oauth_version=1.0".
                 "&oauth_callback=$callback";

        $output = $this->post_request($url, $param);

        // parse the output
        parse_str($output, $token);

        // save to session
        $_SESSION['oauth_token'] = $token['oauth_token'];
        $_SESSION['token_secret'] = $token['oauth_token_secret'];



        // redirect to authorize url
        authorize($key);
}


After getting a token from request token url, we can redirect the users to authorize url with the oauth token we get from request token.

function authorize($key='') {
        $oauth_token = $_SESSION['oauth_token'];

        $url = "https://$key.freshbooks.com/oauth/oauth_authorize.php";
        $param = "oauth_token=$oauth_token";

        header("Location: $url?$param");
}


Once the user allow the application to access the users information, Freshbooks will redirect the users to the callback url we put in our request token function. The callback url should be our access token function to get the access token that we can use moving forward.

$key = '<your oauth key here>';
$secret = '<your oauth secret here>';

// call access token request passing the App key and App secret parameters
access_token($key, $secret);

function access_token($key='', $secret='') {
        $oauth_token = ($_GET['oauth_token']) ? $_GET['oauth_token'] : $_SESSION['oauth_token'];
        $oauth_verifier = $_GET['oauth_verifier'];
        $token_secret = $_SESSION['token_secret'];

        $timestamp = time();
        $nonce = md5(time());
        $sig = $secret."%26".$token_secret;
        $method = "PLAINTEXT";

        $url = "https://$key.freshbooks.com/oauth/oauth_access.php";
        $param = "oauth_consumer_key=$key".
                 "&oauth_token=$oauth_token".
                 "&oauth_signature_method=$method".
                 "&oauth_signature=$sig".
                 "&oauth_timestamp=$timestamp".
                 "&oauth_nonce=$nonce".
                 "&oauth_version=1.0".
                 "&oauth_verifier=$oauth_verifier";

        $output = post_request($url, $param);

        // parse the output
        parse_str($output, $token);

        // save to session
        $_SESSION['oauth_token'] = $token['oauth_token'];
        $_SESSION['token_secret'] = $token['oauth_token_secret'];
}


We need to save the oauth token and oauth token secret for api call. Please watch out for my next post, I'll be posting on how to do the API call using OAuth method. Check out below script for the full implementation of the freshbooks authentication.

<?php

session_start();

$key = '<your oauth key here>';
$secret = '<your oauth secret here>';

// from callback
$oauth_token = $_GET['oauth_token'];
if ($oauth_token) {
        access_token($key, $secret);
} else {
        request_token($key, $secret);
}

function request_token($key='', $secret='') {
        $timestamp = time();
        $nonce = md5(time());
                $key = $this->data['key'];
                $secret = $this->data['secret'];
        $sig = $secret."%26";
        $method = "PLAINTEXT";

        $callback = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; // put your callback url
        $url = "https://$key.freshbooks.com/oauth/oauth_request.php";
        $param = "oauth_consumer_key=$key".
                 "&oauth_signature_method=$method".
                 "&oauth_signature=$sig".
                 "&oauth_timestamp=$timestamp".
                 "&oauth_nonce=$nonce".
                 "&oauth_version=1.0".
                 "&oauth_callback=$callback";

        $output = $this->post_request($url, $param);

        // parse the output
        parse_str($output, $token);

        // save to session
        $_SESSION['oauth_token'] = $token['oauth_token'];
        $_SESSION['token_secret'] = $token['oauth_token_secret'];

        authorize($key);
}

function authorize($key='') {
        $oauth_token = $_SESSION['oauth_token'];

        $url = "https://$key.freshbooks.com/oauth/oauth_authorize.php";
        $param = "oauth_token=$oauth_token";

        header("Location: $url?$param");
}

function access_token($key='', $secret='') {
        $oauth_token = ($_GET['oauth_token']) ? $_GET['oauth_token'] : $_SESSION['oauth_token'];
        $oauth_verifier = $_GET['oauth_verifier'];
        $token_secret = $_SESSION['token_secret'];

        $timestamp = time();
        $nonce = md5(time());
        $sig = $secret."%26".$token_secret;
        $method = "PLAINTEXT";

        $url = "https://$key.freshbooks.com/oauth/oauth_access.php";
        $param = "oauth_consumer_key=$key".
                 "&oauth_token=$oauth_token".
                 "&oauth_signature_method=$method".
                 "&oauth_signature=$sig".
                 "&oauth_timestamp=$timestamp".
                 "&oauth_nonce=$nonce".
                 "&oauth_version=1.0".
                 "&oauth_verifier=$oauth_verifier";

        $output = post_request($url, $param);

        // parse the output
        parse_str($output, $token);

        // save to session
        $_SESSION['oauth_token'] = $token['oauth_token'];
        $_SESSION['token_secret'] = $token['oauth_token_secret'];

        var_dump($_SESSION);
}

?>

Saturday, July 7, 2012

Dropbox OAuth API Integration on PHP

This post will teach you how to integrate with Dropbox OAuth using PHP platform. Please take note that I'm not using any library to perform this integration nor special coding or whatsoever.

This is basically built from scratch which I want to share with you all, who wish to integrate with Dropbox.

To start with, you need an API credentials which you can get by logging in to your Dropbox account and create an app on this url - https://www.dropbox.com/developers/apps

We need the credentials below to proceed:
  • App key
  • App secret
We also need to understand the 3 url's that we need to access to complete the authentication process as listed below.
The request token url will be use to get a token which will be use to authorize your app to access users information in their behalf.

The authorization url will be the page for users to allow our application to access the users credential.

The access token url will be use to get an access token which will be use to access users credentials in their behalf.

Another thing that we need to understand is how to create signature. We need this in performing oauth request.

For the sake of this post, we will use the PLAINTEXT signature method, which is the simplest signature method.

Once we have the credentials and the api url's, we are now ready to start by just following the simple steps below.

1. Lets request for a token from the request token url - https://api.dropbox.com/1/oauth/request_token. Since we are using plaintext signature method, the signature will be your app secret plus "%26". Please see below.

$key = '<your app key>';
$secret = '<your app secret>';
$timestamp = time();$nonce = md5(time());
$sig = $secret."%26";
$method = "PLAINTEXT";


2. Once we have all the parameters, lets compose the post request.

$url = "https://api.dropbox.com/1/oauth/request_token";
$param = "oauth_consumer_key=$key".
                "&oauth_signature_method=$method".
                "&oauth_signature=$sig".
                "&oauth_timestamp=$timestamp".
                "&oauth_nonce=$nonce".
                "&oauth_version=1.0";


3. Execute post request using curl, which is the basic command in performing post request.

$ch = curl_init();
           
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_VERBOSE, 1);

// disable ssl verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);

// submit post request parameters
curl_setopt($ch, CURLOPT_POSTFIELDS, $param);

// getting response from server
$output = curl_exec($ch);


4. Parse the output and you will get the "oauth_token" and "oauth_token_secret" below which will be use to perform authorization. You can save these information in your session so that you will retrieve it later when performing access token.

// parse the output
parse_str($output, $token);

// save to session
$_SESSION['oauth_token'] = $token['oauth_token'];
$_SESSION['token_secret'] = $token['oauth_token_secret'];


5. From the step #4, we only need the "oauth_token" to request for authorization. For this process, we need to define our callback url in which Dropbox will redirect the users after allowing the access.

$oauth_token = $_SESSION['oauth_token'];
$callback = '<your callback url>';

$url = "https://www.dropbox.com/1/oauth/authorize";
$param = "oauth_token=$oauth_token".
                "&oauth_callback=$callback";

header("Location: $url?$param");


6. After the user allows our application, Dropbox will redirect the user to our callback url we specify on step #5. We need to submit post request to access token url with the parameter "oauth_token" from step #4. This will also require signature, the same way we did on request token process, but this time with extra parameter "oauth_token_secret" from step #4.

$oauth_token = $_SESSION['oauth_token'];
$token_secret = $_SESSION['token_secret'];

$key = '<your app key>';
$secret = '<your app secret>';
$timestamp = time();$nonce = md5(time());
$sig = $secret."%26".$token_secret;
$method = "PLAINTEXT";


7. Lets compose the url and parameter with "oauth_token" as part of the request.

$url = "https://api.dropbox.com/1/oauth/access_token";
$param = "oauth_consumer_key=$key".
                "&oauth_token=$oauth_token".
                "&oauth_signature_method=$method".
                "&oauth_signature=$sig".
                "&oauth_timestamp=$timestamp".
                "&oauth_nonce=$nonce".
                "&oauth_version=1.0";


8. Execute the post request using curl.

$ch = curl_init();
           
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_VERBOSE, 1);

// disable ssl verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);

// submit post request parameters
curl_setopt($ch, CURLOPT_POSTFIELDS, $param);

// getting response from server
$output = curl_exec($ch);


9. Parse the output and we will get an access token which we will use to do the api request. You can save these information in your database so that you won't need to request for authorization when doing api request.

// parse the output
parse_str($output, $token);

// save to session
$_SESSION['oauth_token'] = $token['oauth_token'];
$_SESSION['token_secret'] = $token['oauth_token_secret'];


You can try the full script below I made with a live API account and a basic API request. I optimized the script as well for better coding.

<?php

session_start();

$key = 'vh096l7q9m5m8tv'; // put here your app key
$secret = 'omri1uakcak8zqz'; // put here your app secret

// from callback
$oauth_token = $_GET['oauth_token'];
if ($oauth_token) {
        access_token($key, $secret);
} else {
        request_token($key, $secret);
}

function request_token($key='', $secret='') {
        $timestamp = time();
        $nonce = md5(time());
        $sig = $secret."%26";
        $method = "PLAINTEXT";

        $url = "https://api.dropbox.com/1/oauth/request_token";
        $param = "oauth_consumer_key=$key".
                 "&oauth_signature_method=$method".
                 "&oauth_signature=$sig".
                 "&oauth_timestamp=$timestamp".
                 "&oauth_nonce=$nonce".
                 "&oauth_version=1.0";

        $output = post_request($url, $param);

        // parse the output
        parse_str($output, $token);

        // save to session
        $_SESSION['oauth_token'] = $token['oauth_token'];
        $_SESSION['token_secret'] = $token['oauth_token_secret'];

        authorize();
}

function authorize() {
        $oauth_token = $_SESSION['oauth_token'];
        $callback = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; // put your callback url

        $url = "https://www.dropbox.com/1/oauth/authorize";
        $param = "oauth_token=$oauth_token".
                 "&oauth_callback=$callback";

        header("Location: $url?$param");
}

function access_token($key='', $secret='') {
        $oauth_token = $_SESSION['oauth_token'];
        $token_secret = $_SESSION['token_secret'];

        $timestamp = time();
        $nonce = md5(time());
        $sig = $secret."%26".$token_secret;
        $method = "PLAINTEXT";

        $url = "https://api.dropbox.com/1/oauth/access_token";
        $param = "oauth_consumer_key=$key".
                 "&oauth_token=$oauth_token".
                 "&oauth_signature_method=$method".
                 "&oauth_signature=$sig".
                 "&oauth_timestamp=$timestamp".
                 "&oauth_nonce=$nonce".
                 "&oauth_version=1.0";

        $output = post_request($url, $param);

        // parse the output
        parse_str($output, $token);

        // save to session
        $_SESSION['oauth_token'] = $token['oauth_token'];
        $_SESSION['token_secret'] = $token['oauth_token_secret'];

        folders($key, $secret);
}

function folders($key='', $secret='') {
        $oauth_token = $_SESSION['oauth_token'];
        $token_secret = $_SESSION['token_secret'];

        $timestamp = time();
        $nonce = md5(time());
        $sig = $secret."%26".$token_secret;
        $method = "PLAINTEXT";

        $url = "https://api.dropbox.com/1/metadata/dropbox";
        $param = "oauth_consumer_key=$key".
                 "&oauth_token=$oauth_token".
                 "&oauth_signature_method=$method".
                 "&oauth_signature=$sig".
                 "&oauth_timestamp=$timestamp".
                 "&oauth_nonce=$nonce".
                 "&oauth_version=1.0";

        $output = file_get_contents($url."?".$param);
        $jsondata = json_decode($output);

        foreach ($jsondata->contents as $contents) {
                echo $contents->path."<br/>";
        }
}

function post_request($url='', $param='') {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_VERBOSE, 1);

        // disable ssl verification
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);

        // submit post request parameters
        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);

        // getting response from server
        $output = curl_exec($ch);

        return $output;
}

?>


Sunday, July 1, 2012

Integration with Paypal on PHP

This post will teach you how to to integrate your website with paypal and hope I was able to guide you well.

To start with, you need to apply for a Paypal account. If you just want a test account, you can register for a sandbox account - http://www.sandbox.paypal.com

We need the following account details below:
  • Username
  • Password
  • API Signature
Once you have all the details, we can now do the coding part. Aside from account details, you also need to know the endpoint url and the paypal callback url. Please see details below.

Live:
  • Endpoint - https://api-3t.paypal.com/nvp
  • Callback - https://www.paypal.com/webscr&cmd=_express-checkout&token=
Sandbox:
  • Endpoint - https://api-3t.sandbox.paypal.com/nvp
  • Callback - https://www.sandbox.paypal.com/webscr&cmd=_express-checkout&token=
Just to get us going, please see below code snippet for checking the environment and initiate the details.

// set up your environment - live or sandbox
$live = "true";

if ($live == "true") {
        // live account details
        $username = 'paypal live username';
        $password = 'paypal live password';
        $signature = 'paypal live api signature';
        $endpoint = "https://api-3t.paypal.com/nvp";
        $url = "https://www.paypal.com/webscr&cmd=_express-checkout&token=";
} else {
        // sandbox account details
        $username = 'paypal sandbox username';
        $password = 'paypal sandbox password';
        $signature = 'paypal sandbox api signature';
        $endpoint = "https://api-3t.sandbox.paypal.com/nvp";
        $url = "https://www.sandbox.paypal.com/webscr&cmd=_express-checkout&token=";
}


Next, we need the details of transaction to be submitted to paypal api. For the benefit of this post, please see details below.

$itemamt = '40.00'; // item amount
$paymentamt = '50.00'; // total amount
$taxamt = '10.00'; // tax amount
$currencyid = 'CAD'; // 'GBP', 'EUR', 'JPY', 'USD', 'AUD'


Please make sure that $paymentamt = $itemamt + $taxamt

Also, we need the details below to perform payment transaction.

$startdate = urlencode('2012-07-01T18:10:40+08:00'); // payment start date
$billingfreq = '1' // number of months interval;
$paymenttype = 'Authorization'; // or 'Sale' or 'Order'
$description = urlencode('sample description'); // description of transaction


You also need to define your callback url. Please see below.

$returnurl = 'http://www.domain.com/callback/return.html'; // callback url for successful transaction
$cancelurl = 'http://www.domain.com/callback/cancel.html'; // callback url for failed transaction


After defining the parameters, compose the query string. Please see below.

$reqStr = "METHOD=SetExpressCheckout&VERSION=65.2&PWD=$password&USER=$username&SIGNATURE=$signature&RETURNURL=$returnurl&CANCELURL=$cancelurl&REQCONFIRMSHIPPING=0&NOSHIPPING=1&PAYMENTREQUEST_0_CURRENCYCODE=$currencyid&PAYMENTREQUEST_0_AMT=$paymentamt&PAYMENTREQUEST_0_ITEMAMT=$itemamt&PAYMENTREQUEST_0_TAXAMT=$taxamt&PAYMENTREQUEST_0_DESC=$description&PAYMENTREQUEST_0_PAYMENTACTION=$paymenttype&L_PAYMENTREQUEST_0_ITEMCATEGORY0=Digital&L_PAYMENTREQUEST_0_NAME0=$description&L_PAYMENTREQUEST_0_QTY0=1&L_PAYMENTREQUEST_0_AMT0=$itemamt&L_PAYMENTREQUEST_0_DESC0=$description&L_BILLINGAGREEMENTDESCRIPTION0=$description&L_BILLINGTYPE0=RecurringPayments&MAXFAILEDPAYMENTS='true'";

Setup the curl as below.

// set the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_VERBOSE, 1);

// disable ssl verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

// set the method
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);

// set the post parameters
curl_setopt($ch, CURLOPT_POSTFIELDS, $reqstr);
               
// execute curl
$response = curl_exec($ch);
if (!$response) exit("SetExpressCheckout failed: ".curl_error($ch).'('.curl_errno($ch).')');


Get and parse the http response.

// get and parse the response
$arr_response = explode("&", $response);

$http_response = array();
foreach ($arr_response as $key => $val) {
        $param = explode("=", $val);
        if (sizeof($param) > 1) $http_response[$param[0]] = $param[1];
}

if ((sizeof($http_response) == 0) || !array_key_exists('ACK', $http_response)) {
        exit("SetExpressCheckout failed: " . print_r($arr_response, true));
}


Get the token and pass it to paypal for processing.

// get the token and pass to paypal for processing
if (strtoupper($http_response["ACK"]) == "SUCCESS" || strtoupper($httpParsedResponseAr["ACK"]) == "SUCCESSWITHWARNING") {
        // redirect to paypal to confirm and process transaction
        $token = urldecode($http_response["TOKEN"]);
        $paypalurl .= $token;

        if (isset($paypalurl)) redirect($paypalurl);
        exit;
} else  {
        exit('SetExpressCheckout failed: ' . print_r($http_response, true));
}


This is all for now. Next post will be processing after Paypal. You can also check out the full script below. Happy coding!!

<?php

// set up your environment - live or sandbox
$live = "true";

if ($live == "true") {
        // live account details
        $username = 'paypal live username';
        $password = 'paypal live password';
        $signature = 'paypal live api signature';
        $endpoint = "https://api-3t.paypal.com/nvp";
        $url = "https://www.paypal.com/webscr&cmd=_express-checkout&token=";
} else {
        // sandbox account details
        $username = 'paypal sandbox username';
        $password = 'paypal sandbox password';
        $signature = 'paypal sandbox api signature';
        $endpoint = "https://api-3t.sandbox.paypal.com/nvp";
        $url = "https://www.sandbox.paypal.com/webscr&cmd=_express-checkout&token=";
}

$itemamt = '40.00'; // item amount
$paymentamt = '50.00'; // total amount
$taxamt = '10.00'; // tax amount
$currencyid = 'CAD'; // or 'GBP', 'EUR', 'JPY', 'USD', 'AUD'

$startdate = urlencode('2012-07-01T18:10:40+08:00'); // payment start date - 2012-07-01T18:10:40+08:00
$billingfreq = '1' // number of months interval;
$paymenttype = 'Authorization'; // or 'Sale' or 'Order'
$description = urlencode('sample description'); // description of transaction

$returnurl = 'http://www.domain.com/callback/return.html'; // callback url for successful transaction
$cancelurl = 'http://www.domain.com/callback/cancel.html'; // callback url for failed transaction

$reqstr = "METHOD=SetExpressCheckout&VERSION=65.2&PWD=$password&USER=$username&SIGNATURE=$signature&RETURNURL=$returnurl&CANCELURL=$cancelurl&REQCONFIRMSHIPPING=0&NOSHIPPING=1&PAYMENTREQUEST_0_CURRENCYCODE=$currencyid&PAYMENTREQUEST_0_AMT=$paymentamt&PAYMENTREQUEST_0_ITEMAMT=$itemamt&PAYMENTREQUEST_0_TAXAMT=$taxamt&PAYMENTREQUEST_0_DESC=$description&PAYMENTREQUEST_0_PAYMENTACTION=$paymenttype&L_PAYMENTREQUEST_0_ITEMCATEGORY0=Digital&L_PAYMENTREQUEST_0_NAME0=$description&L_PAYMENTREQUEST_0_QTY0=1&L_PAYMENTREQUEST_0_AMT0=$itemamt&L_PAYMENTREQUEST_0_DESC0=$description&L_BILLINGAGREEMENTDESCRIPTION0=$description&L_BILLINGTYPE0=RecurringPayments&MAXFAILEDPAYMENTS='true'";

// set the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_VERBOSE, 1);

// disable ssl verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

// set the method
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);

// set the post parameters
curl_setopt($ch, CURLOPT_POSTFIELDS, $reqstr);

// execute curl
$response = curl_exec($ch);

if (!$response) exit("SetExpressCheckout failed: ".curl_error($ch).'('.curl_errno($ch).')');

// get and parse the response
$arr_response = explode("&", $response);

$http_response = array();
foreach ($arr_response as $key => $val) {
        $param = explode("=", $val);
        if (sizeof($param) > 1) $http_response[$param[0]] = $param[1];
}

if ((sizeof($http_response) == 0) || !array_key_exists('ACK', $http_response)) {
        exit("SetExpressCheckout failed: " . print_r($arr_response, true));
}

// get the token and pass to paypal for processing
if (strtoupper($http_response["ACK"]) == "SUCCESS" || strtoupper($httpParsedResponseAr["ACK"]) == "SUCCESSWITHWARNING") {
        // redirect to paypal to confirm and process transaction
        $token = urldecode($http_response["TOKEN"]);
        $paypalurl .= $token;

        if (isset($paypalurl)) redirect($paypalurl);
        exit;
} else  {
        exit('SetExpressCheckout failed: ' . print_r($http_response, true));
}

?>

HTML 101: Setting up tab index in your website

Setting up tab index is very useful if you want your text boxes, buttons, and any other elements be set in a specific order.

You can set it by using "tabindex" attribute to all your input elements. Please see sample below.

<input type="text" value="" name="text" tabindex="1"></input>
<input type="text" value="" name="text" tabindex="2"></input>
<input type="submit" value="submit" name="text" tabindex="3"></input>


You can also disable the tab index of an element by setting the value to "-1". This is very useful if you have an element that is hide or you set the opacity to be not visible. Please see sample below.

<input type="text" value="" name="text" style="opacity:0;" tabindex="1"></input>
<input type="text" value="" name="text" tabindex="-1"></input>
<input type="submit" value="submit" name="text" tabindex="2"></input>


Hope this is helpful!

Sunday, June 10, 2012

Forcing the files to download using htaccess

If we want to put a functionality in our website to download files, the best and easiest way to do it is to have it in htaccess.

By default, the files will open up to your current page or open up a tab when clicked via target="_blank" attribute. Well, that is for me not a good experience, most especially if your website is a downloading site.

You can also try to make a script to force the files to download either via php, asp, or any language, but that will be tedious.

Why do you need to be hard on yourself if you can do it fast and easy.

Please see below syntax that you can put in on your htaccess to force the file to download on your website.

AddType application/force-download .csv
AddType application/force-download .xls
AddType application/force-download .doc
AddType application/force-download .docx
AddType application/force-download .avi
AddType application/force-download .mpg
AddType application/force-download .mov
AddType application/force-download .wav
AddType application/force-download .zip
AddType application/force-download .mp3
AddType application/force-download .pdf


Hope this helps. Thank you for reading such a short post.

Thursday, May 17, 2012

Setting up a remember me functionality on your website

First we need to have a login page where to put the "remember me" check box to have an identifier whether the user wants to be remembered or not.

Second, we need to set the users table to store the remember me token which we will use to identify as to which user should be logged in.

Please take note that I used token which is another field rather than using the actual user id coz having a token that changes every time is much secure than having just a static id.

I will discuss below on how you can make it much secure.

Okay, once you have the above in placed, we are now ready to do the coding.

You need to capture those users that agrees to be remembered then call this function below. For the benefit of this post, I set the cookie to expire in 14 days.

<?php
 

if (!mysql_connect('localhost', 'mysql_user', 'mysql_password')) die("can't connect to db: ".mysql_error());

if (!mysql_select_db('database_name')) die("can't select db: ".mysql_error);

$user_id = '<your login user id>';

// call this function to set cookie and expiry time

set_remember($user_id);

// set cookie and expiry time
function set_remember($user_id=0) {
        $token = md5($user_id."-".date('YmdGis'));
        $expire = time() + (14 * 86400); // 14 days

        setcookie("remember_me_token", $token, $expire);

        $expire = date('Y-m-d', $expire);
        $return = update_user_token($user_id, $token, $expire);
}

// update users table for token and expiry time
function update_user_token($user_id=0, $token='', $expire='') {
        $sql = "UPDATE user_table SET token='$token)', expire='$expire' ".
               "WHERE user_id='$user_id'";

        $query = mysql_query($sql);
        return 1;
}

?>

$user_id is the id of the user who successfully logged in to your site. This will be used to generate a random token which we will set in our cookie and update the users table as well.

We will use the function of the PHP to set the cookie.

setcookie("your_cookie_variable", "your_cookie_value", "expiration_of_cookie");

Please take note that you have to make sure that the user be able to login with the right credential before you call the function "set_remember($user_id)".

After calling function, you can get the cookie value by calling $_COOKIE["your_cookie_variable"]; and in our example above, you can call it by this syntax $_COOKIE['remember_me_token'];

I just want to remind you that COOKIE is not like a SESSION that starts when the pages loaded, the COOKIE will store value in your computer, so you need to come up with a COMPLEX name to prevent hackers from hacking your site.

Okay, moving on, since we set our cookie to expire in 14 days, then we have to make the user to be remembered every time they login and extend the expiration accordingly.

To do that, we need to get the token value from the cookie, get the user_id from our database, then call again the function set_remember($user_id);. If there's no cookie available, then redirect the user to login page.

Please see below for the sample implementation.

<?php

if (!mysql_connect('localhost', 'mysql_user', 'mysql_password')) die("can't connect to db: ".mysql_error());

if (!mysql_select_db('database_name')) die("can't select db: ".mysql_error);

$cookie = get_cookie('remember_me_token');
if ($cookie) $user_id = get_user_id_by_cookie($cookie);

// go to login page if no value for user_id
if (!$user_id) header("http://mywebsite/user/login");

// function to get the user id from the cookie
function get_user_id_by_cookie($cookie='') {
        $sql = "SELECT user_id FROM user_table WHERE token='$cookie'";

        $query = mysql_query($sql);
        return mysql_result($query, 0, 0);
}

// call this function to renew token then set a new new expiry datetime
set_remember($user_id);

// set cookie and expiry time
function set_remember($user_id=0) {
        $token = md5($user_id."-".date('YmdGis'));
        $expire = time() + (14 * 86400); // 14 days

        setcookie("remember_me_token", $token, $expire);

        $expire = date('Y-m-d', $expire);
        $return = update_user_token($user_id, $token, $expire);
}

// update users table for token and expiry time
function update_user_token($user_id=0, $token='', $expire='') {
        $sql = "UPDATE user_table SET token='$token)', expire='$expire' ".
               "WHERE user_id='$user_id'";

        $query = mysql_query($sql);
        return 1;
}

?>


Hope this post helps a lot!! Thanks!!

Wednesday, May 16, 2012

How to get the main domain from the URL

This post is just a code snippet on how to get the main domain from the URL string. Enjoy and happy coding!!

<?php

$url = "http://subdomain.domain.com/sample/url"; 

$host = parse_url($url, PHP_URL_HOST);
$host = array_reverse(explode('.', $host));
$host = $host[1].'.'.$host[0];

echo "$host";

?>

Wednesday, April 25, 2012

How to setup cache pages in PHP

This post will teach you how to setup caching in your pages. This is recommended to setup if your pages is not that dynamic enough that changes frequently.

First, you need to create as to where you will put all your cache files, don't put it on the same directory where your files are in coz it might overwrite your pages. On this post, I created cache directory.

We can also set the cache expiry time by validating the time it was created. To check, we used time() and filemtime() functionality.

To make it work, we will put condition to check if the we have cache file and that it didn't expired yet. If okay, we will just include the file then display the contents. If not, it will capture the page then write to a file.

Please see below for the implementation. Happy coding!!

<?php
$cachefile = "cache/yourpage.html";
$cachetime = 30 * 60; // 30 minutes

// validate and check for existing cache file
if (file_exists($cachefile) && (time() - $cachetime < filemtime($cachefile))) {
        include($cachefile);
        exit;
}

// start the output stream
ob_start();
?>

<html>your page here to put into cache</html>

<?php
// save the contents to cache file
$fp = fopen($cachefile, 'w');
fwrite($fp, ob_get_contents());
fclose($fp);


// end the output stream
ob_end_flush();

?>

Friday, March 9, 2012

Setting up dynamic sub domain via httpd.conf or htaccess

This post will teach you how to setup dynamic sub domain on your server.

We actually have 2 options on how to do it, maybe 3 which uses cpanel if allowed on your account.
Anyway, what I'll be discussing is the setup via httpd.conf or via .htaccess file.

To do this via httpd.conf, you only need to create a virtualhost with ServerAlias as below.
<VirtualHost>
    DocumentRoot /www/subdomain
    ServerName www.domain.tld
    ServerAlias *.domain.tld
</VirtualHost>


To do this via .htaccess, create the htaccess file on the www/ directory where your subdomains will be placed.

RewriteCond %{ENV:REDIRECT_SUBDOMAIN} =""
RewriteCond %{HTTP_HOST} ^([a-z0-9][-a-z0-9]+)\.domain\.com\.?(:80)?$ [NC]
RewriteCond %{DOCUMENT_ROOT}/%1 -d
RewriteRule ^(.*) %1/$1 [E=SUBDOMAIN:%1,L]
RewriteRule ^ - [E=SUBDOMAIN:%{ENV:REDIRECT_SUBDOMAIN},L]


Hope this helps. Thanks!

Sunday, January 8, 2012

Creating dynamic progress bar in HTML

This post will teach you how to create a dynamic progress bar in HTML using jQuery and CSS.

First, you need to have an HTML, please see below on how I do it.

- Create 3 divs: progressWrap, progressBar, and progressNum
- #progressWrap : this will be the container of the progressbar, take note of the width coz this will be the basis to compute for the percentage.
- #progressBar : this will be the actual progress bar
- #progressNum : this will be the percentage

For the benefit of this post, I set the #progressBar width to 50px which is 25% of #progressWrap width = 200px

<html>
<head>
        <title>Progress Bar</title>
        <style type="text/css">
        #progressWrap
        {
                margin: 0px 0px 0px 5px;
                background: #FFF;
                height: 11px;
                width: 200px;
        }

        #progressWrap #progressBar
        {
                height: 11px;
                position:absolute;
                background-color: #000;
        }

        #progressWrap #progressNum {
                text-align:center;
                width:100%;
                color:#515151;
                font-size:9px;
                font-weight:bold;
        }
        </style>
</head>
<body>
<div id="progressWrap">
        <div id="progressBar" style="width:50px"></div>
        <div id="progressNum">25%</div>
</div>
</body>
</html>


Next is to set our progress bar dynamic using jQuery. Please see below.

The formula for the percentage is based on the width of the container in CSS. The width is divided by 100 and will be multiplied to the percentage value to get the width of the progress bar.

<script type="text/javascript">
        $(document).ready(function() {
                var percent = 25;
                var width = percent * parseInt($('#progressWrap').css('width')) / 100;

                $('#progressNum').html(percent+'%');
                $('#progressBar').css('width', width+'px');
        });
</script>


To see the working script, please see below.

<html>
<head>
        <title>Progress Bar</title>
        <style type="text/css">
        #progressWrap
        {
                margin: 0px 0px 0px 5px;
                background: #FFF;
                height: 11px;
                width: 300px;
        }

        #progressWrap #progressBar
        {
                height: 11px;
                position:absolute;
                background-color: #000;
        }

        #progressWrap #progressNum {
                text-align:center;
                width:100%;
                color:#515151;
                font-size:9px;
                font-weight:bold;
        }
        </style>
        <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div id="progressWrap">
        <div id="progressBar"></div>
        <div id="progressNum"></div>
</div>
</body>
</html>
<script type="text/javascript">
        $(document).ready(function() {
                var percent = 25;
                var width = percent * parseInt($('#progressWrap').css('width')) / 100;

                $('#progressNum').html(percent+'%');
                $('#progressBar').css('width', width+'px');
        });
</script>

Thursday, January 5, 2012

File upload with style using jQuery and CSS

This post is an improved version of my previous post "How to put a style on input file type using CSS and jQuery". The improvement is due to the problem on IE sucks with security issues.

My previous post I have is basically working and will teach you how to open a dialog box and select the file you want to upload with a styled layout.

However, the problem on IE is that it doesn't accept the approach of jQuery or Javascript, that triggers the click event of the input file element that causes an error "Access is Denied" when submitted.

Good thing I was able to find a way to trick IE. Please see below on how I do it and hopefully will be able help developers.

First, we need to understand what IE's requirement are to make it work. So, basically for the file upload to work on IE, the user should have to click on the input file element without using jQuery or Javascript to do it for us.

Given the requirement of IE and the style to put in, the best solution for me is to use CSS opacity and z-index.

In logic, what you need to do is #1. set your input file element on top of your styled textbox using z-index, this is for user to be able to click the file input element. #2. set the input file element as invisible using the opacity equal to zero "0", this is to hide the input file element and the styled textbox will be visible instead. That way, we can satisfy IE and at the same time, be able to style the file upload.

As for the sample script I made, please see below.
The sample compose of 2 scripts: index.html and upload.php

index.php

<html>
<head>
        <title>File Upload</title>

        <style type="text/css">
        div.inputContainer {
                position: relative;
        }
        div.inputStyled {
                position: absolute;
                top: 0px;
                left: 0px;
                z-index: 1;
        }
        input.inputHide {
                position: relative;
                text-align: right;
                -moz-opacity:0 ;
                filter:alpha(opacity: 0);
                opacity: 0;
                z-index: 2;
        }
        </style>

        <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
        <script type="text/javascript">
        $(document).ready(function() {
                $('#docufile').change(function() {
                        var vals = $(this).val();
                        val = vals.length ? vals.split('\\').pop() : '';

                        $('#document').val(val);
                });

                $('#btnSubmit').click(function() {
                        $('#frmAdd').submit();
                });
        });
        </script>
</head>
<body>
<form id="frmAdd" name="frmAdd" action="upload.php" method="post" enctype="multipart/form-data" encoding="multipart/form-data">
        <div class="inputContainer">
        <div class="inputStyled">
                <input name="document" id="document" type="text">
                <input name="button" type="button">
        </div>
        <input type="file" class="inputHide" name="docufile" id="docufile"/>
        </div>
        <input type="submit" value="submit" id="btnSubmit"/>
</form>
</body>
</html>


upload.php

<?php

$docufile = '';
if (@$_FILES['docufile']['tmp_name']) {
        $docufile = upload_file($_FILES['docufile']);
}

echo $docufile;

function upload_file($docu=null) {
        $upload_dir = "files/";
        $docu_file='';

        if (!$docu['error'] == 0) return '';
        if (!@is_uploaded_file($docu['tmp_name'])) return '';

        $filename = preg_replace("/\s+/", "", $docu['name']);
        if (!file_exists($upload_dir.$filename)) {
                $docu_file = $filename;
        } else {
                $rand = 1;
                while(file_exists($upload_dir.$rand."-".$filename)) {
                        $rand ++;
                }
                $docu_file = $rand."-".$filename;
        }

        $upload_file = $upload_dir.$docu_file;
        if (!@move_uploaded_file($docu['tmp_name'], $upload_file)) {
                return '';
        }

        return $docu_file;
}
?>



Quote for the day:
If you want to reach your potential, you need to add a strong work ethic to your talent. If you want something out of your day, you must put something in it. Your talent is what God put in before you were born. Your skills are what you put in yesterday. Commitment is what you just put in today in order to make today your masterpiece and make tomorrow a success. - john m.

Leadership 101


  • Leadership demands sacrifices for the near-term to receive lasting benefits. the longer we wait to make sacrifices, the harder they become. Successful people make important decisions early in their life, then manage those decisions the rest of their lives.
  • Growth does not happen by chance. If you want to be sure to grow, you need a plan something strategic, specific, and scheduled. it's a discipline that would need incredible determination from us.
  • Success comes by going the extra mile, working the extra hours, and investing the extra time. The same is true for us. If we want to get to excel in any segment of life, a little extra effort can help. Our efforts can go a long way if we only work a little smarter, listen a little better, push a little harder, and persevere a little longer.
  • Making a difference in your work is not about productivity; it's about people. When you focus on others and connect with them, you can work together to accomplish great things.
  • Envision a goal you'd like to reach. Make it big enough to scare you a little. Now write down a plan for moving toward it. Create mini-goals within the big goal, to set yourself up for continual progress. And include some risks, too. Set yourself up for success.
  • Leaders build margins, not image. A leader may be forced to take unpopular stands for the good of the company. Popularity isn't bad, but decisions made solely on the basis of popular opinion can be devastating. So take courage and make the right though sometimes painful choices.