Sunday, 13 January 2013

PHP Tutorial - the wonderful world of hello

Ok the second tutorial will be simple its hello world.  Ok so I'll write some code I'll use two minus signs to represent all the code in the file.  The first double minus sign will be followed by the file name  so here is the first version of hello world

--hello.php
hello world
--

as you can see there is not even a php processor tag involved.  So what would it look like if we used php to write the code well one of three ways


--hello1.php
<?php
print "hello world";
?>


--hello2.php

<?php
echo "hello world";
?>

--hello3.php

<?="hello world";?>



OK lets go a step further and get it to say our name with it defaulting to world if no name supplied

--hello4.php
<?php
$name = isset($_GET["name"])?$_GET["name"]:"world";
// the following will write out the same text in different ways
// concatenate the two strings together
print "hello " . $name;
// with double quotes we dont need to concatenate two string together.
print "hello $name";
?>

You can test this by running this file via a web server and through your browser

hello4.php
hello4.php?name=test

Ok still with me  then how about an image that writes hello world to the screen

--hello5.php

<?php
header('Content-Type: image/png');

// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 10, 5, 5,  "HELLO WORLD", $text_color);

// Output the image
imagepng($im);

// Free up memory
imagedestroy($im);
?>



--hello6.php

<?php
header('Content-Type: image/png');

// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);

$name = isset($_GET["name"])?$_GET["name"]:"world";

imagestring($im, 10, 5, 5,  "HELLO ".$name, $text_color);

// Output the image
imagepng($im);

// Free up memory
imagedestroy($im);
?>