Thursday, April 19, 2018

How to get current time in milliseconds in PHP | Converting microtime() to milliseconds/seconds

The short answer is
$milliseconds = round(microtime(true) * 1000);
Use microtime(). This function returns a string separated by a space. The first part is the fractional part of seconds, the second part is the integral part. Pass in true to get as a number:
var_dump(microtime()); // string(21) "0.89115400 1283846202"
var_dump(microtime(true)); // float(1283846202.89)
64 bits platforms only!
function milliseconds() {
    $mt = explode(' ', microtime());
    return ((int)$mt[1]) * 1000 + ((int)round($mt[0] * 1000));
}

Wednesday, April 11, 2018

Using PHP's glob() function to find files in a directory | Filter files in directory | Regex filter files in directory

The examples below look at a directory with the following, the same example directory as used in the read through directory post
To find all the files in the directory /path/to/directory with a .txt file extension, you can do this:
$files = glob("/path/to/directory/*.txt");
Array
(
    [0] => /path/to/directory/bar.txt
    [1] => /path/to/directory/foo.txt
    [2] => /path/to/directory/link2foo.txt
)
There are flags which can be passed as a second optional parameter. One of these is GLOB_BRACE which means that e.g. {jpg,gif,png} will be expanded to match jpg, gif and png which can be useful if you need to look for a particular set of files by their extension, in this example for image files
$files = glob("/path/to/directory/*.{jpg,gif,png}", GLOB_BRACE);
Array
(
    [0] => /path/to/directory/1.jpg
    [1] => /path/to/directory/2.gif
    [2] => /path/to/directory/3.png
)

Can a PHP script execute common code before exit() | register_shutdown_function | PHP execute a piece of code before process terminated by exit() or die() method

Registers a callback to be executed after script execution finishes or exit() is called.
Multiple calls to register_shutdown_function() can be made, and each will be called in the same order as they were registered. If you call exit() within one registered shutdown function, processing will stop completely and no other registered shutdown functions will be called.
<?php
function shutdown()
{
    // This is our shutdown function, in 
    // here we can do any last operations
    // before the script is complete.

    echo 'Script executed with success', PHP_EOL;
}

register_shutdown_function('shutdown');
?>
<?php 
namespace App\Test;

class CallbackClass { 
    function CallbackFunction() { 
        // refers to $this 
    } 

    function StaticFunction() { 
        // doesn't refer to $this 
    } 
} 

function NonClassFunction() { 
} 
?> 

there appear to be 3 ways to set a callback function in PHP (using register_shutdown_function() as an example): 

1: register_shutdown_function('NonClassFunction'); 

2: register_shutdown_function(array('\App\Test\CallbackClass', 'StaticFunction')); 

3: $o =& new CallbackClass(); 
   register_shutdown_function(array($o, 'CallbackFunction')); 

Friday, April 6, 2018

How to Make Async Requests in PHP | Methods for synchronous processes in PHP | Making synchronous function call in PHP | Make sure same function will not execute parallel


<?php
function executeSync($key, $closure) {
    $sem = getSemGetCustom($key);
    if(getSemAcquireCustom($sem)) {
        $closure();

        getSemReleaseCustom($sem);
    }
    else {
        throw new \Exception("Processing");
    }
}

function getSemGetCustom($key) {
    return fopen(sys_get_temp_dir() . DIRECTORY_SEPARATOR . md5($key) . '.sem', 'w+');
}

function getSemAcquireCustom($sem) {
    return flock($sem, LOCK_EX);
}

function getSemReleaseCustom($sem) {
    return flock($sem, LOCK_UN);
}

function logText($text) {
    file_put_contents('data.txt', $text.PHP_EOL , FILE_APPEND | LOCK_EX);
}

$id = $_GET["id"];
$closure = function() use($id) {
    logText("STARTING-$id");
    sleep(1);
    logText("FINISHED-$id");
};

