Showing posts with label Web Application. Show all posts
Showing posts with label Web Application. Show all posts

Sunday, May 28, 2017

PHP Script: Call Method Dynamically

PHP Script: Call Method Dynamically. Below is PHP Script which describes the full process:

<?php
$fnc = "canCall";
if (!is_callable($fnc)) {
    echo "Cant call method: $fnc <BR>";
} else {
    echo "Return from method $fnc: " . $fnc(15) . "<BR>";
}

$fnc = "canCall2";
if (!is_callable($fnc)) {
    echo "Cant call method: $fnc <BR>";
} else {
    echo "Return from method $fnc: " . $fnc(15) . "<BR>";
}

function canCall($a = 10)
{
    return $a * 5;
}

$caller_class = new CallerClass();
$caller_class->check();

class CallerClass
{
    private $for_method1 = 10;

    public function check()
    {
        $fnc = "method1";
        if (!is_callable(array(&$this, $fnc))) {
            echo "$fnc is not callable function";
        } else {
            $this->{"for_method1"} = 20;
            echo "Return from $fnc:" . $this->{$fnc}() . "<BR>";
        }

        $fnc = "method2";
        if (!is_callable(array(&$this, $fnc))) {
            echo "$fnc is not callable function";
        } else {
            echo "Return from $fnc:" . $this->{$fnc}() . "<BR>";
        }
    }

    public function method1()
    {
        return "From method 1 <$this->for_method1>";
    }
}

?>


Which will output as below:

Return from method canCall: 75
Cant call method: canCall2 
Return from method1:From method 1 <20>
method2 is not callable function

How to PHP call another page and get output as variable?

How to PHP call another page and get output as variable? it's easy. We can do it in two way. First way is processing via ob_... and second way is get content in a variable and execute eval function. 

Below is a PHP Script which will describes both way:


<?php
ob_start();
${"variable"} = array("as_array" => "Test variable value in array #Method 1");
require 'content.txt';
$output = ob_get_clean();
echo $output;

${"variable"} = array("as_array" => "Test variable value in array #Method 2");
$file = file_get_contents('content.txt');
$content = eval("?>$file");
echo $content;


Content of "content.txt" file below:

<div style="margin: 10px; border: 1px solid red; padding: 10px;">
    <h3>HI, Time = <?= date("d/m/Y h:i A") ?></h3>
    <h4><?= $variable["as_array"] ?></h4>
    <table>
        <tr>
            <td>TABLE > TR > TD</td>
        </tr>
    </table>
</div>


And output of above PHP Script below:


HI, Time = 28/05/2017 02:56 PM

Test variable value in array #Method 1

TABLE > TR > TD

HI, Time = 28/05/2017 02:56 PM

Test variable value in array #Method 2

TABLE > TR > TD

Friday, May 26, 2017

Stripe Payment API: Create Get Edit Delete Customer

You can create Customer in Stripe using API. You can profile source when you create the Customer. Here source is payment source, Such you can create a Credit Card Token and provide reference as source. To create Credit Card Token follow below link:

http://pritomkumar.blogspot.com/2017/05/stripe-payment-api-create-token-using.html

And below link for API details:
https://stripe.com/docs/api#create_customer

Below is a PHP Script that will Create Get And Delete Customer From Stripe.



<?php
$params = array(
    "email" => "customer_3@pritom.com",
    "source" => "token_id_using_above_link" 
 );
$create = StripeCustomer::create($params);
StripeCustomer::prettyPrint($create);

if ($create["code"] == 200) {
    $get = StripeCustomer::get($create["response"]->id);
    StripeCustomer::prettyPrint($get);

    $delete = StripeCustomer::delete($create["response"]->id);
    StripeCustomer::prettyPrint($delete);
}

class StripeCustomer {
    private static $key = "sk_test_............";

    static function create($params)
    {
        $url = "https://api.stripe.com/v1/customers";

        $headers[] = "Authorization: Bearer " . self::$key;
        $headers[] = "Content-Type: application/x-www-form-urlencoded";

        return makeCurlCall($url, "POST", null, $params, $headers);
    }

    static function get($id)
    {
        $url = "https://api.stripe.com/v1/customers/$id";

        $headers[] = "Authorization: Bearer " . self::$key;
        $headers[] = "Content-Type: application/x-www-form-urlencoded";

        return makeCurlCall($url, "GET", null, null, $headers);
    }

    static function delete($id)
    {
        $url = "https://api.stripe.com/v1/customers/$id";

        $headers[] = "Authorization: Bearer " . self::$key;
        $headers[] = "Content-Type: application/x-www-form-urlencoded";

        return makeCurlCall($url, "DELETE", null, null, $headers);
    }

    static function prettyPrint($data)
    {
        echo "<pre>";
        print_r($data);
        echo "</pre>";
    }
}

Below is output of the Script above:



CREATE REQUEST RESPONSE:
Array
(
    [code] => 200
    [response] => stdClass Object
        (
            [id] => cus_Aj4vdApn2NQIbB
            [object] => customer
            [account_balance] => 0
            [created] => 1495783280
            [currency] => 
            [default_source] => card_1ANcktFIwfarG3vBDsNU6Bg9
            [delinquent] => 
            [description] => 
            [discount] => 
            [email] => customer_8@pritom.com
            [livemode] => 
            [metadata] => stdClass Object
                (
                )

            [shipping] => 
            [sources] => stdClass Object
                (
                    [object] => list
                    [data] => Array
                        (
                            [0] => stdClass Object
                                (
                                    [id] => card_1ANcktFIwfarG3vBDsNU6Bg9
                                    [object] => card
                                    [address_city] => 
                                    [address_country] => 
                                    [address_line1] => 
                                    [address_line1_check] => 
                                    [address_line2] => 
                                    [address_state] => 
                                    [address_zip] => 
                                    [address_zip_check] => 
                                    [brand] => Visa
                                    [country] => US
                                    [customer] => cus_Aj4vdApn2NQIbB
                                    [cvc_check] => pass
                                    [dynamic_last4] => 
                                    [exp_month] => 12
                                    [exp_year] => 2019
                                    [fingerprint] => CjZNbbCtG5QSnuIS
                                    [funding] => credit
                                    [last4] => 4242
                                    [metadata] => stdClass Object
                                        (
                                        )

                                    [name] => Card Name
                                    [tokenization_method] => 
                                )

                        )

                    [has_more] => 
                    [total_count] => 1
                    [url] => /v1/customers/cus_Aj4vdApn2NQIbB/sources
                )

            [subscriptions] => stdClass Object
                (
                    [object] => list
                    [data] => Array
                        (
                        )

                    [has_more] => 
                    [total_count] => 0
                    [url] => /v1/customers/cus_Aj4vdApn2NQIbB/subscriptions
                )

        )

)
GET REQUEST RESPONSE
Array
(
    [code] => 200
    [response] => stdClass Object
        (
            [id] => cus_Aj4kNrfMs3ivE8
            [object] => customer
            [account_balance] => 0
            [created] => 1495782666
            [currency] =>
            [default_source] =>
            [delinquent] =>
            [description] =>
            [discount] =>
            [email] => customer_3@pritom.com
            [livemode] =>
            [metadata] => stdClass Object
                (
                )

            [shipping] =>
            [sources] => stdClass Object
                (
                    [object] => list
                    [data] => Array
                        (
                        )

                    [has_more] =>
                    [total_count] => 0
                    [url] => /v1/customers/cus_Aj4kNrfMs3ivE8/sources
                )

            [subscriptions] => stdClass Object
                (
                    [object] => list
                    [data] => Array
                        (
                        )

                    [has_more] =>
                    [total_count] => 0
                    [url] => /v1/customers/cus_Aj4kNrfMs3ivE8/subscriptions
                )

        )

)

DELETE REQUEST RESULT
Array
(
    [code] => 200
    [response] => stdClass Object
        (
            [deleted] => 1
            [id] => cus_Aj4kNrfMs3ivE8
        )

)

Thursday, May 25, 2017

PHP Script - detect whether running under Linux or Windows?

PHP script - detect whether running under Linux or Windows or other Operating System? I don't have so much knowledge but can overcome with some solution. "PHP_OS" will solve this issue. Below is function to check if OS is Windows or not:

if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
    echo 'Windows!';
} else {
    echo 'Other Than Windows!';
}

PHP_OS will output below list of Operating System, not full list but I think it's almost all.
  • CYGWIN_NT-5.1
  • Darwin
  • FreeBSD
  • HP-UX
  • IRIX64
  • Linux
  • NetBSD
  • OpenBSD
  • SunOS
  • Unix
  • WIN32
  • WINNT
  • Windows
You can see on Wikipedia for more information.


Wednesday, May 24, 2017

PHP Encrypt Data With OpenSSL Public Key And Decrypt With OpenSSL Private Key

Below is a PHP code snippet to encrypt data with a public key and then again decrypt the encrypted data with a private key.
 

If you have fetched the problem "error:0406D06E:rsa routines:RSA_padding_add_PKCS1_type_2:data too large for key size" then use the below code snippet to overcome this problem.
 

It's a good solution to handle big size data, but don't try too big size data with this method actually when you post file.
Raw data is fine.  




$data = "Large data to test. Large data to test. Large data to test. Large data to test.";
$data = $data . $data . $data . $data . $data . $data . $data . $data;
$data = $data . $data . $data . $data . $data . $data . $data . $data;
encryptAndDecrypt($data);

function encryptAndDecrypt($data)
{
    echo "Original data length=" . strlen($data) . "<BR>";

    $private_key = openssl_pkey_get_private(readServerFile("./XeroCerts/privatekey.pem"));
    $public_key = openssl_pkey_get_public(readServerFile("./XeroCerts/publickey.cer"));

    //Block size for encryption block cipher for 1024 bit key
    $encrypt_size = 110;

    //Block size for decryption block cipher for 1024 bit key
    $decrypt_size = 128;

    //For encryption we would use:
    $encrypted = '';
    $data = str_split($data, $encrypt_size);
    foreach ($data as $chunk) {
        openssl_public_encrypt($chunk, $partial, $public_key, OPENSSL_PKCS1_PADDING);
        $encrypted .= $partial;
    }
    openssl_free_key($public_key);
    $encrypted = base64_encode($encrypted);
    echo "Encrypted=" . $encrypted . "<BR>";

    //For decryption we would use:
    $decrypted = '';
    $data = str_split(base64_decode($encrypted), $decrypt_size);
    foreach ($data as $chunk) {
        openssl_private_decrypt($chunk, $partial, $private_key, OPENSSL_PKCS1_PADDING);
        $decrypted .= $partial;
    }
    openssl_free_key($private_key);
    echo "Decrypted=" . $decrypted;
    die();
}

Output of the above code snippet is below: 


If you don't want to save strings in clear text, there are new php functions (php >= 5.3.0) that can be of help; openssl_encrypt() and openssl_decrypt().

Original data length=5056
Encrypted=Vf2GHkx..............LgpFjM9gY/FkIYWaELHl3I=
Decrypted=Large data to test. ............ Large data to test. Large data to test. Large data to test.

Simple PHP encrypt and decrypt Using AES-256-CBC Algorithm | OpenSSL Encrypt | OpenSSL Decrypt

If you don't want to save strings in clear text, there are new php functions (php >= 5.3.0) that can be of help; openssl_encrypt() and openssl_decrypt(). 


<?php
define("SSL_SECRET_KEY", "SSL_SECRET_KEY");
define("SSL_SECRET_IV", "SSL_SECRET_IV");
define("SSL_ENCRYPTION_METHOD", "AES-256-CBC");
define("SSL_SECRET_IV_SIZE", openssl_cipher_iv_length(SSL_ENCRYPTION_METHOD));

