pinging host measured in micro seconds

[problem]

You have a requirement to capture network speed, in microseconds.

The required speed was less than 0.25 of a second (or quarter of second).

[/problem]

[solution]

We use PHP to capture the current time in microseconds. Run a system ping command. Capture the new time and minus one from the other.

[/solution]

[example]

Here’s the PHP code, using the microtime function and a simple ping.

<?php

list($usec, $sec)=
explode(" ",microtime());

$thisDate=sprintf("%f", ($usec+$sec));

$host="$argv[1]";

system("ping -c1 $host > /dev/null 2>&1",$response);

if($response==0) {

list($usec, $sec)=explode(" ",microtime());

$nextDate=sprintf("%f", ($usec+$sec));

printf("%0.4fn",$nextDate-$thisDate);

} else {

print("ping failed to host: $hostn");

}

?>

Here is a run through:

$ php -q pingHost.php bagend
0.0098
$ php -q pingHost.php bagend
0.0066
$ php -q pingHost.php bagend
0.0065
$ php -q pingHost.php bagend
0.0066

[/example]

[reference]

[tags]UNIX, Network testing, ping, PHP, microtime, PHP Coding School[/tags]

[/reference]

Useful PHP script – running queries against sybase database

[problem]

you want to run queries against a Sybase Database, using the PHP API.

[/problem]

[solution]

A PHP script using sybase API for PHP, connect as given user, with your password on specific host.

[/solution]

[example]

Useful for monitoring sybase dbs, although in this instance it does not actually hit any database tables.

<?php

$user = "your_user";
$passwd = "password";
$host = "your_host";
$sql="select getdate(), @@version ";
$conn=sybase_connect($host,$user,$pass); // connect to db
print("running query host: $hostnuser: $usern");
$result = sybase_query ( $sql ); // Run query and store in array
$i = 0;
while($row = sybase_fetch_array($result)) {
// Loop around the array and print field or column 1 and 2
$i++;
$item1 = $row[0];
$item2 = $row[1];
echo "$i $item1 $item2";
}
sybase_close();
?>

[/example]

[reference]

[tags]Sybase PHP example, PHP Coding School[/tags]

[/reference]

display an image with a label superimposed

[problem]

You want to generate an image, with text over the top.

[/problem]

[solution]

Why of course we use PHP extensive image library routines! 🙂

[/solution]

[example]

<?php

header(“Content-type: image/png”);
$string = $_GET[‘label’];

if(isset($_GET[‘font’])) { $font = $_GET[‘font’]; } else { $font=“2″; }
$len=strlen($string);
$text_width = imagefontwidth($font);
$text_height = imagefontwidth($font);
/* Create a blank image */
$im = imagecreate (($len*$text_width)+10, $text_height+10);
$bgc = imagecolorallocate ($im, 0, 0, 0);
$tc = imagecolorallocate ($im, 255, 255, 255);
imagefilledrectangle ($im, 0, 0, 150, 30, $bgc);
imagestring ($im, $font, 5, 0, “$string”, $tc);
imagepng($im);
imagedestroy($im);

?>

[/example]

[reference]

I’ve now created an online tool, using this code Label Your Images

[tags]Image Creation, Label Image, PHP Coding School[/tags]

[/reference]

PHP and AJAX tool to transform text

[problem]

You want to transform text form ascii to base64, urlencode it, digest it, etc.

Or you want to decode these formats.

[/problem]

[solution]

Just wrote this tool, to allow instant transformation of data into following formats:

base64 encode decode, urlencode decode, md5 and sha1 hashing, addslashes and htmlentities

click here to access the transform tool
Pretty cool to see ‘all’ too – check it out.

[/solution]

[example]

Here is the code:


<?php

if(isset($_GET['mode'])) {

$mode=urlencode($_GET['mode']);

$val=$_GET['val'];

switch($mode) {

case "base64_encode": echo base64_encode($val); break;
case "base64_decode": echo base64_decode($val); break;
case "urldecode": echo urldecode($val); break;
case "urlencode": echo urlencode($val); break;
case "htmlentities": echo htmlentities($val); break;
case "rot13": echo str_rot13($val);break;
case "md5": echo md5($val);break;
case "sha1": echo sha1($val);break;
case "all":

echo "base64_encode: ".base64_encode($val);
echo "base64_decode: ".base64_decode($val);
echo "urldecode: ".urldecode($val);
echo "urlencode: ".urlencode($val);
echo "htmlentities: ".htmlentities($val);
echo "addslashes: ".addslashes($val);
echo "rot13: ".str_rot13($val);
echo "md5: ".md5($val);
echo "sha1: ".sha1($val);
break;

}

exit(0);

}

?>

[/example]

[reference]

[tags]AJAX Tool, PHP AJAX, PHP Coding School[/tags]

[/reference]

making a thumbnail image on the fly

[problem]

You need to make a thumbnail of an image, on the fly.

[/problem]

[solution]

Here is a short PHP script to make a thumbnail out of the image.

It takes two arguments, one for the image’s file name and one for the compression rate.

[/solution]

[example]

displayThumb.php
<?php

$filename = $_GET['filename'];
$compression = $_GET['compression'];

Header("Content-type: image/png");

$im = imagecreatefrompng("$filename");

$currWidth=ImageSX($im);
$currHeight=ImageSY($im);

$newWidth=$currWidth * ($compression / 100);
$newHeight=$currHeight * ($compression / 100);

$im1 = imagecreatetruecolor($newWidth,$newHeight);
$bgc = imagecolorallocate ($im1,255,255,255);
imagefilledrectangle ($im1, 0, 0, $newWidth, $newHeight, $bgc);
imagecopyresampled ($im1, $im, 0, 0, 0, 0,
$newWidth, $newHeight, $currWidth, $currHeight);
imagepng($im1);
imagedestroy($im1);

?>

[/example]

[reference]

[tags]Image manipulation, thumbnail creation on the fly, PHP Coding School[/tags]

[/reference]

converting a GIF to a PNG with PHP

[problem]

You need to convert a GIF into a PNG.

[/problem]

[solution]

Another short bit of PHP, which takes a GIF filename as a parameter and a compression tag,
so you can convert to PNG and change size too.

If you don’t want to compress the image, just use a value of 100.

[/solution]

[example]

convertGifPng.php

<?php

$filename = $argv[1];
$compression = $argv[2];

Header("Content-type: image/png");

$im = imagecreatefromgif("$filename");

$currWidth=ImageSX($im);
$currHeight=ImageSY($im);

$newWidth=$currWidth * ($compression / 100);
$newHeight=$currHeight * ($compression / 100);

$im1 = imagecreatetruecolor($newWidth,$newHeight);
$bgc = imagecolorallocate ($im1,255,255,255);
imagefilledrectangle ($im1, 0, 0, $newWidth, $newHeight, $bgc);
imagecopyresampled ($im1, $im, 0, 0, 0, 0,
$newWidth, $newHeight, $currWidth, $currHeight);
imagepng($im1);
imagedestroy($im1);

?>

[/example]

[reference]

[tags]Convert Images GIF PNG, PHP Coding School[/tags]

[/reference]

PHP MySQL Web Interface

[problem]

Having written a ga-zillian scripts, to query dbs, decided it would be much simpler to call just one function multiple times, duh! 🙂

Then fulfilling business request after request – with many short php web pages calling the function. Decided to progressing this further – by removing the web page altogether (hitting the function via a wrapper). Let it handle the query, via variable parameters passed in on the HTTP GET.

This posed a bit of problem, pushing complexity on the enquirer. So then decided to write a web (interface) form to drive the function (wrapper) – which subsequently made the query. 🙂

Moved to github – View here

The web interface prepares the fields, which are subsequently submitted to the function for you.

You may notice that run_q is a PHP script, this is so you can either e-mail links directly to the function (genericQuery.php) or to this interface (run_q.php).

This query selects all fields and rows with a limit of 2 rows, to be returned – directly submitted to the function.

After the interface submits, the subsequent query to the function can be cut and paste from the browser address bar.

Also this interface shows all the possible functions, where you can get quite creative in your query – try it out.

[/problem]

[reference]

[tags]PHP MySQL Web Interface, PHP Coding School[/tags]

[/reference]

Writing a wordpress plugin – 3 easy steps

[problem]

You want to create a wordpress plugin, which substitutes your tags for HTML.

[/problem]

[solution]

This was a million times easier than I thought it was going to be. 🙂

step 1: mkdir wordpress/wp-content/plugins/YourPluginName

step 2: vi wordpress/wp-content/plugins/YourPluginName/Your Plugin Name.php

step 3: activate your plugin

[/solution]

[example]

Here I want to substitute the following tags, with content wrapping.

[problem] … [/problem]

Put simply 😉


/*

Plugin Name: php-coding-school
Plugin URI: http://php.coding-school.com/php-coding.school.php
Description: wraps content, etc
Version: 1.0
Author: marcus
Author URI: http://php.coding-school.com

*/

add_filter('the_content', 'mp_wrap_content');

function mp_wrap_content($content) {

$search_strings='Your pattern to replace';

$end_strings='Your replacement';

$content = str_replace($search_strings,$end_strings, $content);
...
return $content;

}
?>

[/example]

[reference]

Used everywhere on this site, including this post itself. 🙂

[tags]Wordpress Plugin Tutorial, PHP Coding School[/tags]

[/reference]

showing syntax highlighted source

[problem]

Want to display PHP code with syntax highlighting (colors). This helps with debugging, etc.

[/problem]

[solution]

Within PHP you can nicely display colorful text, which can be very useful for debugging or just to showcase your code.

We simply use the highlight_file function within PHP, like this below.

[/solution]

[example]

<?php highlight_file(“transform.php”); ?>

For a real-life demo, take a look here:

[/example]

[reference]

[tags]PHP Syntax Highlighting, PHP Coding School[/tags]

[/reference]

Useful PHP code – guestbook counter

[problem]

You want to display a counter on your web page, but you do not want to use a db.

[/problem]

[solution]

All you need to make this work is echo “1” into a file called counter and ensure the web user has write access. For example: $ echo 1 > counter; chmod 777 counter;

[/solution]

[example]

<?php

$fh=fopen(“/tmp/counter.txt”, “r”);
$cnt=fread($fh,filesize(“/tmp/counter.txt”));
fclose($fh);
$fh=fopen(“/tmp/counter.txt”, “w+”);
if(fputs($fh,($cnt+1))) { print(“You are visitor: $cntn”); }
fclose($fh);

?>


[/example]

[reference]

[tags]PHP Guest Book, PHP Coding School[/tags]

[/reference]