Tag Archives: php basics

PHP Basic Series – POST, GET & REQUEST

One of the major goals of PHP is to allow a common website to be fully dynamic. For that can be used database requests, form posting, changing information when parameters change, etc.

No matter when working with AJAX/PHP/MYSQL or PHP/MYSQL or simply PHP/MAIL you will probably be using the pre-defined variable arrays of $_POST, $_GET, $_FILES or $_REQUEST. Among these there is one more variable that you should have knowledge about, the $_SERVER variable that holds all the server environment information and is also an array.

[Note]: All these arrays are associative

$_POST

The $_POST array will hold all information that have been passed by a HTTP POST method, or in a simple way, all information that have been passed by a post form and all this information will become a associative index on the array. Per example, if you have a input text box that is named “name” to access it via post you would use $_POST['name'];

It’s always easier to understand the flow of information when you have more than one page, so let’s consider a 3 page application in wich:

  1. Page 1 will hold the post form
  2. Page 2 will process the post
  3. Page 3 will show a thank you message

Page 1: form.html (note that since we are gonna be using php script on the page, there is no need for the php extension even knowing that you can use it).

<html>
<body>
<form method=”post” action=”processForm.php”>
<input type=”text” name=”username” value=”” /><br />
<input type=”submit” value=”submit form” />
</form>
</body>
</html>

It’s a very simple page with a form and a textbox that will submit the information, once posted, to the processForm.php file, that, will process the post request. Note that on the form method the post is defined, but you could use as well the get method. The only thing about using the get method is that it will submit all the values on the browser url as part of a querystring and it would be necessary to use the $_GET variable to request the values.

Page 2: processForm.php - The process posted form page

<?php
if (!empty($_POST)) // checking if a post has been completed
{

if (strlen($_POST['username']) > 0)
{
// has something, let’s force to go to the thanks page
header(‘location: thanksPage.php‘);
}

}
?>

[Note]: Since is a full PHP page you don’t need the closing tag (in red).

Page 3: thanksPage.php – The thank you for posting page

At the last page of the example we will show a thank you page to the user for posting he’s username information.

<html>
<body>
<p> Thanks for posting the form </p>
</body>
</html>

The last page is quite simple and it’s a simple thanks message as part of the last process to be done to complete the post method.

Looking into a simple work flow we would have:

[page 1: form] [enter information] [submit]
{ form is posted to the processPost.php page } :: [page 2: processing] [check if the form has been submited] [check if the username was given]
{ page is redirected to the thanksPage.php } :: [page 3: user message] [show message] [end]

As you have probably noticed by now if the username is not given it will only show a blank page, we would not have a error message being show or even a return to the previous page. Another thing is that even that the username is given, there is no validation what so ever over the submited post.

This is where the $_GET comes to be extremely useful. Get should be used to communicate parameters between pages, but only communicating those parameters that does not contain sensitive information such as passwords or credit card numbers. As example, think in a AJAX call to a php script where the goal is to filter the search based on a given parameter. This is actually done by using $_GET on the php side and passing the filters by a querystring.

Since we don’t really need a form posting to use the get, let’s first demonstrate how to send parameters between pages using the $_GET array. To better understand the process let’s create a 2 page set where the first a user will click a link that will set a parameter on the second page.

Page 1: Links with parameters

<html>
<body>
<a href=”processGet.php?showmsg=1&msg=it%20worked “>click me to set parameters</a>
</body>
</html>

Note 3 elements on that link:

  1. The elements in bold: The ? starts the querystring and whatever comes after it is a parameter that will be passed to the $_GET array. The second element in bold, &, is used to identify any other parameter that will be used on the querystring. After the question mark, all other parameters must use the & to be identified.
  2. The elements in green are the parameters name. The same name that will be used as index on the $_GET array.
  3. The elemenst in blue are the parameters value.

To get those parameters and it’s values, you need a PHP page to parse the $_GET array, so let’s check the page 2.

Page 2: processGet.php – parsing the $_GET array to retrieve the querystring parameters.

<?php
$showMsg = $_GET['showmsg'];
$msg        = $_GET['msg'];
?>
<html>
<body>
<p>
<?php
if ($showMsg) { echo $msg; }
// the equivalent to this is echo ($showMsg) ? $msg : ”;
?>
</p>
</body>
</html>

The second page will check if the first parameter, showmsg, is set to 1 (or true) and if so it will display the msg “it works” on the page for the user.

[Note]: Since this is a php page with html tags in it, you need to close all open php tags (in red).

$_POST and $_GET become really helpful when working together. You would use the post to safely communicate data and the get to inform when something went wrong or simply to exchange information between pages.

Let’s get the example given to $_POST and add some $_GET parameters to communicate the information between page 1 and 2.

Page 1: form.php (note that the extension has changed)

<?php
$hasError = $_GET['error'];
$errorType = $_GET['type'];
?>
<html>
<body>
<?php if (!empty($hasError)) { ?>
<p><? if (!empty($errorType) && $errorType == 1) { echo ‘Please enter your username.'; } ?><br /></p>
// if you had more than one type you could parse all errors here
<?php } ?>
<form method=”post” action=”processForm.php”>
<input type=”text” name=”username” value=”” /><br />
<input type=”submit” name=”submit” value=”submit” />
</form>
</body>
</html>

Page 1 (form.php) contains the form that will submit the username information to the processing php page (processForm.php) and also contains a validation using parameters got from the $_GET array. These parameters will be sent by the second page, proccessForm.php, when an error on the submission is detected.

Page 2: processForm.php

<?php
if ($_POST) {
$username = $_POST['username'];
if (empty($username)) {
header (‘location: form.php?error=1&errortype=1′); // this will display an error message asking the user to enter his username information on the 1st page.
}
else {
header (‘location: thanksPage.php’); // the information was correctly given, so redirect to the thanks page.
}
}
else {
header(‘location: form.php?error=1&errortype=2′); // this could show a message warning the user that a post submission is needed to process
}
?>

With the help of the $_GET array and querystring now we have much more control over the form submission with a very basic validation and at the same time making the form much more dynamic.

I have mentioned above about the $_SERVER, $_REQUEST and $_FILES and where does they come in all of this? Well the $_REQUEST is the same as the $_POST, $_GET and $_COOKIES altogether in one array. In a coding point of view is good to be using all separate since you know what is being sent and where it came from, but using the $_REQUEST is up to each developer.

The $_FILES array is used when you are posting a file through a form (file upload – remember to set the correct enctype on the form). The file will not be available on the $_POST array making the only way to access it through the $_FILES array. Within this array you can find information where it’s currently stored (the tmp file on the server), it’s real name, type, etc.

To wrap up let’s take a look on the $_SERVER array. The server array contains all the information related to the server environment, from the PHP_SELF – the script executing the php coding, to the SERVER_NAME. Check it out on the php manual page for more info or simply do a var_dump($_SERVER) to learn everything about your development server.

On the next post we will gather everything that we have learned here and place it in a small one page application (yeah multi-page is not really necessary, but make it simpler to explain) where we are going to request a username / password from a user to login.

Have fun.


PHP Basics Series – File Manipulation

PHP file manipulation functions are one of the most raw functions that we have. The functions use the same names (and formating) as the C++ functions.

There a great amount of Filesystem Functions that can be used to manipulate a file, but, in order to direct to daily uses, the focus will be set over:

  • Manipulating a common text file.
  • Manipulating a csv file.
  • Deleting a file.

Manipulating a common text file

Consider the scenario: Create a text file with the Loren Ipsum passage as content.

It’s not a hard task, but some steps are needed to do that.

  1. Create the file
  2. Open the file for writing
  3. Place contents on file
  4. Close file

Good thing is that steps 1 and 2 are set in one action (even knowing that is possible to create the file outside of the script and then open it to write) making the course of action a bit smaller.

[Note]: If you open a file, you are required to close it.

Writing

<?php

$pathToFile = ‘/tmp/newTextFile.txt';
// if on windows adapt to c:\\tmp\\newTextFile.txt – Remember to always escape the backslash otherwise the path will be wrong.

$handler = fopen($pathToFile, ‘w+’); // check the lists of available flags on the fopen function. the w+ will create and open a file to write

$contents = ‘Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';

fwrite($handler, $contents); // putting the contents on the file

fclose($handler);
?>

With this small script the application will easily create a file (or clean the file and start over with this flag) and write the contents on it. There is another way to the same with one single line:

<?php
file_put_contents($pathToFile, $contents);
?>

This function works just like the fopen, fwrite and fclose all together, but it will create and override new contents over the existing ones (if file exists) unless a flag to append is specified.

Is a great function to place all lines at once, but is memory expensive if you are placing line by line (since it will opening, writing and closing for each line, instead of open, write each line and then close).

Consider now that is necessary to append another text into that file that have just been created. To do that is necessary to append new content, so the flag on the fopen will change.

Updating

<?php
$handler = fopen($pathToFile, ‘a+’); // this will open the file to write and place the pointer at the end of the file

// just a twist to place line by line
$lines = array(‘line 1′, ‘line 2′, ‘line 3′, ‘line 4′, ‘line 5′, ‘line 6′, ‘line 7′);

foreach ($lines as $index => $content)
{
fwrite($handler, $content);
}

fclose($handler);
?>

The same can be done by placing the file_put_contents inside the foreach and removing the fopen and fclose, but instead of having 1 fopen and 1 fclose you would have 7 of them altogether with the fwrite.

With both scripts above we have covered the writing and updating the file, now all is left is to read the file.

Reading

Reading the file is simple and it’s almost the same concept as the writing a file, but instead of using fwrite it will be using fread.

<?php
$handler = fopen($pathToFile, ‘r+’); // open the file and place the pointer at the beginning of the file.

$lines = array();
while (!feof($handle)) // while the file ain’t over
{
$lines[]= fread($handle, 8192); // trying to read 8192 chars until next – used to create lines, but also can be used filesize($handle) that will read all – with no need of while loop
}
fclose($handler);

// or reading all at once

$handler = fopen($pathToFile, ‘r+’);
$contents = fread($handler, filesize($pathToFile));
fclose($handler);
?>

As we have a sister function for writing all content at once, we also have a function to read all content at once with one single line.

<?php
$contents = file_get_contents($handler);
?>

The file_get_contents works fine, but will return all content into a string which can make the work very hard if the file is too big.

Manipulating CSV files

We have gone through the whole process of writing, reading and updating a file, but why should we take a look on CSV files directly? The answer is simple: Nowadays CSV files are one of the easier way to communicate data between systems and to safely transport data to the user that need it exported.

PHP carries a series of functions that easily handle CSV files making the scripting and processing of files simpler and faster.

Writing and Updating

Using the same concept as the file_put_contents above the fputcsv works in a similar way, but you can easily place all columns values using an array, which makes the design process a bit easier when retrieving data from a database.

<?php
$handle = fopen($pathToFile, ‘w+’);

$line1 = array(‘column1′,’column2′);
$line2 = array(‘column1′,’column2′);
$lines = array($line1,$line2);

foreach ($lines as $index => $line)
{
fputcsv($handle, $line);

// formats a line (passed as a fields array) as CSV and write it (terminated by
// a newline) to the specified file handle . By default all columns are separated
// by a comma ‘,’
}

flcose($handle);
?>

Since fputcsv uses the fopen to handle the file, to update a file would be similar as above, just the write function that would stay as the fputcsv.

Reading

Reading contents from a CSV file is a simple as writing and appending and it will return line by line of the file into an array where each delimiter will be split into a entry on the array.

<?php
$handler = fopen($pathToFile, ‘r+’);

$lines = array();
while(($data = fgetcsv($handle)) !== false)
{
$lines[] = $data;
}

fclose($handler);
?>

Delete files

To end it up let’s learn how to delete files, but as a huge note, I must say, once is deleted, is truly gone, there is no way to recover it.

To delete a file with PHP all you need is a path, correct permissions and a single line of script.

<?php unlink($pathToFile); ?>

PHP unlink works similar to Unix C unlink() function and it will look for the file (or folder) in the specified path and completely remove it from there.

Play a bit with the file manipulation and learn fully how it works. Most likely you will be using it to gather db info into a report, creating new stream files (videos, music), etc.

Have fun.


PHP Basics Series – Functions

Enigma Machine - Encryption - Wikipedia

Enigma Machine - Encryption - Wikipedia

Defining functions on PHP is one of the simplest things that can be done. Functions are a great way to control your code and, when used correctly, can provide some great power to it as well.

Not likely C++ (and some other languages) that you defined the function output just before the function name, PHP works with a simple definition where you define the name and arguments that will be used to define the function and it’s scope.

As mentioned before defining a function with PHP is simple:

<?php
function userDefinedPrint ()
{
echo ‘My first function … sweeeetttt … ‘;
return true;
}
?>

PHP functions does not carry a need for a argument, return or even needs to be declared on the top of the code (safe a exception – check example 2) to be called, which make them pretty flexible to work with.

The real major restrictions of defining a user-defined function in PHP is the same for any variable declaration or any label in PHP, function names must start with an underscore or a letter, never a number, the functions cannot, at any instance have the same name as a PHP function or structure and the names are case sensitive. Defining a function called print, would cause an error on PHP that’s because PHP does not support function overloading.

There is three basic ways that you can pass an argument to a user-defined function:

  • By value and this one being required or optional
  • By reference
  • By argument array

When defining a function that needs to pass arguments by value or, better explaining, using a variable that will be used inside the function scope to receive a value, it’s the most common form to do it where the only thing that needs to be observed is if the value is required or optional.

<?php
function userDefinedPrint($whatINeedToPrint, $maybeThisToo = ”)
{
echo $whatINeedToPrint;
if (strlen($maybeThisToo) > 0)
{
echo $maybeThisToo;
}
return true;
}

userDefinedPrint(‘my first function… ‘);

/** this will output: my first function… */

userDefinedPrint(‘my first function… ‘ , ‘yeayyyyy’);

/** this will output: my first function… yeayyyyy */
?>

The function above have 2 arguments, one required and another one optional. Whenever the function is called it requires to give at least one argument, and, by function scope, if the second argument is given (a condition that it’s size is bigger than 0), then it will also be printed.

The second argument, the optional one, is called optional because it already have it’s default value given, therefore the function will always know that if the second argument is not given, it will use the default value on it’s scope.

The second most used type of function is creating a one which receives the parameter by reference. Passing a parameter by reference is quite tricky thing if the concept is not fully understood.

When creating a function that uses a parameter by reference, automatically PHP knows that the programmer is referencing a variable that is outside the function scope.

A nice way to place this concept is the same as the “pointers” used by C++. In this case the function parameter “points” to the same memory area as the previously defined variable.

In order to define a parameter as a referenced parameter you must use the ampersand (&) before the variable name

$referencedVariable = 0;
function increaseCounter(&$counter)
{
return ++$referecedVariable;
}

echo $referencedVariable; // will display 0
increaseCounter($referencedVariable);
echo $referencedVariable; // will display 1

Is important to notice that it’s necessary the full understanding of the “reference” concept. If wrongly used, it will surely return unexpected results, therefore, when well used, it surely can improve the code programming logic.

The last item is to define a function using an argument array (or a variable length argument list). It isn’t a hard concept to understand, but instead of creating a function that will show that, I will use one, very well know one, that can exemplify this concept in a beautiful way.

The “echo” constructor does not require for you to pass the arguments between parenthesis. While using this constructor it pass one or more arguments to print.

echo ‘this is the string I want printed';
echo ‘this is the’ , ‘ string ‘ , ‘ I want printed’ ;

The result for both calls is the same, what changes is the number of arguments. In the first call “echo” only have one single argument. On the second call “echo” does have 3 arguments (separated by commas).

On the second call the “echo” constructor will first print the first argument, then print the second and third in order. When used some concatenation or any mathematical operation, it will work on those first and then start the output (check the echo reference guide for more information).

To define a function that use a variable length argument list you need to know how many arguments are (func_num_args()) and how to get the argument value (func_get_arg(), and func_get_args()). This surely increases the level of understanding of the function, but, in some cases (let’s say when working for a script that is executed by a cron job), it’s extremely helpful.

Defining a function that uses a variable argument list is simple, just don’t set a number of arguments or parameters on the function scope (leave it blank), but knowing how many arguments and getting the value of each argument can be tricky and that’s why PHP offer the argument function sisters:

Here is a simple example that will help understanding the creation of a function like this:

function emailBlaster()
{
$num_arguments = func_num_args();
$email = func_get_arg(0);
$subject = func_get_arg(1);
$body = func_get_arg(2);

if ($num_arguments > 1)
{
mail($email,$subject,$body);
}
}

// you could use as well the func_get_args array;

emailBlaster(‘noemail@noemail.com’,’testing’,’this is the email body’);

The variable length argument array does not have a defined number of arguments and it should be used only on very specific situations.

About functions pretty much everything is covered and all that needs to be done now is to improve and better understand how each type works and what is the best way to use each type.

Play a bit, check the results, check the PHP manual, have fun.


PHP Basics Series – Conditional Statements

PHP Conditionals Statements are a true variation from C/C++ and they are, in fact, decision making structures. They are part of a set of control structures that is in fact your toolbox of PHP code.

For truly understanding how a conditional statement work, you have to get back to real hardware logical structures. When you study digital designs you learn that every processor, multiplex, works with a bunch of elements that, according is set on the circuit board, decisions will be made getting the correct result for you (click in the image).

When working with PHP conditional statements you will find most of those real elements that you find inside many electric hardware and they are as important as such. Just keep in mind, whenever you need to code a decision, you will need at least 1 conditional statement.

PHP’s conditional statements are:

[Note:] all PHP structures are lower case

Most likely, when working with a if statement, you will be also working with a else statement, but, in some cases, where you have a nested or sequenced structure with many if and else’s, your best choice will be the switch.

The if and else statement are pretty simple:

<?php
if ( expression )
{
// do what needs to be done
}
?>

If you got another situation that you also need to test, but is just one more situation, then you will use the else, following the if.

<?php
if ( expression )
{
// do what you need to do
}
else
{
// was not what you expected before, so do this now
}
?>

To better visualize the code, let’s take a real situation, for instance, parsing the information sent by posting a form.

<?php
$name = ”;
if ($_POST['login'] == ‘John’)
{
$name = $_POST['login'];
}
else
{
echo ‘Error: Unable to log into the system. Wrong username.';
}
?>

Some times will be needed to handle more than one else statement, or more than one condition to test after the first condition (if). There are actually 2 ways to do that, sequence some else followed by a if, or better known as elseif, or use the switch. There is no real rule to when to use what, but here is a tip, if you have more than 1 elseif, then use a switch.

<?php
if (expression)
{
// do what you got do
}
else if (another condition)
{
// do another thing
}
else
{
// last condition
}
?>

The code can be written, also,  using a elseif, instead of a else if. No real difference between the both, so it will be more how the programmer likes to code. Anyway, as mentioned before, when you have a long sequence of elseif’s, in most of the cases, you will be able to replace them for a switch structure.

The switch statement will allow to compare a same variable with a bunch of different values and you can easily math one or more comparisons to the same action.

<?php
switch ($_POST['todaysDuties'])
{
case ‘take garbage out': // consider the case as a if
$need = true;
break; // and always add a break, otherwise it will continue to the next statement

case ‘take dog to the vet':
case ‘give dog a bath': // here we are seeing 2 conditions set to the same action
$need = false;
break;

default: // this is the default statement, or better know as else
// do nothing
break;
}
?>

[Note:] If you need to do a comparison that have more than one condition such as if equals something, or bigger than something else, place the condition inside parenthesis. Just like a if statement, it will look if the condition is true or false, so the conditions need to be worked as math expressions so the result is always correct, or the expected result.

Looking at the figure (top of the article), it shows a logical diagram for a circuit in which will get the signal entries from x1 to xn, invert them (or saying NO to it), pass them into a AND array, going to a OR array and finally going to an XOR array that will result the final output. These elements, that will return some logical choices of true or false when combined, are also used on combined expressions of an conditional statement.

The most common operators that is used inside a conditional statement are:

  • == : double equals : equals to (a single equal is receiving some value)
  • === : triple equals : identical to (in every single way, from type to value)
  • || : double bars : or
  • && : double commercial e’s : and
  • ! : exclamation point : not
  • != : exclamation point followed by a equal : not equal to
  • >, <, >=, <= : numerical operators

For example porpoises only a if statement could be easily represented by:

<?php
if ( ((!expression) && (expression)) || (expression))
{
// do something
}
else
{
// do something else
}
?>

There is another way to declare if / else statements in a single line without using the if or else. This is the short version of the code and, even knowing that it’s easier to use it while declaring variables or echoing, keep in mind that many developers does not know or can easily read them.

A short version of an if / else is declared as:

<?php
$variable = (expression) ? ‘get this value’ : ‘get another value’;
// this can be read as the variable will receive ‘get this value’ if the expression is true, else, it will ‘get another value’
?>

The same can be done to be used while outputting something and it also can support in-line (nested) short statements (not recommended – harder to read).

As many others controllers and structures from PHP, the conditional statements can be nested in many levels and can also be included inside other control structures.

To better practice how the conditional statements work, look for questions that can be programmable and the result of the conditional expression can be set to true,  false or maybe (in this case, an elseif that will return true or false).

Have fun.


PHP Basics series – Variable types and outputting

So far we have discussed a bit about coding and standards, a bit more about starting with PHP and now we will discuss about PHP variable types and outputting (displaying on the screen).

Some developers say that PHP have a “hybrid” variable type or, by what they mean, PHP does not carry a true primitive type since you don’t need to specify it when declaring a variable.

In some ways that’s true, you really don’t need to specify what is the variable type when declaring a variable, but that’s most because PHP engine already detects that for you automatically and it will also make the necessary conversions (cast) when necessary.

PHP has, as primary variable types:

Scalar Types

$stringType = ‘string';
$integerType = -10, 10;
$floatType = -10.9, 10.9;
$booleanType = TRUE, FALSE, 1, 0; // in this case 1 and 0 are also interpreted as boolean

Dynamic Types (compound)

$arrayType = array();
$objectType = new DirectoryReader(‘./’);

Special Types

$resourceType = fopen(‘file.txt’);
$nullType = NULL;

As seen above there is no need to declare the variable type to determine that it is a string, boolean, integer, float, etc. When working with several types at same time, you can cast them to become something else or, depending on the operation, PHP will do that for you.

Here is a nice example of when PHP converts something to get the result.

$result = 9 + ‘9’ – 1;

The result above will be the sum of 9 plus the integer equivalent of 9 less 1. If we were dealing with strings, the same will happen.

$result = ‘The sum of 9 + 9 is ‘ . (9+9) . ‘!';

In this case PHP will first sum and them convert the result to a string so it can be concatenated with the rest of the string.

There is no real mystery in declaring a variable, but there are some small rules:

  1. A variable name will never start with a number, always with a letter or underscore
  2. In order to PHP to know that it’s a variable that is dealing with, the dollar sign ($) must precede all variable names
  3. The declaration of a variable must receive some value even if it’s null. This type can be later changed to the correct one with value.

Considering this all the variable declarations above are correct, but to help to get it right, here are some true examples of incorrect variable declarations.

$1234Variable = ‘1234’;
$variable;
variable = ‘test';

The correct format for those examples above are:

$_1234Variable = ‘1234’;
$variable = null;
$variable = test;

Keep the 3 golden rules of variable declaration in mind and every time it will be right. Whenever in doubt that the variable type is really the one being looked for, just do a cast. Here are some examples;

$variable = ‘1234’;
$integerVariable = (int) $variable;
$floatVariable = (float) $variable;

Besides variable declaration the second thing most done in a PHP script is outputting results on the screen, or printing.

For most cases the printing is done by using one of the following:

  1. echo to print any scalar value on the screen, or how the manual mention it, to echo something on the screen
  2. print to print any scalar value on the screen. It’s pretty much the same as echo, but with the difference of being a function, so you can grab a result from it (that will always be 1).
  3. print_r to print arrays mostly and some objects that support the array iterator

There are more ways to output something on a document, but for now, that’s all is necessary to be known.

To wrap up this article here is a full example with correct variable declarations and the respective output.

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html>
<head>
<title>
Page Title</title>
<!– other head data such as CSS styling and JS scripts –>

</head>
<body>
<p>
<?php
$_string = ‘ This is a string ‘;
$_interger = 7; // for luck
$_boolean = TRUE; // it could also be FALSE, 1 or 0
$_array = array($_string,$_interger,$_boolean);

echo $_string . ‘<br />'; // this can be also done whithout concatenation by closing the PHP tag, placing the br tag on place and opening again if needed to continue with the PHP script – look bellow

print $_interger . ‘<br />';

print ($_boolean . ‘<br />’);
?><pre><?php
print_r($_array);
?></pre>
</p>
</body>
</html>

The document would result:

This is a string
7
1

array(
[0] => ‘This is a string’
[1] => 7
[2] => TRUE
)

Play a bit with it and do some testing, check results. Next article the focus will be on the Array which is maybe the most important type in the whole PHP engine.

Have fun.


PHP Basics Series – Starting with PHP

Hi and welcome to the second article of the PHP Basics Series. The first article – PHP Basics series – coding – was about coding best practices, standards and methods. A small overview on what you need to know to be a good coder.

In this second article we are going to talk about the very beginning of PHP, how it works, how to start coding on it and a bit of history.

PHP stands for Hypertext Preprocessor and it was created based on the C, Java and Perl (used until today on extra modules) languages. With many authors, editors, contributors, etc, is hard to name one as it’s creators, therefore you can point Rasmus Ledorf (who wrote the original gateway binaries) and Andi Gutmans and Zeef Suraski (both responsible for witting the parser that formed PHP3) as the original creators of PHP3.

If we had to create a in-line structure to show how it works, it would be something like this:

The client (your browser) requests a page to the server. The server reads the page and see if there are any PHP script and it will parse that script generating the correct result that can be embed to the HTML / XML / Javascript (JS) / etc.

Off course there is much more when we are talking about the way that PHP works, and it’s history, but I will focus more on the coding techniques.

Before we create our first code and I promise that it will not be “Hello World“, you will need to have PHP installed on your development machine or in a server where you can store your PHP files to be executed.

If you are on a Windows machine you can either install PHP manually adding it to IIS server or you can install a PHP bundle that will install for you the Apache server, PHP engine and MySQL (if you desire to, otherwise you can use PHP native SQLite).

Truly I’m not the best indicated to show how to install PHP on a IIS server, but there is a very good step by step – Vista – on Bills IIS Blog: How to install PHP on IIS.

Installing the bundle, for a development machine, at this point, is the most recommended. There is a great bundle, AppServ, which is pretty easy to install and configure. It will come with all of the most usual libraries that you need and you can also choose to install some extra ones.

In other hand, if you are on a Linux machine (Ubuntu, Xubuntu – love it, Suse, etc) most likely you already have PHP, Apache and MySQL installed. Therefore you can check by using the Synaptic Package Installer, and if is not there, install it. Just make sure that you have root permissions.

Now that you have PHP installed, let’s create our first code.

Note: If you don’t have an development editor, you can use Eclipse PDT. It’s a great editor and it’s free. Very similar to the Zend Studio. If you have any other editor that you like, such as Dreamweaver, Notepad, Edit+, etc, you can use it as well.

The first thing you need to know is how make the server to understand that it will be dealing with a PHP code. For that you will be using the PHP open / close tags. There are a set of 4 open / close tags for PHP, but we will focus on only one.

PHP holds as it’s open / close tags the following:

  1. <?php ?> – Full tag
  2. <? ?> – Short tags. As one of it’s variations you will have <?= that is the same as <? echo
  3. <% - ASP tags. More as a history point, but really, not useful at all.
  4. <script language=”php”></script> – besides the first one, the only one that you can trust to work.

While coding we could be using all of the 4 sets of PHP’s open / close tags, but, for keeping a standard and full compatibility on any PHP installation, we will always use the first set. The second set have some amazing features applied to it, but on the latest versions of PHP you need to enable it on the INI configuration and, if you are dealing with embending your code on a XML file you can have some parsing errors.

As I promised before, we are not going to write a “Hello World” application and we will code 2 types of application today. A standalone and a embed one. There is no real definition as standalone or embed types, but it will be easier, for now, to identify our files as standalone or embed. The standalone is a file that is purely PHP, no other code besides PHP. The embed is a HTML, XML, or any other type of file that have PHP code inside it.

Let’s take a look on a standalone file first: standalone.php (note the .php extension, whithout it, the server can’t recongnize that there is a PHP code inside it and it would only write the code on the screen as text).

standalone.php
<?php
$string    = ‘ This is a string and the number is: ‘;
$number = 7;
echo $string;
echo $number;

If you call the file from your browser (http://localhost/standalone.php) you will see the following result:

This is a string and the number is 7

As you may noticed by now, the close tag, ?>, for the above script was omitted. When you are dealing with only PHP code on a file, you don’t need to include the closing tag, the PHP engine will do that for you and it also is a simple performance and standard recomendation from PHP.

Among other uses from the standalone file, you can call it from the command prompt / command line: php /path/to/file/standalone.php. It’s results will be displayed on the command prompt screen. At first this does not seem too useful, but when getting more advanced, you will see that you can use this with cron jobs to increase your application power.

Let’s take a look now on the embed file, embed.php. Again the extension of the file must be .php otherwise the server will not understand that there is PHP code inside the file and it will not process it.

embed.php

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;
<html>
<head>
<title>
Page Title</title>
<!– other head data such as CSS styling and JS scripts –>

</head>
<body>
<p>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<p>

<?php
$string    = ‘ This is a string and the number is: ‘;
$number = 7;
echo $string;
echo $number;
?>
</p>
</body>
</html>

This is a good example of a PHP script that is embed into a XHTML file. When you call the file on your browser you will have the following result:

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

This is a string and the number is 7

As you have notice, in the embed file the php close tag, ?>, is on place. Without it, the PHP engine would throw an error on the screen not letting the code to be parsed and the page to be displayed.

This is our first PHP application. For now on things will be increasing and we will focus a bit more on structures and tools that you can use while programming PHP.

For now on every time that we work with a PHP file that will be displayed on a browser or used on a cron job or for any other need, we will reference it as a application because that is what truly is.

See you on the next article, have fun.


PHP Basics series – Coding

code-standardThis is the first article that I’m writing about learning PHP.

For a couple of months now, and even more after this article from Marco Tabini, I have noticed the need of  better coding standards and a more directed learning content for “greenhorn” programmers in PHP.

Based on this, I’m starting today with a PHP Basis Series that will try to get around all the basic need that a developer should have to program well in PHP.

This first article will cover everything you need to know about coding and it’s standards.

You can learn PHP, Javascript, Java, C#, ASP.Net, Ruby on Rails, etc, if you don’t have good programming techniques and standards, your code will be messy, unreadable, hard to understand, etc.

It’s important that you have good standards and coding techniques and to emphasize that I quote a professor of mine that once said: ” A good developer learn the best pratices, standards and coding techinques, so he can program in any language.”.

While talking in PHP we have a small list of good coding practices / standars and methods.

When declaring variables and functions, use camelCase.

It’s actually simple. The variable or function will have it’s name started with a lower case and the next word will have the first letter uppercase and this will repeat for every word after.

Constants are always UPPERCASE.

This rule is more to help you out on identifying the constants among the variables.

Variables, functions names and constants must have a meaningful name.

Consider the following function:

function funtion_1($var, $var2)
{
for($i = 0; $i < $var2; $i++)
{
$var = $i + $var2;
}
return $var;
}

Looking it like this, it’s very, very hard to understand what is the use for the function or what each variable means, but re-writing it like this:

function increaseByMany($numberSource, $counter)
{
for($index = 0; $index < $counter; $index++)
{
$numberSource = $index + $counter;
}
return $numberSource;
}

It get’s really easier to understand whtat is doing and what it will return.

Use 4 spaces instead of Tabs.

Consider that you are working remotely with other developers from all over US and the World. Each developer has it’s own preferable editor. The only problem with this is that each editor can be configured to set the number of spaces for the tabs, so a developer can have 8 spaces instead of 4, for each tab. With the objective to have the correct indentation on every editor, instead of using tabs, use 4 spaces. It will be annoying at first, but it does really pay in the long run.

Have the minimal documentation for the system even if it is on the function / class itself.

This example is better visualized on a object class. Consider the creation of a class that handles every single action that a user can do on the system and this class was created more than 6 months ago. If you don’t have any inline documentation, or any documentation at all, understanding the methods inside and some specific methods from the class can be very hard. To avoid that and to allow other developers to understand how the class works, you should at least do inline commeting.

Some systems like PHPDoc, can grab the inline comments that you have written on your class and convert it, automatically, to a very professional system documentation.

Consider working with Object Oriented Programming, scalability and modularity.

Even if you are starting, working with Object Oriented Programming is a need and doing it so in a modular and scalable way is a must. The reason to work with OOP is simple: code re-use and modularity. If is well developed, you can easily allow a developer to work on a part of the system while you work on another, or you can let a developer to use a object that you already have created on his part of the system. The most important thing is that the system get’s easier to read, easier to maintain and you win on development time since you wont need to re-invent the wheel. The scalability is something that every system should consider on it’s beginning. If your system is not scalable enought there is a good chance that at some point, it will fail because it can’t grow.

Do your analysis before witting anything.

In one of my first jobs I have worked as a system architech and it was insane hard to convice the CEO that before acting, we need a plan, or by that I mean, we need to do analysis. Every time that my team tried to create something without discussing it first, things did go wrong, so, from a personal experience, if you are the system architech, do your analysis on the issue first. It will save time and you will be albe to consider how modular and scalable it can be.

Specifically to PHP

1. Never use short tags and it’s variations
2. If the document only contains PHP code, no need to use the PHP close tag ( ?> )

These are the very few basics from coding pratices / standards. Before writting a code always consider that it can become huge, that it can have 10 milhon users at time and, most important, that another developer will be reading it.

This will help you to write better code and as an advise, get the best coding standards that are out there, make a list and set on a document so every system that you work from now on you can use those and, off course, if someone joins the boat, you can send him that document too.

Have fun.


Follow

Get every new post delivered to your Inbox.

Join 293 other followers

%d bloggers like this: