Today we finish the basics and prepare for the real deal:

  • PHP Variable, Array, Functions, Date and Time
  • Form Handling
  • HTML data Handling and Processing

Reference functions

empty – Determine whether a variable is set
Isset  – same as !empty($a)
is_array – Finds whether a variable is an array
is_bool – Finds out whether a variable is a boolean
is_float – Finds whether a variable is a float
is_int – Find whether a variable is an integer
is_null – Finds whether a variable is NULL
is_numeric – is a variable is a number or a numeric string?
is_object – Finds whether a variable is an object
is_string – Finds whether a variable is a string
count – Count elements in a variable
array_search – Searches the array for a given value and returns the corresponding key if successful
sort – Sort an array into numerical/lexicographical order
array_reverse – Return an array with elements in reverse order
array_unique – Removes duplicate values from an array
array_sum – Calculate the sum of values in an array.
array_rand – Pick 1 or more random entries from the array
shuffle – randomly reorders the elements in an array

Time and Date

Time() gives you the current UNIX timestamp. It returns the current time measured in the number of seconds since January 1 1970 00:00:00 GMT. Common examples of using Timestamp:
  • Keeping track of login times
  • Time how long processes are taking
  • Keeping attendance time log

Date() outputs the current date and time into whatever format you specify:
Print date(“j F Y”);  28 June 2009
Print date(“jS F Y”);  28th June 2009
Print date(“F j, Y, g:i a”);   June 28, 2009, 9:46 pm
Print date(“H:i:s”);   09:46:17
Print date(“D M j G:i:s T”) ;  Mon Jun 28 9:46:17 GMT

OK so what is PHP for?

Main purpose of PHP is analysing web data – from whole web pages to individual text fields of a form. So first of all lets have a quick reminder of what that means in terms of HTML. The values of forms can be accessed in PHP using the $_POST, $_GET and $_REQUEST arrays
For Example: $_POST[“input-element-name”]
HTML Form Handling (form.php)

Create a new file and write the following code in it. File extension could either be .php or .html:

<form action="receive.php" method="post">    
Name: <input type="text" name="username" />
<input type="submit" />
</form>

Create another file (for example receive.php). This file will recieve the data submitted by the above form:

<?
 $username = $_POST["username"];
 if($username)
 print "your name is $username";
 else
 {
 <?   <a href="form.php">please fill the form!</a>
 <?
 }
?>

Alternate Way

You can also perform the above task using only a single .php file having form as well as the code for receiving data. Code is given below:

 $username = $_POST["username"];
 if($username)
 {
     echo "your name is $username !!!";
 }
 else
 {
 ?>
 <form action="<?= $PHP_SELF ?>" method="post">
 Name: <input type="text" name="username" />
 <input type="submit" />
</form>

Got that Data… now what

  • As we’ve seen if you create an HTML form and have a php script as a target – the items of that form will magically appear as variables in your script.
  • You must always perform client-side data validation techniques before receiving data on the server-side.
  • But now we’ve got the data we need to process it… this always causes problems.
  • With slashes everywhere, dead whitespace, capitals in the wrong places you always have to tidy it up.
  • This Data processing is a good practice if you want to store it in the database.

Trimming Strings

  • trim() strips whitespace from the start and end of a string and returns the result.
  • It also gets rid of new lines, tabs, carriage returns and the like.
  • ltrim() and chop() do similar things – but only from one end of the string.

Changing Case

  • Most people who use your sites will be Muppets. (although your sites will probably only be viewed by members of staff so draw your own conclusions).
  • Whatever you tell them to do, they won’t enter data in the format you want and this will matter. Login names are classic examples of this.
  • Imagine someone types “dAviD VillA” into a field.

Strtoupper() turns string to uppercase e.g. DAVID VILLA

Strtolower() turns string to lowercase david villa

Ucfirst() capitalizes first character David villa

Ucwords() capitalizes every word David Villa

Adding Slashes
To do this escaping normally you just add a \ (backslash). This can be very painful to do manually. AddSlashes() is a function to do it for you.
  • StripSlashes() reverses the process. So if a user typed in: You said to me that “you don’t give gaurantees”
  • If you use $userInput = AddSlashes($userInput). It will convert to: You said to me that /”you don/’t give gaurantees/”.

Exploding Strings

  • explode() returns an array of strings created by breaking the subject string at each occurrence of the separator string.
  • Syntax: explode(sep, subject);
  • Implode() reverses the process.
 $email = "sourcecodemania@ictinnovations.co.uk";
 $arr = explode("@", $email);
 $domains = explode(".", $arr[1]);

In the code sample above, line 2 will create an array “$arr” with following two elements: $arr[0] = “sourcecodemania” and $arr[1] = “ictinnovations.co.uk”
Where as line 3 will further create another array “$domains” with following three elements: $domain[0] = “ictinnovations”, $domain[1] = “co” and $domain[2] = “uk”

Regular Expressions

PHP supports 2 styles of regulare expresions syntax : POSIX and PCRE (Perl Compatible)

  • Ereg()  POSIX regular expressions search
  • Eregi()  Turns string to lowercase
  • Preg()  Capitalizes first character
  • Pregi()  Capitalizes every word
Characters and Wildcards:
  1. // prints “Found ‘cat'”
  2. if (ereg(“cat”, “raining cats and dogs”))
  3. print “Found ‘cat’ “;
To represent any character in a pattern, a period is used as a wildcard. The pattern c.. matches any three-letter string that begins with a lowercase c. For example, cat, cow, cop, and so on

Character List:
  1. ereg(“p[aeiou]p”, $var)
  2. ereg(“[0-3][0-9]”, “27”);
Anchors:
          $match = ereg(“^[0-9]”, $var); //  returns true if $var = “1234567”
Optional and Repeating Characters
  1. The ? operator allows zero or one occurrence of a character, so the expression: ereg(“pe?p”, $var) matches either “pep” or “pp”, but not the string “peep”.
  2. The * operator allows zero or many occurrences of the “o” in the expression: ereg(“po*p”, $var) matches “pp”, “pop”, “poop”, “pooop”, and so on.
  3. The + operator allows one to many occurrences of “b” in the expression: ereg(“ab+a”, $var) search strings such as “aba”, “abba”, and “abbba” match, “aa” doesn’t.
Email validation Regular Expression:
 $email = "sourcecodemania@ictinnovations.co.uk";
 if(!eregi("^[a-zA-Z0-9._]+@[a-zA-Z0-9-]+.[a-zA-Z0-9.]+$",$email))
 {
 print "that is not a valid email address";
 }
 

In the next topic we’ll cover File handling in PHP. :-)

Next >> Lecture 3. File Handling in PHP

Tagged with: PHP
 

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

 

Looking for something?

Use the form below to search the site:


Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Related News Feeds

Set your Twitter account name in your settings to use the TwitterBar Section.