Ping host measured in microseconds

Problem

You want to ping a host on a given port and record time taken in microseconds.

The following solution uses PHP socket libraries to open a connection, to the given host and port – then just close it again. By obtaining the microseconds before and after, it is able to deduce time taken in microseconds.

Additionally I’ve added functionality to print the epoch, so the timestamp can be obtained.



Solution

pingStat.php


<?php
list($usec, $sec)=explode(" ",microtime());
$thisDate=sprintf("%f", ($usec+$sec));
$host="$argv[1]";
$port="$argv[2]";

if(!$host) {
die("Usage: $0 host port [ dtg ]n");
}

$fp = fsockopen("$host", $port, $errno, $errstr, 30);
if (!$fp) {

print("ping failed to host: $host:$port -
$errstr ($errno)n");

} else {

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

if($argv[3]) {
printf("%d:%0.4fn",time(),$nextDate-$thisDate);
} else {
printf("%0.4fn",$nextDate-$thisDate);
}

fclose($fp);

}

?>



Example


First example pings a host on port 80 and prints the current epoch.


$ php -q ./pingStat.php apachehost 80 y
1183524570:0.0824

Second example pings it again on port 443 and this time does not print epoch.


$ php -q ./pingStat.php apachehost 443
0.0775



Reference

[tags]Ping host measured in microseconds, PHP Coding School[/tags]



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).



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.



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





Useful PHP script – running queries against sybase database

Problem

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



Solution

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



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();
?>



Reference

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



display an image with a label superimposed

Problem

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



Solution

Why of course we use PHP extensive image library routines! ๐Ÿ™‚



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);

?>



Reference

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

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



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.



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.



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);

}

?>





making a thumbnail image on the fly

Problem

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



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.



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);

?>



Reference

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



converting a GIF to a PNG with PHP

Problem

You need to convert a GIF into a PNG.



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.



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);

?>



Reference

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



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. ๐Ÿ™‚

All will become clear shortly! ๐Ÿ™‚



Solution



Example


Following this link will help a bit, I hope! ๐Ÿ™‚ mysql demo

This 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).

For example:

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

Function:
MySQL Demo Query

The next example drives the interface, which can then be submitted to the function. Notice it pre-selects mysql as the db (this is just for demo purposes, the table does not exit and mysql db is not accessible as this user).

Interface:

MYSQL Web Interface

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.



Reference

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



Writing a wordpress plugin – 3 easy steps

Problem

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



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



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;

}
?>



Reference

Used everywhere on this site, including this post itself. ๐Ÿ™‚

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



showing syntax highlighted source

Problem

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



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.



Example


<?php highlight_file("transform.php"); ?>

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



Reference

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