Skip Navigation Links
EZWEB
PHPExpand PHP

PHP Basics

Server / Client


Three types of errors can occur:

  • Parse
    • php engine checks for correct grammar and spelling;  eg, leaving off a  ;   is a parse error
  • Execution
    • an error that occurs while a script is executing;  eg, using a variable that holds no value
  • Logic
    • most insidious because the code runs OK, but you don’t get the results you expect;  eg, if subtract the taxes from a subtotal rather than adding it gives you very messed up results
  • All PHP code must be placed within PHP tags. The server will treat anything within these tags as PHP which must be processed before being sent to the browser.


Basic Syntax

  • 4 different styles of PHP tags:
    • XML style
      <?php            ?>
    • Short style
      <?          ?>
    • Script style
      <script language=“php”>                   </script>
    • ASP style
      <%         %>

Example:

1

<?php echo “Hello, $name.”;  ?>

  • Files end with the extension  .php
  • All statements end with a semicolon
  • White space is ignored

Comments in PHP

  • A very important part of web page development involves commenting your code. Comments are blocks of text you add for explanation or clarification that are ignored by the PHP interpreter. You add comments to a script for a couple of important reasons.
    • So other developers who look at your code know what you have done and why, especially if you are working on a project as a team
    • So that you know what and why you’ve done something when you view your code months after first writing it
  • HTML comments look like this:

   < ! - -                     - - >

  • PHP supports three different types of comments:

3 styles of comments:
   #  comments
   // comments
   /*       comments           */

   #     similar to Unix commands or Perl, to comment an
single line of code – anything after the
comment but before the Return is ignored by the PHP interpreter

       //    from C++, comments a single line of code

       /*                    */
              for comments running over more than one line

  • Comments do not have to be placed at the beginning of a line. You can put them after a function call, eg.
  • Comments can be an effective way to debug a script – comment a block of code to make it inactive without deleting the code, then uncommenting the block later to reactivate it.

Example:

1

<html> 

2

<body> 

3

<?php 

4

//This is a comment 

5

/*

6

This is

7

a comment

8

block

9

*/

10

?>

11

</body>

12

</html>
  • Any scripts, such as labs, homework assignments, etc, must contain an introductory block of comments indicating:
    • your name
    • date
    • name of assignment
    • purpose of assignment
  • All class assignments must contain, in comments:
       Name
       Date
       Name of Assignment
       Purpose of Assignment

Example:

1

<?/* Steve Morosko

2

    3 September 2005

3

    Lab #3

4

    Use loops and conditional to create and format a table

5

*/?>


php manual

  • If you have any questions about how anything in php works, one of the best sources you can go to is the online manual, at php.net.
  • Click on Documentation, then the language and format you want to use ( English, View Online ). The manual is the official documentation for php.
  • The largest section of information is the Function Reference, where each of php’s built-in functions has its own page of documentation.
  • The description of each function includes a C-like header definition of the function. EG, if you look up echo( ) you will see:
    • echo  ( string arg1 [ , string argn . . . ] )
  • meaning that echo takes at least one argument that is a string, as well as any number of additional arguments, also strings.  Anything inside  [   ]  is optional.
  • Then you will get some examples of how the function is used, followed by comments from various users clarifying certain points or questions, or explaining examples.


Variables in PHP

  • Variables, as in any other language, are places in memory that temporarily hold values.
  • All variables in PHP start with a $ sign symbol. Variables may contain strings, numbers, or arrays.
  • Naming Rules:
    • prefixed with a $
    • begin with letter or underscore
    • may contain only letters, number, underscores
    • case sensitive

Example:

$distance        valid
$a                 valid but not desciptive
a                   not valid, must start with $
$123abc         not valid, $ must be followed by letter or underscore
$x+y             not valid

  • Assign a value with the assignment operator ( = )
  • Variables do not have to be declared before you use them, although you may want to in order to reduce confusion

Example:

1

<$  $first_name  =  “Steve”;  ?>

  • PHP works with 8 different data types strings:
    • integers
    • floating-point
    • Boolean
    • array
    • object
    • resources – special variable, holding a reference to an external resource such as an open file, database connection, or image canvas
    • NULL – a variable that has no value
  • PHP is a very weakly typed language. You do not have to declare a variable to be a certain type before using it – PHP does that automatically. The type is determined by the value assigned to it.

Sending data to browser

  • PHP has a number of built-in functions to send data to the browser. The most common are echo( ) and print( ). Both do the same thing with a couple of exceptions:
    • with echo( ), you can send multiple chunks of data to the browser,  separated by commas
    • print( ) returns a value of True or False, depending upon whether or not the function was called successfully
    • Technically, echo( ) and print( ) are not true functions, but language constructs, but it is normal to refer to both as functions
  • echo( )
    allows you to send one or multiple pieces of code, separated by commas

Example:

1

<?  $txt  =  “Hello World”;

2

    echo $txt;  ?>

  • print( )
    returns a value of TRUE or FALSE, if the function was called successfully

Example:

1

<?  $txt  =  “Hello World”;

2

    Print $txt;  ?>


Strings

  • Strings hold textual information – blocks of letters, numbers, spaces, characters, etc
  • To assign a string to a variable, simply use the assignment operator, although the assigned values must be inside quotes

 

  • The difference between using double quotes and single quotes is very similar to perl. Any variables placed inside double quotes are interpolated. Variables inside single quotes are treated as string literals.

Example:

1

<?

2

$name = “Steve”;

3

echo “My name is $name”;//prints“My name is Steve”

5

echo ‘My name is $name’;//prints“My name is $name”

5

?>

  • When you want to print a quote, you  can use a single inside doubles, or vice-versa

Example:

1

<?  echo “Where’s my dog?”;  ?>

  • Or escape the quote (which works with some other characters like a $)

Example:

1

<?  echo ‘Where\’s my dog?’;  ?>


Escape Character

Use \ to escape quotes, $, \, etc


\n

Linefeed

\r

Carriage return

\t

Horizontal tab

\\

Backslash

\s

Dollar sign

\”

Double quote

 

Example:

1

<?

2

$name = “Steve”;

3

echo “$name said, \”Bob owes me \$20.\” ”; 

4

//  prints   Steve said, “Bob owes me $20.”

5

?>

Example:

1

<?

2

$name = “Steve”;

3

echo ‘$name\’s reply was “What, me worry?” ’;

4

//prints  Steve’s reply was “What, me worry?”

5

?>


Concatenate Strings

  • There are times when you  will have to connect strings together, or concatenate them. The concatenation operator for strings in php is a dot or period

Example:

1

<?

2

$fname=”Steve”;

3

$lname=”Morosko”;

4

$fullname=$fname . $lname;

5

$fullname2=$fname . “ “ . $lname;

6

echo $fullname;

7

echo $fullname2;

8

?>

  • newlines and tabs       \n   \t
    • adds returns or tabs to the way code prints, not the way a document renders in the browser

Example:

1

<?

2

echo “<html><head><title>My Title</title></head>”;

3

//prints <html><head><title>My Title</title></head>

4

?>

Example:

1

<?

2

echo “<html>\n<head>\n\t<title>My Title</title>\n</head>”;

3

/* prints

4

<html>

5

<head>

6

     <title>My Title</title>

7

</head>

8

*/

9

?>


Printing HTML tags

  • We use the same functions, echo( ) or print( ), to send html code to the browser. Since the html is to be printed as text, we heed to include it within quotes:

Example:

1

<?  echo( “<p>Hello</p>” );   ?>

  • It may get confusing when you first start doing this: You are writing PHP code, which prints HTML code, which eventually renders in a browser as text. When you print out the HTML code, you’ll want it to be structured in such a way that it is easy to read.
  • PHP ignores white space. What you’ll want to do is use the newline character ( \n ) to add a return to the HTML code, use a tab character ( \t )to add tabs, or use separate echo( ) or print( ) statements.
  • Using the newline will not alter the spacing within the rendered HTML page – you will still have to use <p> or <br /> tags.


