Monday, September 25, 2017

Clear previously set headers php | How to fix “Headers already sent” error in PHP

headers_sent indicates that it is too late to remove headers. They're already sent. Hence the name of the function.

What you want is to specifically check if the headers have not been sent yet. Then you know it's safe to modify them.


<?php
header('Content-type: application/csv');

if (!headers_sent()) {
    echo "<pre>";
    print_r(headers_list());
    echo "</pre>";
}

header_remove();
header('Content-type: text/html');
echo "HERE";


Array
(
    [0] => X-Powered-By: PHP/7.0.9
    [1] => Content-type: application/csv
)
HERE

Monday, September 18, 2017

Stripe Using Connect with Deferred Standard Accounts | Stripe Create Deferred Standard Account | Stripe Create Connected Account Using API Call

1 Login to your stripe account and navigate to https://dashboard.stripe.com/account/applications/settings and follow below steps:









2. Now have to create Deferred (standard) account using below code snippet (API call). Later account holder will login to their account and complete their verification process:



<?php
include_once "curl.php";

$api_key = "sk_test_eXF..........jWrcHK95rwj";
$url = "https://api.stripe.com/v1/accounts";

$params = array(
    "type" => "standard",
    "country" => "AU",
    "email" => "pritomkucse+stripe1@gmail.com"
);

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

$result = CurlExecutor::execute($url, "POST", null, $params, $headers);
$result["response"] = json_decode($result["response"]);
CurlExecutor::prettyPrint($result);

Successful output would be like below:


Array
(
    [code] => 200
    [response] => stdClass Object
        (
            [id] => acct_1B3......1R7ddx6
            [object] => account
            [business_logo] => 
            [business_name] => 
            [business_url] => 
            [charges_enabled] => 1
            [country] => AU
            [default_currency] => aud
            [details_submitted] => 
            [display_name] => 
            [email] => pritomkucse+stripe1@gmail.com
            [keys] => stdClass Object
                (
                    [secret] => sk_test_wel..........5fXfyBsmhI6
                    [publishable] => pk_test_mlPoU..........zBUbHBFof
                )

            [metadata] => stdClass Object
                (
                )

            [payouts_enabled] => 
            [statement_descriptor] => 
            [support_email] => 
            [support_phone] => 
            [timezone] => Etc/UTC
            [type] => standard
        )

)

Use "keys/secret" (actually it is "Secret key" for API), you can use this Key to process all your transactions.

And list of your connected account is below:




Stripe Using Connect with Standard Accounts | Stripe Create Standard Account

1 Login to your stripe account and navigate to https://dashboard.stripe.com/account/applications/settings and follow below steps:








2. Copy Client ID and follow below PHP script (which will redirect target users to Stripe application page to fill up their personal details to create and account with Stripe):



<?php
$client_id = "ca_BPnCyPD...........ODApFdHyTXHbwQ";
$auth_url = "https://connect.stripe.com/oauth/authorize?".
    "response_type=code&client_id=$client_id&scope=read_write".
    "&redirect_uri=".rawurlencode("http://localhost/ci/dragon71/stripe/callback.php").
    "&state=".md5(trim(true));
header("Refresh:0; url=$auth_url");

3. After completing procedures there, Stripe will redirect back to our target redirect URL as below:


http://localhost/ci/dragon71/stripe/callback.php?state=c4ca4238a0b923820dcc509a6f75849b&scope=read_write&code=ac_BQGZyHtVkFbOFYhNPTlAdbZeZcMutzec

If fails then:

http://localhost/ci/dragon71/stripe/callback.php?state=c4ca4238a0b923820dcc509a6f75849b&error=access_denied&error_description=The+user+denied+your+request

4. One thing we forgot, have to collect our API Key to request API call, navigate to https://dashboard.stripe.com/account/apikeys to collect your API Key's.




5. After successful redirect back, it's time to collect access token to procedure further. 


<?php
include_once "curl.php";

$api_key = "sk_test_eXF4.........jWrcHK95rwj";
$url = "https://connect.stripe.com/oauth/token";

$params = array(
    "code" => $_GET["code"],
    "grant_type" => "authorization_code"
);

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

$result = CurlExecutor::execute($url, "POST", null, $params, $headers);
$result["response"] = json_decode($result["response"]);
CurlExecutor::prettyPrint($result);

Successful output would be like below:


Array
(
    [code] => 200
    [response] => stdClass Object
        (
            [access_token] => sk_test_oWtb.........xb4tLBXqZmh
            [livemode] => 
            [refresh_token] => rt_BQGsyumxyAoDH....................aPMt5MvpprSnpwD
            [token_type] => bearer
            [stripe_publishable_key] => pk_test_xHhgw.........zfo0QYltBB
            [stripe_user_id] => acct_1B3........3aeEh
            [scope] => read_write
        )

)

Use "access_token" (actually it is "Secret key" for API), you can use this Key to process all your transactions.

And list of your connected account is below:




Sunday, September 10, 2017

The Complete Guide to Creating Symbolic Links | How to create a Symbolic Link on Windows

mklink creates a symbolic link to a file. The below command creates a symbolic, or “soft”, link at Link pointing to the file Target :

mklink "c:\tmp\a.txt" "c:\tmp\b.txt"

will create link a.txt (destination) that is equal to b.txt (source)

Use /D to create soft link pointing to a directory. like so:

mklink /D "c:\tmp\dir_destination" "c:\tmp\dir_source"

Use /H to create hard link pointing to a file:

mklink /H "c:\tmp\dir_destination" "c:\tmp\dir_source"

Use /J to create hard link pointing to a directory, also known as a directory junction:


mklink /J "c:\tmp\dir_destination" "c:\tmp\dir_source"

mklink /J Link Target

And below command will remove symbolic link on a drive:

rmdir "c:\tmp\dir_destination"


Friday, September 8, 2017

jQuery Detect when browser receives file download | Detecting the File Download Dialog In the Browser

Client Side:

<script src="./../jquery-2.1.4.js"></script>

<script type="text/javascript">
$(document).ready(function () {

var downloadToken = new Date().getTime();

$("button").click(function () {
    downloadToken = new Date().getTime();
    $("[name='downloadToken']").val(downloadToken);
    $("form").trigger("submit");
    timer();
});

function timer() {
    var attempts = 100; /* As you required */
    var downloadTimer = window.setInterval(function () {
        var token = getCookie("downloadToken");
        attempts--;

        if (token == downloadToken || attempts == 0) {
            $(".log").prepend("Browser received file from server<br/>");
            window.clearInterval(downloadTimer);
        }
        else {
            $(".log").prepend("Browser not received file from server yet<br/>");
        }
    }, 1000);
}

function parse(str) {
    var obj = {};
    var pairs = str.split(/ *; */);
    var pair;
    if ('' == pairs[0]) return obj;
    for (var i = 0; i < pairs.length; ++i) {
        pair = pairs[i].split('=');
        obj[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
    }
    return obj;
}

function getCookie(name) {
    var parts = parse(document.cookie);
    return parts[name] === undefined ? null : parts[name];
}

});
</script>

<form action="download.php" method="post">
    <input type="hidden" name="downloadToken"/>
    <button type="button">Download</button>
    <div class="log"></div>
</form>

Server Side Script as of PHP:

<?php
$file_name = "download.zip";
header('Content-Description: File Transfer');
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename=download.zip');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file_name));

// Sleep 5 seconds...
sleep(5);

// Cookie will be expire after 20 seconds...
setcookie("downloadToken", $_POST["downloadToken"], time() + 20, "");

ob_clean();
flush();
readfile($file_name);

Browser Screenshot:






Thursday, September 7, 2017

Finding IP Address of my computer using VBScript | Retrieve Your Computer's IP Address | IP Address and Computer Name VBscript | How to get the IP Address for your Local Area Connection on Windows

dim NIC1, Nic, StrIP, CompName

Set NIC1 = GetObject("winmgmts:").InstancesOf("Win32_NetworkAdapterConfiguration")

For Each Nic in NIC1
    if Nic.IPEnabled then
        StrIP = Nic.IPAddress(i)

        Set WshNetwork = WScript.CreateObject("WScript.Network")
        CompName = WshNetwork.Computername

        MsgBox "IP Address:  " & StrIP & vbNewLine _
            & "Computer Name:  " & CompName, 4160, "IP Address and Computer Name"

        wscript.quit
    End if
Next


Sunday, September 3, 2017

jQuery get exact position of element | get exact left top position of jQuery element

Below is code snippet

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jQuery Position of Element</title>
    <script src="jquery-2.1.4.js"></script>
    <script type="text/javascript">
        $(document.body).ready(function() {
            var body = $(document.body), element = body.find(".element"),
                    log = body.find(".log");
            var rect = element[0].getBoundingClientRect();
            log.append("<p>LEFT==" + rect.left + "</p>");
            log.append("<p>TOP==" + rect.top + "</p>");
            log.append("<p>RIGHT==" + rect.right + "</p>");
            log.append("<p>BOTTOM==" + rect.bottom + "</p>");
            log.append("<p>WIDTH==" + rect.width + "</p>");
            log.append("<p>HEIGHT==" + rect.height + "</p>");
        });
    </script>
</head>
<body style="margin:0">
<div style="position:relative;width:100%;height:100%;margin:0">
    <div class="element" style="position:absolute;margin:0;left:170px;top:200px;border:1px solid red;width:100px;height:30px;"></div>
</div>
<div class="log" style="font-weight:bold;"></div>
</body>
</html>

And output is below: