How to sort numeric file name in php

How to sort numeric file name in php

I had to read files in a directory and sort them in numeric order, meaning that the file name has numbers in it.

Kind of like this

$unsortedArray = ["abc5.jpg", "abc3.jpg" "abc4.jpg", "abc1.jpg", "abc2.jpg"]

So if we want to sort them to get

$sortedArray = ["abc1.jpg", "abc2.jpg" "abc3.jpg", "abc4.jpg", "abc5.jpg"]

We just got to use the in-built php functions natsort and array_values (available in PHP 4 onwards). I believe that natsort is a wrapper around sort . This is also known as natural sorting or natural sort order. Code is available below

 if( natsort($unsortedArray) ) {
     // Re-index the array
     $files = array_values($files); 
     return $files;
 }

That’s all !

Enjoyed the content ? Share it with your friends !

Disk Scheduling Algorithm Implementation in Java

Disk Scheduling Algorithm Implementation in Java

 

/**
 * 
 * @param current  : current position
 * @param sequence : sequence of positions
 * @return
 */
private int[] arrangeBySSTF(int current, int sequence[])
{
    int n = sequence.length;
    int sstf[] = new int[n];
    for(int i = 0;i < n;i ++)
    {
        sstf[i] = sequence[i];
    }
    
    int ii = -1;
    for(int i = 0;i < n;i ++)
    {
        int minimum = Integer.MAX_VALUE;
        ii = i;
        for(int j = i;j < n;j ++)
        {
            int distance = Math.abs(current - sstf[j]);
            if( distance < minimum )
            {
                ii = j;
                minimum = distance;
            }
        }
        int tmp = sstf[i];
        sstf[i] = sstf[ii];
        sstf[ii] = tmp;
        current = sstf[i];
    }
    return sstf;
}

/**
 * 
 * @param previous position
 * @param current position
 * @param sequence of positions
 * @return
 */
private int[] arrangeBySCAN(int previous, int current, int sequence[])
{
    boolean isLeft = false;
    int scanSequence[] = new int[sequence.length+1]; //+1 for boundary
    int scanSeqIndex = 0;
    
    int sortedArray[] = sequence.clone();
    
    Arrays.sort(sortedArray);
    
    int result = Arrays.binarySearch(sortedArray, current);
    int index = result;
    if( result < 0 )
        index = -(result + 1);
    
    System.out.println("Index : " + index);
    //index -= 1;
    
    if( previous > current )
        isLeft = true; 
    
    if( !isLeft )
    {
        for(int i=index;i < sequence.length;i ++)
            scanSequence[scanSeqIndex++] = sortedArray[i];
        
        scanSequence[scanSeqIndex++] = dp.getCylinders(); 
        
        for(int i=index-1;i >= 0;i --)
            scanSequence[scanSeqIndex++] = sortedArray[i];
    }
    else
    {
        //untested?
        for(int i=index-1;i >= 0;i --)
            scanSequence[scanSeqIndex++] = sortedArray[i];
        
        scanSequence[scanSeqIndex++] = 0; //0 is the assumed left boundary
        
        for(int i=index;i < sequence.length;i ++)
            scanSequence[scanSeqIndex++] = sortedArray[i];
        
    }
    return scanSequence;
}

/**
 * Return the sequence based on LOOK algorithm
 * @param previous 	: previous position 
 * @param current 	: current position
 * @param sequence	: sequence of positions
 * @return
 */
private int[] arrangeByLOOK(int previous, int current, int sequence[])
{
    boolean isLeft = false;
    int scanSequence[] = new int[sequence.length]; //+1 for boundary
    int scanSeqIndex = 0;
    
    int sortedArray[] = sequence.clone();
    
    Arrays.sort(sortedArray);
    
    //find the index if the element would to be inserted
    //if not found, returns  (-(insertion point) - 1)
    int result = Arrays.binarySearch(sortedArray, current); 
    int index = result;
    if( result < 0 )
        index = -(result + 1);
    
    System.out.println("Index : " + index);
    
    if( previous > current )
        isLeft = true; 
    
    if( !isLeft )
    {
        for(int i=index;i < sequence.length;i ++)
            scanSequence[scanSeqIndex++] = sortedArray[i];
        
        for(int i=index-1;i >= 0;i --)
            scanSequence[scanSeqIndex++] = sortedArray[i];
    }
    else
    {
        //untested?
        for(int i=index-1;i >= 0;i --)
            scanSequence[scanSeqIndex++] = sortedArray[i];
                
        for(int i=index;i < sequence.length;i ++)
            scanSequence[scanSeqIndex++] = sortedArray[i];
        
    }
    return scanSequence;
}

Will post the full solution soon

Enjoyed the content ? Share it with your friends !

Analysis on modern game anti-cheat

analysis on modern game anti-cheat

 

A brief overview of anti-cheats

Anti-cheats have been in games for about two decades or more already. Anti-cheat systems such as Punkbuster are one of the earlier products that was implemented or integrated into games

The necessity of anti-cheats

Anti-cheats are extremely important to games now as there are many people looking to cheat in games for various reasons – be it money, fun or winning.Regardless of the reason, it always has a detrimental effect to other innocent players, and to the game community and economy.

