INFO-1208 PHP Fundamentals PHP Basic Syntax and Variables INFO-1208 1 Week 2 – Basic Syntax and Variables • How it all works • PHP tags and statements • Calling functions • Concatenation • Uniform Resource Locator - URL and the query string • Form variables • Variables and Literals • Data types and Constants • Variable scope • All PHP language references can be found at www.php.net INFO-1208 2 How PHP Works INFO-1208 3 PHP Interpreter PHP preprocessing • PHP used to stand for “Pre-HyperText Processor” or Personal Home Pages • A request is made to the web server • The web server locates the resource in this case a .php document • The PHP interpreter is invoked, it reads the contents of the document, executes all the code and returns the output • The web server then returns the output back to the client ( browser ) • This can be text, html, a binary stream ( image ) • Quickly test online at https://www.w3schools.com/php/phptryit.asp?filename=tryphp_intro Be careful copying code from PowerPoint slides: the quotes could be "smart quotes" instead of "straight quotes" PHP Tags and Statements PHP tags • PHP code can be placed in a file with the extension .php • PHP code is defined between an opening and closing tag. <?php ?> INFO-1208 7 PHP statement • PHP statements are placed between an opening and closing PHP tag and ALWAYS end with the semi-colon ; . • All whitespace is ignored <?php echo '<h1>Hello world !</h1>'; ?> Placement of PHP •PHP tags and their statements can be placed repeatedly in a page, described as a “block of PHP or PHP block” <?php echo '<title>Welcome to My Website</title>'; ?> <h1>Welcome to my page</h1> <?php //echo a list of products from our catalog echo 'Here is the list'; ?> Basic PHP Example INFO-1208 10 Common beginner's mistake: Opening PHP page on local machine ▪This PHP script is not processed by the server ▪Chrome Browser automatically ignores the PHP script in the output INFO-1208 11 Running PHP ▪PHP scripts need to be processed by a webserver that has a PHP engine installed ▪The output of that script is then sent to the client’s browser ▪The PHP file will need to placed in the correct directory on the web server and then accessed by the client’s browser by using the correct server URL e.g. http://localhost/mypage.php INFO-1208 12 Accessing the PHP page ▪Viewing the source code from the browser ▪Do you see the original PHP script? INFO-1208 13 Comments INFO-1208 14 HTML Comments ▪HTML comments have the same syntax for both multiline and single line comments ▪These are visible when the user views the page source INFO-1208 15 PHP Comments •Comments in PHP are not interpreted and can be single line or multi-line <?php // First let's do this single line comment echo 'Time to get started !'; /* * Then lets try this multi-line comment */ echo 'looks like we are doing this!'; ?> PHP Comments ▪Single line comments can also start with a hash # INFO-1208 17 Calling PHP Functions Built-in PHP Functions •So far all we have done is output static text, we want to output dynamic content, for example every time the page loads, display the current day and time. <?php //output something like //Hello, you loaded this page at 11 jan 2021 09:22 PM echo 'Hello, you loaded this page at:' . date('d j Y ?> h:i A'); PHP String Concatenation • To join 2 strings of text or statement outputs together, join them using a period <? //output Hello World as 2 strings, concatenated by a period echo 'Hello' . ' World, today is ' . date('d'); ?> Looking up Built-in Functions in the PHP Manual INFO-1208 21 PHP Manual ▪You can access the PHP manual online at php.net ▪If you are looking for a specific function, you can see the details by going to: php.net/function ▪PHP date() function example: php.net/date INFO-1208 22 Uniform Resource Locator (URL) URL • A Uniform Resource Locator, also termed a web address, is a reference to a web resource (i.e: an html page or image file) that specifies its location on a computer network and a mechanism for retrieving it. http:// www.google.ca http:// www.google.ca /index.html /index.html - is the protocol - is the hostname - is the resource or file URL Query String • A URL can also transfer information through the web server. http://www.yoursite.com/data.php?name=ryan • The query string is defined after the special character ? • ?name=ryan • In the form of variable=value • We divide each value pair by the special character & name=ryan&course=php Form Variables • A URL can also transfer information through to the web server. • PHP can access this data through a special superglobal variable called the $_REQUEST array http://www.gofree.com/index.php?type=birds <?php //print the value of the variable "type" to the screen, //it will print "birds" echo $_REQUEST['type']; ?> PHP Variables and Literals INFO-1208 27 Literals • A literal in PHP is the data itself. In this example it is a string. When this code is run through the interpreter it will output the exact string as it appears between the quotes <?php //the text below will output unchanged, it is literally a string echo 'PHP is my favorite programming language, yay'; ?> PHP Variables • While strings are the data, variables are symbols for the data. Variables have a $ in front and can be assigned using the = • A variable is created the first time you use it, you don’t have to declare it. Must start with a letter or underscore. List of words NOT to use • <?php //Assign my string to my variable $my_statement = 'PHP is my favorite programming language, yay'; //output the data stored in my variable echo $my_statement; ?> No Substitution in Literals ▪ For string literals, we use single quotes ' ' ▪ If you want to substitute, or print, the data stored in the variable, ensure that you use double quotes on a string ▪ Example: $last_name = "Bedford"; //this will display correctly print "My last name is $last_name"; //this will simply print $last_name, exactly as written print 'My last name is $last_name'; INFO-1208 30 Data Types Data Types PHP supports the following basic data types: • Integer - Used for whole numbers • Float - Used for real numbers ( decimals ) • String - Used for string of characters • Boolean - Used for true or false values • Array - Used to store multiple data items • Object - Used for storing instances of classes INFO-1208 32 Data is Dynamically Typed PHP will automagically change data types for the same variable • <?php //Assign my string to my variable $my_statement = 'PHP is my favorite programming language, yay'; //change my variable to an integer $my_statement = 12567; //this will output the integer 12567 with no data type error echo $my_statement; ?> Printing Complex Data Types ▪Instead of print or echo, you can print out the value of complex variables, such as arrays, using the print_r() function ▪This is great for troubleshooting a script INFO-1208 34 PHP Variable Names ▪PHP variables start with a dollar sign $ ▪The variable MUST start with a letter or an underscore ▪ Example: $variable or $_variable ▪Afterwards, the variable name can contain letters, numbers, or underscores ▪ Example: $_variable_name2 ▪PHP variables are CaSe SenSitiVe ▪$_variableName is different than $_VariableName ▪PHP scripts will produce errors if the wrong variable name is used when the script is executed INFO-1208 35 Naming PHP Variables ▪PHP variables are recommended to use camel-hump or camel-case naming conventions ▪Camel-hump example: $EmailAddress ▪Camel-case example: $email_address ▪Variable names should be named according to the type of data they are storing ▪Good example: $phone_number ▪Bad example: $ph INFO-1208 36 PHP Variables ▪You've seen that PHP variables do not to be declared or initialized before they can be used ▪It is considered good practice to initialize variables prior to using them. Do not risk printing a variable without a value. ▪When declaring variables, comments should also be used to describe the purpose of the variable’s use in the script INFO-1208 37 Working with Strings ▪PHP string variables can be problematic when it comes to the use of quotation marks ▪Here are some examples of valid uses: ▪ "My name is $name" ▪ 'This course is awesome' ▪If you want to use quotation marks within the string, you will need to escape the quotation mark ▪ "My name is \"Darryl\"" ▪If you leave off a closing quote, the PHP interpreter gets confused and may report the syntax error on a line below where the actual error is INFO-1208 38 PHP Array Variables ▪We will discuss Arrays in more detail later on in this course ▪Arrays can contain more than one value ▪PHP uses two types of arrays: ▪Indexed array ▪Associative array INFO-1208 39 Types of Arrays Indexed Array Key Value 0 1 2 Ontario British Columbia Alberta Associative Array Key Value ON BC AB Ontario British Columbia Alberta INFO-1208 40 Constants A constant is a name or an identifier for a fixed value. Constant are like variables, except that once they are defined, they cannot be undefined or changed. Must start with a letter or underscore • <?php //Define a constant define('MY_STATEMENT', 'PHP is my favorite programming language, yay'); //use the constant echo 'What is my fav language? ' . MY_STATEMENT; ?> Variable Scope Variable Scope • The scope is the context in which a variable is defined. PHP only has local or global. <?php //Define variable in global scope $my_global_var = 'something I may need everywhere'; //define a function that is local in scope function myLocal() { //will output blank or be undefined because scope is local to this function echo 'My variable contains: ' . $my_global_var; } myLocal(); //Calling the function ?> PHP Variable Scope ▪And, PHP variables only exist on the PHP page that is being executed. Once output is sent back to the browser, the variable contents are gone ▪The exception are built-in superglobal variables that begin with $_ and are all uppercase characters Example: $_SERVER ▪More on those later INFO-1208 44 Lab 02 Details INFO-1208 45 Wrapping Up •Any questions for me? INFO-1208 46