Numbers

  • PHP has two numeric types of variables
    • integers
    • doubles
  • Numbers are never quoted – if you do, you will turn them into strings with numeric values. Also, you never use commas in numbers.
  • You can use the standard arithmetic operators with PHP numbers

 

+

addition

subtraction

*

multiplication

/

division

%

modulus

+ +

increment

– –

decrement

 

Example:

 

$x = 7;

 

$y = 3;

 

$z = $x * $y ;   //  21

  • % modulus
    • remainder, after division has occurred

Example:

 

$x = 7;

 

$y = 3;

 

$z = $x  %  $y ;   //  1

  • + +     increment

Example:

 

$x = 7;

 

echo   $x++ ;   //  prints 7

 

echo   ++$x ;   //  prints 8

  • – –      decrement

Example:

 

$x = 7;

 

echo  $x- - ;    //  prints 7

 

echo  - - $x ;   //  prints  6


Number Functions

PHP has dozens of functions you can use with numbers. For now, two of them are:

  • round( )
    • rounds a decimal to the nearest integer
      takes one or two arguments
      • number to be rounded
      • number of decimal places

Example:

 

$x = 313.137687;

 

$x = round( $x );   //  313

 

$x = round( $x, 3 );   //  313.138

 

$x = round( $x, - 2 );  //  300

 

Example:

 

$n = 3.13;

 

$n = round ( $n );    //  3

 

echo $n;

 

         or to a specified number of decimal places:

Example:

 

$n = 313.554899;

 

$n = round( $n, 3 );       //  313.555

 

echo $n;

Example:

 

$n=round($n,-2);      //300

 

echo $x;

  • number_format( )

       turns a number into the more common written     
       version, grouped into thousands by commas:  

Example:

 

$n = 43905;

 

$n = number_format( $n );

 

echo $n;              //  43,905

                     
       can also set a specified number of decimal points:

Example:

 

$n = 43905;

 

$n = number_format( $n, 2 );     

 

echo $n;        //  43,905.00


Default values

If a variable has not yet been assigned a value, PHP will give them default values. In a situation where a number is expected, the default is a zero. A sting, on the other hand, be an empty string.

Constants

  • A constant is a specific data type in PHP. Unlike variables, they retain their initial value throughout the script. To create a constant, use the define( ) function instead of the assignment operator.
  • As a programming practice, constants are named using all CAPS. More importantly, they are not prefixed with a $.

Example:

 

define( ‘NAME’, ‘Bubba’ );

     

  • To print constants, you cannot use the echo( ) statement as you would with variables. You must use one of two methods:

  echo ‘Hello ‘ . NAME;     //concatenated
  echo ‘Hello ‘ , NAME;     //with comma

  • Besides the constants you define, PHP has a large number of its own, such as PHP_VERSION and PHP_OS. Notice they do not have a prefix of $. Check phpinfo( ) to get an overview.
  • PHP also has a large number of predefined variables. Again, use phpinfo( ) to get a look at them.
  • Of particular importance will be the superglobals  variables:

 

$GLOBALS

an array of all global variables

$_SERVER

an array of server environment variables

$_GET

an array of variables passed to script using GET method

$_POST

an array of variables passed to script using POST methos

$_COOKIE

an array of cookie variables

$_FILES

an array of variables related to file uploads

$_ENV

an array of environment variables

$_REQUEST

an array of all user input variables

$_SESSION

an array of session variables

  • We’ll look at these closer throughout the course

Variable Scope

Scope refers to the place within a script where a particular variable is visible. Four types of scope in PHP are:

  • Superglobal variables are visible everywhere
  • Global variables within a script are visible throughout the script, but not inside functions
  • Variable used inside functions are local to the function
  • Variables used inside a function that are declared as global, refer to the global variables of the same name

End of PHP Training and tutorials





Free Tutorials and Training