executeSync("KEY", $closure);
Or if you want to set timeout for lock
<?php
public static function lockAndExecute($key, Closure $closure, $timeout_seconds = 5) {
    $file = sys_get_temp_dir() . DIRECTORY_SEPARATOR . md5($key) . '.tmp';
    $handle = fopen($file, 'w+');
    while (!flock($handle, LOCK_EX | LOCK_NB)) {
        usleep(1000 * 249);
        $timeout_seconds = $timeout_seconds - 0.25;
        if ($timeout_seconds <= 0) {
            throw new Exception("Unable to acquire lock");
        }
    }
    try {
        return $closure();
    }
    finally {
        flock($handle, LOCK_UN);
        fclose($handle);
    }
}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Custom Popup</title>
    <meta name="viewport" content="user-scalable=yes, initial-scale=1, maximum-scale=1,minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi"/>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $.get("exec.php", { id: 1 });
            $.get("exec.php", { id: 2 });
            $.get("exec.php", { id: 3 });
            $.get("exec.php", { id: 4 });
            $.get("exec.php", { id: 5 });
            $.get("exec.php", { id: 6 });
            $.get("exec.php", { id: 7 });
            $.get("exec.php", { id: 8 });
            $.get("exec.php", { id: 9 });
            $.get("exec.php", { id: 10 });
        });
    </script>
</head>
<body>

</body>
</html>

You can see that function "executeSync" executing synchronously.

Friday, March 30, 2018

jquery select first x number of elements | Selecting the first “n” items with jQuery

Quick jQuery snippet to select first x number of elements. You can also use the jQuery .slice() function which can chop up element groups into a range for you with a combination of .get();
$("a").slice(0,20)
lso you can use lt pseudo selector: This matches the elements before the nth one (the nth element excluded). Numbering starts from 0
$(“a:lt(n)”)
Because :lt() is a jQuery extension and not part of the CSS specification, queries using :lt() cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. For better performance in modern browsers, use $("your-pure-css-selector").slice(0, index) instead

What's the best way to retry an AJAX request on failure using jQuery | The best way to retry an AJAX request on failure using jQuery | jQuery AJAX retry

$.ajax({
    url: 'http://',
    type: 'POST',
    data: {},
    tryCount: 0,
    retryLimit: 3,
    success: function (response) {
        //do something
    },
    error: function (xhr, textStatus, errorThrown) {
        this.tryCount++;
        if (this.tryCount <= this.retryLimit) {
            //try again
            $.ajax(this);
            return;
        }
        if (xhr.status == 500) {
            //handle error
        }
        else {
            //handle error
        }
    }
});

Thursday, March 15, 2018

Convert 1 Satak to Square Feet ( sq ft ) easily

Convert 1 Satak to Square Feet ( sq ft ) easily

This conversion calculator is very easy to find Satak to Square Feet. This measurement may separate from place to place. Satak is a Bangla word, so the people spell it different way in English. Someone also says shotok, sotok, sotangso, shotangsho etc. I think the following list of area conversion's will meet all your asking.
From
To
Others Area Conversion List
To Others Unit
4 Satak = 0.04 Acre
4 Satak = 1.6187441354899246 Ayer
4 Satak = 0.12100000000000001 Bigha
4 Satak = 38.72 Chotak
4 Satak = 4 Decimal
4 Satak = 1016.399999997459 Dhul
4 Satak = 145.20000000000002 Dondho
4 Satak = 2.0166666666666666 Gonda
4 Satak = 0.016187441354899246 Hectare
4 Satak = 32.266666666666666 Kak
4 Satak = 0.10083333333333334 Kani
4 Satak = 2.42 Katha
4 Satak = 24.200000000000003 Kontho
4 Satak = 8.066666666666666 Kora
4 Satak = 24.000000000000004 Kranti
4 Satak = 400.00000000000006 Ojutangsho
4 Satak = 30492.0000015246 Renu
4 Satak = 4 Satak
4 Satak = 4 Shotangsho
4 Satak = 0.4 Square Chain
4 Satak = 1742.4 Square Feet
4 Satak = 774.4000000000001 Square Hat
4 Satak = 250905.7605796868 Square Inchi
4 Satak = 161.8744135489925 Square Meter
4 Satak = 193.60000000000002 Square Yard
4 Satak = 480.00000000000006 Til