function encryptData($string)
{
    $key = hash('sha256', SSL_SECRET_KEY);
    /* If you want random IV */
    //$iv = openssl_random_pseudo_bytes(SSL_SECRET_IV_SIZE);
    $iv = substr(hash('sha256', SSL_SECRET_IV), 0, SSL_SECRET_IV_SIZE);

    $output = openssl_encrypt($string, SSL_ENCRYPTION_METHOD, $key, 0, $iv);
    return base64_encode($output);
}

function decryptData($string)
{
    $key = hash('sha256', SSL_SECRET_KEY);
    $iv = substr(hash('sha256', SSL_SECRET_IV), 0, SSL_SECRET_IV_SIZE);

    return openssl_decrypt(base64_decode($string), SSL_ENCRYPTION_METHOD, $key, 0, $iv);
}

$REQUEST_URI = isset($_SERVER["REQUEST_URI"]) ? $_SERVER["REQUEST_URI"] : "";

if (strpos($REQUEST_URI, "enc.php") !== false) {
    $plain_txt = "Value to be encrypt & decrypt";
    echo "Original Text = $plain_txt<br/>";

    $encrypted_txt = encryptData($plain_txt);
    echo "Encrypted Text = $encrypted_txt<br/>";

    $decrypted_txt = decryptData($encrypted_txt);
    echo "Decrypted Text = $decrypted_txt<br/>";

    if ($plain_txt === $decrypted_txt) echo "SUCCESS";
    else echo "FAILED";

    echo "<br/>";
}


Original Text:
Value to be encrypt & decrypt

Encrypted Text = 
RjFhMElpR0VzMVlPeVdtREVraFJzYnhnNXZ4ck4vSmhRVUtXWXJoUzBVWT0=

Decrypted Text
Value to be encrypt & decrypt

SUCCESS 

Or (This will carry IV with encrypted text itself):

<?php
define("SSL_SECRET_KEY", "xorxorxorxorxor");
define("SSL_ENCRYPTION_METHOD", "AES-256-CBC");
define("SSL_SECRET_IV_SIZE", openssl_cipher_iv_length(SSL_ENCRYPTION_METHOD));

function encryptData($string)
{
    $key = hash('sha256', SSL_SECRET_KEY);
    $iv = openssl_random_pseudo_bytes(SSL_SECRET_IV_SIZE);

    $output = openssl_encrypt($string, SSL_ENCRYPTION_METHOD, $key, 0, $iv);
    return base64_encode($iv . ":" . $output);
}

function decryptData($string)
{
    $string = explode(":", base64_decode($string));
    $key = hash('sha256', SSL_SECRET_KEY);

    return openssl_decrypt($string[1], SSL_ENCRYPTION_METHOD, $key, 0, $string[0]);
}

$plain_txt = "Value to be encrypt & decrypt";
echo "Original Text = $plain_txt<br/>";

$encrypted_txt = encryptData($plain_txt);
echo "Encrypted Text = $encrypted_txt<br/>";

$decrypted_txt = decryptData($encrypted_txt);
echo "Decrypted Text = $decrypted_txt<br/>";

if ($plain_txt === $decrypted_txt) echo "SUCCESS";
else echo "FAILED";

echo "<br/>";

Original Text:

Value to be encrypt & decrypt

Encrypted Text:
NfDWpobv5RGaC29EpXvP7Dp2WkJjN2pETmdPendsZkdsMnBVQXBTK2pRekJTNkhlTndEdTRGd3h6eHpFPQ==

Decrypted Text:
Value to be encrypt & decrypt

SUCCESS

Get last word from URL after a slash in PHP (www.xxx.com/about.php/THIS_WORD)

This summary is not available. Please click here to view the post.

Thursday, May 18, 2017

Growl Notification Example Web Application

Its now very easy to show our error or other types of messages in our web application easily. Growl is a nice plugin to display our target messages nicely in our web application. 

$('.error').click(function(event) {
    return $.growl.error({
        message: "Growl Error Message!"
    });
});
$('.notice').click(function(event) {
    return $.growl.notice({
        message: "Growl Notice Message!"
    });
});
$('.warning').click(function(event) {
    return $.growl.warning({
        message: "Growl Warning Message!"
    });
});








Download full example from here

Saturday, December 17, 2016

Adding Desktop Notifications to Your Web Applications

Download example from here


<button onclick="notifyMe()">Notify me!</button>

<script type="text/javascript">
    // request permission on page load
    document.addEventListener('DOMContentLoaded', function () {
        if (!Notification) {
            alert('Desktop notifications not available in your browser.');
            return;
        }
        if (Notification.permission !== "granted") {
            Notification.requestPermission();
        }
    });

    function notifyMe() {
        if (Notification.permission !== "granted") {
            Notification.requestPermission();
        }
        else {
            setTimeout(function() {
                var notification = new Notification('Notification Title', {
                    icon: 'images.jpg',
                    body: "Hey there! You've been notified!, Hey there! You've been notified!, Hey there! You've been notified!",
                });

                notification.onclick = function () {
                    alert("Notification event clicked");
                };
            }, 1000);
        }
    }
</script>

Tuesday, May 15, 2012

Execute Curl to GET POST PUT PATCH DELETE Method Using Php

$headers[] = "Authorization: Basic xxx";
$headers[] = "Accept: text/xml";

$post = array(
    "name" => "Some name",
    "roll" => "Some roll"

);

$result = CurlExecutor::execute("...com/api/test", "POST", $post, null, $headers);
CurlExecutor::prettyPrint($result);


<?php
class CurlExecutor
{
    static function execute($url, $method = "GET", $posts = null, $gets = null, $headers = null, Closure $closure = null)
    {
        $ch = curl_init();
        if ($gets != null) {
            $url .= "?" . (is_array($gets) ? self::makeRawQuery($gets) : $gets);
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        if ($posts != null) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($posts) ? self::makeRawQuery($posts) : $posts);
        }
        if ($method == "POST") {
            curl_setopt($ch, CURLOPT_POST, true);
        } else if ($method == "HEAD") {
            curl_setopt($ch, CURLOPT_NOBODY, true);
        } else if ($method == "PUT" || $method == "BATCH" || $method == "DELETE") {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        }
        if (!is_null($headers) && is_array($headers)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }
        if (!is_null($closure)) {
            $closure($ch);
        }
        $response = curl_exec($ch);
        if ((curl_errno($ch) == 60)) {
            /* Invalid or no certificate authority found - Retrying without ssl */
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            $response = curl_exec($ch);
        }
        /* If you want to retry on failed status code */
        $retryCodes = array('401', '403', '404');
        $retries = 0;
        $retryCount = 3;
        $httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if (in_array($httpStatus, $retryCodes)) {
            do {
                $response = curl_exec($ch);
                $httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            } while (in_array($httpStatus, $retryCodes) && (++$retries < $retryCount));
        }
        if (curl_errno($ch)) {
            $response = curl_error($ch);
        }
        curl_close($ch);
        return array(
            "code" => $httpStatus,
            "response" => $response
        );
    }

    static function makeRawQuery($data, $keyPrefix = "")
    {
        $query = "";
        foreach ($data as $key => $value) {
            if (is_array($value)) {
                if (strlen($keyPrefix) > 0) {
                    $keyPrefixDummy = $keyPrefix . "[" . $key . "]";
                } else {
                    $keyPrefixDummy = $key;
                }
                $query = $query . self::makeRawQuery($value, $keyPrefixDummy);
            } else {
                if (strlen($keyPrefix) > 0) {
                    $key = $keyPrefix . "[" . $key . "]";
                }
                $query .= $key . "=" . rawurlencode($value) . "&";
            }
        }
        return rtrim($query, "&");
    }

    static function prettyPrint($o)
    {
        echo "<pre>";
        print_r($o);
        echo "</pre>";
    }
}