With information, software and tools readily available with a quick search on google, people are easily able to find ways to cheat in games. These people are often known as Script Kiddies

Current outlook of cheaters

Statistics show that script kiddies make up for about 90% of the hackers in the world. About 6-8% are intermediately skilled, while a measly 2-4% are advanced in this field.

Current outlook of anti-cheats

As cheaters get more advanced, so must the anti-cheats. However, this is a cat and mouse game that unfortunately favors the cheaters or hackers. This is because anti-cheat systems are often reactive security rather than proactive security.

Conclusion

As long as a game exist, it will be targeted by hackers.As long as the game can be ran or played, it can be hacked and probably will sooner or later. The key is to limit and control whatever data that is important (such as in-game currency) on the server side, rather than on the client side(which is the game)

 

Enjoyed the content ? Share it with your friends !

Html post and get values outside a form

Html post AND get values outside a form

Retrieving html post and get values outside a form will come in handy when you are taking the page layout and design into consideration. Sometimes, you do not want a button or textfield to be where your form is but yet want to get the value of the element on the server side

a normal form looks like

<form>
  <button type='submit' value='submit'/>
</form>

so to be able to retrieve input value outside a form, you have to first give your form an id

<form id='submitForm'>
  <button type='submit' value='submit'/>
</form>

Lets say you have a textbox outside the form that you want to post/get together with your form when the submit button is pressed. You just have to give it the attribute ‘form=form_id’ like so,

<input type='text' name='txt' form='submitForm'/>

So finally you have something like this for the html

<input type='text' name='txt' form='submitForm'/>
<form id='submitForm'>
  <button type='submit' value='submit'/>
</form>

On the server side, for example in PHP, you would get your $_POST or $_GET as per normal like so,

<?php
$txt = $_POST["txt"];
echo "<p> The text you entered is $txt </p>";
?>

 

Enjoyed the content ? Share it with your friends !

How to take screenshot of url with PHP

How to take screenshot of url with PHP

Here is an example and source code of how to take screenshot of url with php. I have taken this code from one of my projects. It is also able to handle https and optionally, follow through with redirects.

Requirements :
-PhantomJS standalone executable(.exe)
-PHP library for phantomjs

Setup :

  1. Follow the installation for PHP PhantomJS here
  2. Set the path to your phantomjs executable file in the code

    $client->getEngine()->setPath(__DIR__.’/bin/phantomjs.exe’);

    Note : You may have to rename /bin/phantomjs to /bin/phantomjs.exe

Additional features :
– customize width/height of screenshot
– support http and https
– follow redirects

 

require 'vendor/autoload.php';

use JonnyW\PhantomJs\Client;


function get_redirect_url($url)
{
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_HEADER, true);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Set to true to make curl follow the url
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$a = curl_exec($ch); 
	$url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); // This gets the last location/url after all the redirection has been followed through

	return $url;
}
function get_http_response_code($url)
{
	$ch = curl_init($url);
	curl_exec($ch);
	$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	return $code;
}
function is_redirect($url) 
{
	$code = get_http_response_code($url);
	if (($code == 301) || ($code == 302)) {
		return true;
	}
	return false;
}



function screenshot($width, $height, $url, $filePath="file.jpg", $followRedirect=false)
{
        $path = pathinfo($filePath);
        $directory = $path['dirname'];

	if( $followRedirect && is_redirect($url) ) 
	{
		$redirectedUrl = get_redirect_url($url);
		echo "{$url} redirects to {$redirectedUrl} <br/>";
		$url = $redirectedUrl;
	}		

	// Ensure the path is writable to PhantomJS/PHP
	if( !is_writable($filePath) )
	{
		//echo "$directory of $filePath is not writable. Chmod-ing <br />";
		//return false;
	}

	$client = Client::getInstance();
	$client->getEngine()->setPath(__DIR__.'/bin/phantomjs.exe');
	// HTTPS support
	$client->getEngine()->addOption('--ssl-protocol=any');
	$client->getEngine()->addOption('--ignore-ssl-errors=true');
	$client->getEngine()->addOption('--web-security=false');

	$width  = $width ? $width : 1280;  // Note : Specifying a 800x600 may be too small and result in @media css determining
	$height = $height ? $height : 800; // it to be a mobile instead of desktop. Generally a 1280x800 should be good.
	$top    = 0;
	$left   = 0;


	//@see JonnyW\PhantomJs\Http\CaptureRequest
	$request = $client->getMessageFactory()->createCaptureRequest($url, "GET"); //('http://jonnyw.me', 'GET');
	$request->setOutputFile($filePath);
	$request->setViewportSize($width, $height);
	$request->setCaptureDimensions($width, $height, $top, $left);
	$request->setDelay(3); // Depends on how long it takes for the webpage to fully load. this vs setTimeout(x) ?
	$request->setTimeout(1000); // Not sure the diff between setDelay and setTimeout though...

	//@see JonnyW\PhantomJs\Http\Response 
	$response = $client->getMessageFactory()->createResponse();

	// Send the request
	$client->send($request, $response);
	
	return file_exists($filePath); // Check if screenshot exists
}

 

Enjoyed the content ? Share it with your friends !