<<< And this line should be written using PHP (watch it via page source) - but the file must end with .php not .html :-) - Try it now at our new PHP Testing Site and then let's learn it all together with us now :-)
cd ~ (change directory) - user's home folder - write ~ option n
cd / - root directory
pwd (print working directory) - shows path to actual folder
ls (list directory contents) - shows content of folder
clear - makes Terminal show your line as the only one
history - shows mumbered history of all entries
history -c - clears history
SSL - Secure Sockets Layer - Transport Layer Security - Wikipedia Mac OS X SSL Certificate Installation Mavericks Server Part 7: SSL Certificates - YouTube
For SSL change httpd.conf - find file > Finder Window > cmd+shift+G opens Go to the folder: enter /etc/apache2 (this starts with pribate/ - so better /etc/ finds another etc > apache2 - both httpd.conf files are the same files, seems :-) > httpd.conf - open file in editor - go to line ca. 490:
# Include conf/extra/httpd-ssl.conf (# Include /private/etc/apache2/extra/httpd-ssl.conf) change to:
Include conf/extra/httpd-ssl.conf (Include /private/etc/apache2/extra/httpd-ssl.conf) <<< Don't do that - it stops working! Apache etc. will not work anymore!
Line 217 shoud be: Allow Override All - (instead of None - if it is None change it to All)
For more changes go Apache documentation
httpd.apache.org/docs/2.2/mod/mod_ssl.html
Then stop and start the local Apache server (why not restart?):
# /usr/local/apache2/bin/apachectl stop
# /usr/local/apache2/bin/apachectl start
Test if it works:
Connect to the server with a web browser and select the https protocol, like this: https://apache2.games.lovetheuniverse.com ... maybe ... -
(https://yourserver.yourdomain.com)
Try your server’s IP address also, like this:
https://xxx.xxx.xxx.xxx - or
http://xxx.xxx.xxx.xxx:443
If it worked, the server will send the certificate to the browser to establish a secure connection.This makes the browser prompt you to accept the self-signed certificate.
To use PHP modules you installed as shared objects, you need to complete a few more steps.
First, copy the module you have built to the PHP extensions directory, which is probably
/usr/local/lib/php/extensions
Then add the following line to your php.ini file: extension = extension_name.so
You will need to restart Apache after making changes to php.ini.
Install PEAR (PHP Extension and Application Repository) - PECL (PHP Extension Community Library) and other ...
Contents at a Glance
Table of Contents - Index (p911)
Authors - Acknowledgements - Reader Services
Introduction
p1 - Welcome - Introduction themes:
• Why you should read this book
• What you will be able to achieve using this book
• What PHP and MySQL are and why they’re great
• What’s changed in the latest versions of PHP and MySQL
• How this book is organized
How Is This Book Organized?
p9 - V Parts - I - Overview PHP with real-world examples like e-commerce sites etc. - II - Building MySQL database systems and connecting to the world via PHP - security and optimization - III - E-commerce and security - authenticating users - gather, transmit and store data - IV - Advanced PHP techniques - groups of functions useful for building websites - interaction with server and network - image generation - data and time manipulation - session variables - V - Building practical PHP and MySQL projects - real-world issues such as managing large projects and debugging - sample projects demonstrate power and versatility of PHP and MySQL
Finally Soon, you’ll be able to join the many thousands of web developers who use these robust, powerful tools to easily build dynamic, real-time websites.
I - Using PHP
Chapter 1-7
1 - PHP Crash Course
p13 - Chapter overview PHP syntax and language constructs - learn PHP through real-life examples from website building - this should not be another PHP reference like the online manual - practice examples, change, manipulate, break, fix - via our online product example "Bob's Auto Parts" learn using variables, expressions, operators and precedence - boolean values - if else the ? : oprator - the switch statement - loop to generate repetitive HTML tables
Key topics: ...
...
Before You Begin: Accessing PHP
p14 - 1. Need access to web server with PHP installed - 2. Install PHP and MySQL (with Apache and SSL etc.) on computer - see Appendix A and CD-ROM
Creating a Sample Application: Bob’s Auto Parts
Sample examples download here - found at stackoverflow.com
Most common applications for server-side scripting is processing HTML forms - start learning PHP by implementing order form for "Bob's Auto Parts"
Created orderform1.html - processorder1.php will follow (page 25) to work dynamically :-)
Processing the Form
p16 - form action="processorder.php" - we will write the .php soon - URL will be loaded when customer clicks submit - data will be sent to URL via method="post" or "get" - tireqty, oilqty, and sparkqty will be used in .php - give your form fields meaningful names, not field23 etc. - adopt a coding standard for field names -
<?php
echo ‘<p>Order processed.</p>’;
?>
Watching it in the browser - shows no raw PHP - the PHP interpreter only sends the output, HTML - every browser can show it without understanding PHP. Example illustrates concept of server-side scripting in a nutshell - PHP has been interpreted and executed on the web server, as distinct from JavaScript and other client-side technologies interpreted and executed within a web browser on a user’s machine.
Now 4 types of text: HTML, PHP tags, PHP statements, whitespace - can add comments
PHP Tags
<?php and ?> are similar to HTML tags and are called PHP tags - browser recognizes inside PHP, outside HTML - with PHP tags you escape from HTML :-)
4 styles: • XML style: <?php ... ?> will be used in this book, it is the preferred PHP tag style - server administrator cannot turn it off, guarantees it will be available on all servers, important if writing applications that may be used on different installations - used in XML - recommended style
• Short style: <? ... ?> - follows the style of a Standard Generalized Markup Language (SGML) processing instruction - need to enable the short_open_tag setting in your config file or compile PHP with short tags enabled - more info Appendix A - use not recommended - will not work in many environments as it is no longer enabled by default
• Script style: <script language=’php’> echo ‘<p>Order processed.</p>’; </script> - may be used if editor has problems
• ASP style: <% echo ‘<p> ... </p>’; %> - same as used in Active Server Pages (ASP) or ASP.NET - can use it if you have enabled the asp_tags configuration setting - by default, this tag style is disabled.
PHP Statements
between the PHP tags - statement: echo ‘<p>Order processed.</p>’;
prints or echoes the string to the browser window - semicolon at end of statement - PHP separates statements via semicolon like languages separate sentences via periods - similar to C or Java etc. - leaving off semicolon is common syntax error but easy to find and correct.
Whitespace
Same as in HTML - PHP ignores it.
Comments
p20 - PHP supports C, C++, and shell script–style comments. Here C style multiline comment, should start /* and end */:
/* Author: Bob Smith
Last modified: April 10 */
Or single line C++ style starts with //:
echo ‘<p>Order processed./<p>’; // Start printing order
or in the shell script style:
echo ‘<p>Order processed./<p>’; # Start printing order
// here is a comment ?> here is not - after the PHP ending tag the comment does not continue, it ends with the tag, too
Adding Dynamic Content
p21 - Main reason using server-side scripting languages is to be able to provide dynamic content to a site’s users - This is an important application because content that changes according to users’ needs or over time will keep visitors coming back to a site. Example:
<?php
echo "<p>Order processed at ";
echo date('H:i, jS F Y');
echo "</p>";
?>
Can also be written on one line, using the concatenation operator (.), as
<?php
echo "<p>Order processed at ".date('H:i, jS F Y')."</p>"; // add Y to processorder.php example :-)
?>
Calling Functions
p22 - The function date () passes a string - date(‘H:i, jS F Y’) - inside is a pair of parantheses - content is the argument or parameter - it is calles the input of the function - generates the output results - Most of these functions need to have some data passed to them and return some data - PHP has an extensive library of functions
Using the date() Function
The date() function expects the argument you pass it to be a format string, representing the style of output you would like - date(‘H:i, jS F Y’) - H = hour 24 hour format with leading zeros - i = minutes with leading zeros, j = day without leading zeros, s = suffix th - f = full name of month - Y = year - more in chapter 21 -
Accessing Form Variables
p23 - Point of using order form is to collect customers’ orders - exact method depends on version of PHP you are using and setting in php.ini file
Short, Medium, and Long Variables
Access form data via variables in 3 ways - nicknames:
$tireqty // short style - requires the register_globals configuration setting be turned on - off by default - insequre, not recommended, may disappear in PHP6
$_POST[‘tireqty’] // medium style - recommended - used in book
$HTTP_POST_VARS[‘tireqty’] // long style - deprecated, may be removed in future - can now be disabled via the register_long_arrays configuration directive
p24 - We can access each form field as PHP variable - name relates to form field - variable names begin with dollar sign $ - we have created short versions of the variables for ease of use. If short style used no declaration of variable needed in our script - field tireqty in the form creates the variable $tireqty in the processing script - need to turn on register_globals, off by default because of security reasons, no distinction between our created variables and those coming from users, will be mixed with our own variables - have to give them all a starting value Medium style involves retrieving form variables from one of the arrays $_POST, $_GET, or $_REQUEST, holds the details of all the form variables - which array is used decided by used method if POST or GET - combination via REQUEST - data will be stored in chosen array - both data abailable in REQUEST
p25 - To copy the value of one variable into another use assignment operator, in PHP it's an equal sign (=)
$tireqty = $_POST[‘tireqty’]; - to avoid security issues
We place the block above or belowhtml because it doesn't produce any output - generally placed at start of script to make them easy to find
This code creates three new variables—$tireqty, $oilqty, and $sparkqty - sets them to contain the data sent via the POST method from the form
To make script start doing something visible, we add following lines to bottom of our PHP script:
echo '<p>Your order is as follows: </p>';
echo $tireqty.' tires<br />';
echo $oilqty.' bottles of oil<br />';
echo $sparkqty.' spark plugs<br />';
Enter in orderform1.html (created page 15) wrong data and observe what happens - you might want to add some data validation to this script later
Taking data from user and outputting to browser is risky, not secure - should filter input data - more in chapter 4 and 16. Load orderform1.html :-) Works :-) Now we will study the elements of this example:
String Concatenation
p26 - echo $tireqty.' tires<br />'; - period (.) is the string concatenation operator, which adds strings (pieces of text) together - avoids writing multiple echo commands
echo "$tireqty tires<br />"; - equivalent to the first statement - replacing a variable with its contents within a string, is known as interpolation - double-quoted strings only
p27 - echo '$tireqty tires<br />'; simply sends “$tireqty tires<br />
” to the browser - sent unaltered
Variables and Literals
Variables and strings concatenated together are different types of things - variables are symbols for data - strings are data themselves - a piece of raw data is called literal to distinguish it from a variable - PHP replaced the variable name $tireqty in the string with the value stored in the variable
Two kinds of strings mentioned already: with "double quotation marks" and ones with 'single quotation marks' - PHP tries to evaluate strings in double quotation marks - single-quoted strings are treated as true literals Third way of specifying strings using the heredoc syntax (<<<) - end marker used to terminate the string
echo <<<theEnd
line 1
line 2
line 3
theEnd >>> PHP 2 - PHP Testing Site
The token theEnd is entirely arbitrary - it just needs to be guaranteed not to appear in the text - to close a heredoc string, place a closing token at the start of a line - heredoc strings are interpolated, like double-quoted strings
Understanding Identifiers
p28 - Identifiers are the names of variables - also of functions and classes - Rules defining valid identifiers:
• Identifiers can be of any length and can consist of letters, numbers, and underscores.
• Identifiers cannot begin with a digit.
• In PHP, identifiers are case sensitive. $tireqty is not the same as $TireQty. Trying to use them interchangeably is a common programming error. Function names are an exception to this rule:Their names can be used in any case.
• A variable can have the same name as a function.This usage is confusing, however, and should be avoided. Also, you cannot create a function with the same name as another function.
You can declare and use your own variables in addition to the variables you are passed from the HTML form. One of the features of PHP is that it does not require you to declare variables before using them. A variable is created when you first assign a value to it via the assignment operator (=).
On Bob’s site, you want to work out the total number of items ordered and the total amount payable - create two variables to store these numbers - To begin with, you need to initialize each of these variables to zero by adding these lines to the bottom of your PHP script.
$totalqty = 0;
$totalamount = 0.00;
Each of these two lines creates a variable and assigns a literal value to it. You can also assign variable values to variables, as shown in this example:
$totalqty = 0;
$totalamount = $totalqty;
Examining Variable Types
p29 - A variable’s type refers to kind of data stored in it - PHP provides set of data types - Different data can be stored in different data types
PHP’s Data Types
PHP supports the following basic data types:
• Integer - Used for whole numbers - -1 0 1 etc.
• Float (also called double) -Used for real numbers - 2.35 etc.
• String - Used for strings of characters - "abc" etc.
• Boolean - Used for true or false values - true false
• Array - Used to store multiple data items (see Chapter 3, “Using Arrays”) n Object—Used for storing instances of classes (see Chapter 6)
Two special types are also available: NULL and resource - variables that have not been given a value, have been unset, or have been given the specific value NULL are of type NULL - Certain built-in functions (such as database functions) return variables that have the type resource - they represent external resources (such as database connections)
Type Strength
PHP is called weakly typed, or dynamically typed language - in most programming languages, variables can hold only one type of data - type must be declared before the variable can be used - PHP determines type by value assigned to it - can be changed:
$totalqty = 0;
$totalamount = 0.00;
Because we assigned 0, an integer, to $totalqty, this is now an integer type variable. Similarly, $totalamount is now of type float
$totalamount = ‘Hello’;
The variable $totalamount would then be of type string. PHP changes the variable type according to what is stored in it at any given time. PHP “automagically” knows what data type you put into your variable. It returns the data with the same data type when you retrieve it from the variable
Type Casting
p30 - We can pretend that a variable or value is of a different type by using a type cast, works like in C - just put the temporary type in parentheses in front of the variable
$totalqty = 0;
$totalamount = (float)$totalqty;
The second line means “Take the value stored in $totalqty, interpret it as a float, and store it in $totalamount.”The $totalamount variable will be of type float.The cast variable does not change types, so $totalqty remains of type integer - we can also use the built-in function to test and set type, which you will learn about later in this chapter.
Variable Variables
enable to change name of variable dynamically - all languages enable to change value of variable, but not many allow to change variable’s type, and even fewer allow to change variable’s name.
$varname = ‘tireqty’;
You can then use $$varname in place of $tireqty. For example, you can set the value of $tireqty as follows:
$$varname = 5;
This is exactly equivalent to
$tireqty = 5;
Instead of having to list and use each form variable separately, you can use a loop and variable to process them all automatically - example illustrating this in the section on for loops later in this chapter
Declaring and Using Constants
p31 - A constant stores a value just like a variable, but its value is set once and then cannot be changed elsewhere in the script.
Define constants using the define function:
Add these lines of code to your script. We now have three constants that can be used to calculate the total of the customer’s order
Use uppercase - borrowed from C, makes it easy to distinguish between variables and constants at a glance - not required but will make your code easier to read and maintain - one important difference between constants and variables is that when you refer to a constant, it does not have a dollar sign in front of it. If you want to use the value of a constant, use its name only:
echo TIREPRICE;
PHP sets a large number of constants as its own - phpinfo(); - go phpinfo.php - This function provides a list of PHP’s predefined variables and constants, among other useful information.
Other difference between variables and constants is that constants can store only boolean, integer, float, or string data.These types are collectively known as scalar values.
Understanding Variable Scope
The term scope refers to the places within a script where a particular variable is visible. The six basic scope rules in PHP are as follows:
• Built-in superglobal variables are visible everywhere within a script.
• Constants, once declared, are always visible globally; that is, they can be used inside and outside functions.
• Global variables declared in a script are visible throughout that script, but not inside functions.
• Variables inside functions that are declared as global refer to the global variables of the same name.
• Variables created inside functions and declared as static are invisible from outside the function but keep their value between one execution of the function and the next. (We explain this idea fully in Chapter 5.)
• Variables created inside functions are local to the function and cease to exist when the function terminates.
p32 - The arrays $_GET and $_POST and some other special variables have their own scope rules. They are known as superglobals or autoglobals and can be seen everywhere, both inside and outside functions.
The complete list of superglobals is as follows:
• $GLOBALS—An array of all global variables (Like the global keyword, this allows you to access global variables inside a function - for example, as $GLOBALS[‘myvariable’].)
• $_SERVER—An array of server environment variables
• $_GET—An array of variables passed to the script via the GET method
• $_POST—An array of variables passed to the script via the POST method
• $_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 including the contents of input including $_GET, $_POST, and $_COOKIE (but not including $_FILES since PHP 4.3.0)
• $_SESSION—An array of session variables
We learn each of these later - all the variables we use are global by default
Using Operators
Operators are symbols that you can use to manipulate values and variables by performing an operation on them. We describe here the complete list. Already discussed assignment operator (=) and string concatenation operator (.).
In general, operators can take one, two, or three arguments, with the majority taking two. For example, the assignment operator takes two: the storage location on the left side of the = symbol and an expression on the right side.These arguments are called operands - that is, the things that are being operated upon.
Arithmetic Operators
p33 --- + - * / % (Modulus) --- $a = 27; $b = 10; $result = $a%$b; --- The value stored in the $result variable is the remainder when you divide 27 by 10 --- that is, 7
p34 - You should note that arithmetic operators are usually applied to integers or doubles. If you apply them to strings, PHP will try to convert the string to a number. If it contains an e or an E, it will be read as being in scientific notation and converted to a float; otherwise, it will be converted to an integer. PHP will look for digits at the start of the string and use them as the value; if there are none, the value of the string will be zero.
String Operators
Only one, the concatenation operator (.)
$a = “Bob’s “; $b = “Auto Parts”; $result = $a.$b;
The $result variable now contains the string “Bob’s Auto Parts" - Go
PHP 4 - PHP Testing Site
Assignment Operators
(=) always read "is set to" - $totalqty = 0; - if we call it equals, we will get confused - discuss later
Values Returned from Assignment
Using assignment operator returns overall value similar to other operators - Instead of $a + $b we can write
$a = 0; $b = 6 + ($a = 5); // sets $b to 11 - The value of the whole assignment statement is the value that is assigned to the left operand - you can use parentheses to increase the precedence of a subexpression
Combined Assignment Operators
$a += 5; same as $a = $a + 5; --- all combined ass. operators += -= *= /= %= .=
Pre- and Post-Increment and Decrement
The pre- and post-increment (++) and decrement (--) operators are similar to the += and -= operators, but with a couple of twists - all the increment operators have two effects: they increment and assign a value
$a=4; echo ++$a; --- pre-increment operator - first incrementing $a by 1 and second, returning the incremented value
$a=4; echo $a++; --- post-increment operator - first, the value of $a is returned and printed, and second, it is incremented
Similar for the -- operator: $a=4; echo --$a; --- $a=4; echo $a--;
Reference Operator
(&, an ampersand) - $a = 5; $b = $a; --- These code lines make a second copy of the value in $a and store it in $b. If you subsequently change the value of $a, $b will not change:
$a = 7; // $b will still be 5
$a = 5;
$b = &$a;
$a = 7; // $a and $b are now both 7
We can change this by unsetting one of them as follows:
unset($a);
Unsetting does not change the value of $b (7) but does break the link between $a and the value 7 stored in memory.
Comparison Operators
Expressions using these operators return either of the logical values true or false depending on the result of the comparison.
The Equal Operator
$a == $b --- (shows 1 if true - nothing if false?) - Make shure to use the one you want: $a = $b makes left side to right side and is true if nonzero - Using the assignment operator rather than the equals comparison operator is an easy mistake to make, and you will probably make it many times in your programming career.
Other Comparison Operators
== Equals
=== Identical
!= Not equal
!== Not identical
<> Not equal (comparison operator)
< Less than
> Greater than (comparison operator) <= Less than or equal to
>= Greater than or equal to
One to note is the identical operator (===), which returns true only if the two operands are both equal and of the same type. For example, 0==0 will be true, but 0===0 will not because one zero is an integer and the other zero is a string. Why?
Logical Operators
! --- NOT --- write: !$b --- Returns true if $b is false and vice versa
&& --- AND --- write: $a && $b --- Returns true if both $a and $b are true; otherwise false
|| --- OR --- write: $a || $b --- Returns true if either $a or $b or both are true; otherwise false
and --- AND --- write: $a and $b --- Same as &&, but with lower precedence
or --- OR --- write: $a or $b --- Same as ||, but with lower precedence
xor --- XOR --- write: $a x or $b --- Returns true if either $a or $b is true, and false if they are both true or both false
The and and or operators have lower precedence than the && and || operators
Bitwise Operators
The bitwise operators enable you to treat an integer as the series of bits used to repre- sent it.You probably will not find a lot of use for the bitwise operators in PHP
& --- Bitwise AND --- $a & $b --- Bits set in $a and $b are set in the result
| --- Bitwise OR --- $a | $b --- Bits set in $a or $b are set in the result
~ --- Bitwise NOT --- ~$a --- Bits set in $a are not set in the result and vice versa
^ --- Bitwise XOR --- $a ^ $b --- Bitssetin$aor$bbutnotinbothareset in the result
<< --- Left shift --- $a << $b --- Shifts $a left $b bits
>> --- Right shift --- $a >> $b --- Shifts $a right $b bits
Other Operators
p39 - comma operator (,) separates function arguments and other lists of items - normally used incidentally - operators new and -> are used to instantiate a class and access class members, respectively - more in chapter 6
The Ternary Operator
(?:) similar to the expression version of an if-else statement - discussed later
condition ? value if true : value if false --- example:
($grade >= 50 ? ‘Passed’ : ‘Failed’)
The Error Suppression Operator
(@) can be used in front of any expression - that is, anything that generates or has a value - for example,
$a = @(57/0);
Without the @ operator, this line generates a divide-by-zero warning. With the operator included, the error is suppressed - then you need to write some error handling code to check when a warning has occurred - if you have PHP set up with the track_errors feature enabled in php.ini, the error message will be stored in the global variable $php_errormsg
The Execution Operator pair of operators - pair of backticks (``) - usually located on the same key as the ~ (tilde) symbol on your keyboard
PHP attempts to execute whatever is contained between the backticks as a command at the server’s command line.The value of the expression is the output of the command. For example, under Unix-like operating systems, you can use
$out = `ls -la`; --- on Windows: $out = `dir c:`;
echo '<pre>'.$out.'</pre>';
Either version obtains a directory listing and stores it in $out. It can then be echoed to the browser or dealt with in any other way. There are other ways of executing commands on the server. We cover them in Chapter 19, “Interacting with the File System and the Server.”
Array Operators
p40 - array element operators ([ ]) enable you to access array elements.You can also use the => operator in some array contextshes - these operators are covered in Chapter 3
+ Union - $a+$b - Returns an array containing everything in $a and $b
== Equality - $a==$b - Returns true if $a and $b have the same key and pairs
=== Identity - $a === $b - Returns true if $a and $b have the same key and value pairs the same order
!= Inequality - $a!=$b - Returns true if $a and $b are not equal
<> Inequality - $a<>$b - Returns true if $a and $b are not equal
!== Non-identity - $a !== $b - Returns true if $a and $b are not identical
All have equivalent operators that work on scalar variables --- + performs addition on scalar types and union on arrays - cannot usefully compare arrays to scalar types
The Type Operator instanceof operator is used in object-oriented programming - more in chapter 6 - allows to check whether an object is an instance of a particular class
class sampleClass{};
$myObject = new sampleClass();
if ($myObject instanceof sampleClass)
echo “myObject is an instance of sampleClass”;
Working Out the Form Totals
p41 - Now ready to work out totals and tax on Bob’s order form - add following code to bottom of our PHP script:
Code uses operators addition (+) - multiplication (*) - string concatenation operator (.) - also uses the number_format() function to format totals as strings with two decimal places - this is a function from PHP’s Math library
Understanding Precedence and Associativity
p42 - In general, operators have a set precedence, or order, in which they are evaluated. Operators also have an associativity, which is the order in which operators of the same precedence are evaluated.This order is generally left to right (called left for short), right to left (called right for short), or not relevant.
Table shows operator precedence and associativity in PHP - operators with lowest precedence are at the top - precedence increases as you go down the table:
p43 - Associativity (left/right) - Operators
left ,
left or
left xor
left and
right print
left = += -= *= /= .= %= &= |= ^= ~= <<= >>=
left ? :
left ||
left &&
left |
left ^
left &
n/a == != === !==
n/a < <= > >=
left << >>
left + - .
left * / %
right ! ~ ++ -- (int) (double) (string) (array) (object) @
right []
n/a new
n/a ()
Additional operator with the highest precedence: plain old parentheses () - raises precedence of whatever is contained within them - in this way we can deliberately manipulate or work around the precedence rules when we need to -
$totalamount = $totalamount * (1 + $taxrate); // correct
$totalamount = $totalamount * 1 + $taxrate; // false result!
We can use as many sets of parentheses as we like in an expression - the innermost set of parentheses is evaluated first
Have not yet covered the print language construct, which is equivalent to echo - both constructs generate output
We generally use echo in this book, but you can use print if you find it more readable. Neither print nor echo is really a function, but both can be called as a function with parameters in parentheses. Both can also be treated as an operator: You simply place the string to work with after the keyword echo or print.
Calling print as a function causes it to return a value (1).This capability might be useful if you want to generate output inside a more complex expression but does mean that print is marginally slower than echo.
Using Variable Functions
p44 - PHP provides a library of functions that enable you to manipulate and test vari- ables in different ways
Testing and Setting Variable Types
Most variable functions testing the type of function - The two most general are gettype() and settype() - have the following function prototypes, what arguments expect and what they return:
string gettype(mixed var);
bool settype(mixed var, string type);
To use gettype(), you pass it a variable. It determines the type and returns a string containing the type name: bool, int, double (for floats), string, array, object, resource, or NULL. It returns unknown type if it is not one of the standard types.
To use settype(), you pass it a variable for which you want to change the type and a string containing the new type for that variable from the previous list. Arguments for which many types are permitted are shown with the pseudo-type “mixed” - php.net names it also mixed type - such data type isn't existing
$a = 56;
echo gettype($a).'<br />';
settype($a, 'double');
echo gettype($a).'<br />';
echo writes first integer - after settype writes double
p45 - PHP also provides some specific type-testing functions. Each takes a variable as an argument and returns either true or false.The functions are:
• is_array()—Checks whether the variable is an array
• is_double(), is_float(), is_real() (All the same function)—Checks whether the variable is a float
• is_long(), is_int(), is_integer() (All the same function)—Checks whether the variable is an integer
• is_string()—Checks whether the variable is a string
• is_bool()—Checks whether the variable is a boolean
• is_object()—Checks whether the variable is an object
• is_resource()—Checks whether the variable is a resource
• is_null()—Checks whether the variable is null
• is_scalar()—Checks whether the variable is a scalar, that is, an integer, boolean, string, or float
• is_numeric()—Checks whether the variable is any kind of number or a numeric string
• is_callable()—Checks whether the variable is the name of a valid function
Testing Variable Status
PHP has several functions for testing the status of a variable. The first is isset(), which has the following prototype:
bool isset(mixed var);[;mixed var[,...]]) Wipe a variable out of existence using its companion function, unset(), which has the following prototype:
void unset(mixed var);[;mixed var[,...]])
This function gets rid of the variable it is passed.
The empty() function checks to see whether a variable exists and has a nonempty, nonzero value; it returns true or false accordingly. It has the following prototype:
bool empty(mixed var);
Add to script temorarily:
echo 'isset($tireqty): '.isset($tireqty).'<br />'; // added from p45 - then muted :-)
echo 'isset($nothere): '.isset($nothere).'<br />';
echo 'empty($tireqty): '.empty($tireqty).'<br />';
echo 'empty($nothere): '.empty($nothere).'<br />'; // mute end
The variable $tireqty should return 1 (true) from isset() regardless of what value you entered in that form field and regardless of whether you entered a value at all. Whether it is empty() depends on what you entered in it. The variable $nothere does not exist, so it generates a blank (false) result from isset() and a 1 (true) result from empty(). These functions are handy when you need to make sure that the user filled out the appropriate fields in the form.
Reinterpreting Variables
p46 - You can achieve the equivalent of casting a variable by calling a function. The following three functions can be useful for this task:
int intval(mixed var[, int base]);
float floatval(mixed var);
string strval(mixed var);
...
Making Decisions with Conditionals
Control structures are the structures within a language that allow you to control the flow of execution through a program or script. You can group them into conditionals (or branching) structures and repetition structures (or loops). If you want to sensibly respond to your users’ input, your code needs to be able to make decisions.The constructs that tell your program to make decisions are called conditionals.
if Statements
if( $totalqty == 0 )
echo 'You did not order anything on the previous page!<br />';
echo is executed if condition true
Code Blocks
group a number of statements together as a block {}
if ($totalqty == 0) {
echo '<p style="color:red">';
echo 'You did not order anything on the previous page!';
echo '</p>';
}
When the condition is true, all three lines are executed. When the condition is false, all three lines are ignored
Write readable even if not necessary - statements are indented
elseif Statements switch Statements
Comparing the Different Conditionals
Repeating Actions Through Iteration
while Loops
for and foreach Loops
do...while Loops
Breaking Out of a Control Structure or Script
Employing Alternative Control Structure Syntax
Using declare
p57 - End of Chapter 1 :-)
...
2 - Storing and Retrieving Data
p59 - ...
Storing and Retrieving Bob's Order
We use slightly different orderform with added Shipping Address - orderform.html - processorder.php - vieworders.php - path /02/
The form field for the shipping address is called address.This gives you a variable you can access as $_REQUEST[‘address’] or $_POST[‘address’] or $_GET[‘address’], depending on the form submission METHOD. (See Chapter 1, “PHP Crash Course,” for details.)
In this chapter, you write each order that comes in to the same file. Then you construct a web interface for Bob’s staff to view the orders that have been received.
Processing Files
p61 - Writing data to a file requires three steps:
1. Open the file. If the file doesn’t already exist, you need to create it.
2. Write the data to the file.
3. Close the file.
Similarly, reading data from a file takes three steps:
1. Open the file. If you cannot open the file (for example, if it doesn’t exist), you need to recognize this and exit gracefully.
2. Read data from the file.
3. Close the file.
Opening a File
Use the fopen() function - when you open the file, you need to specify how you intend to use it - known as the file mode
...
Using fopen() to Open a File
p62 - ...
Opening Files Through FTP or HTTP
p64 - In addition to opening local files for reading and writing, you can open files via FTP, HTTP, and other protocols using fopen().You can disable this capability by turning off the allow_url_fopen directive in the php.ini file. If you have trouble opening remote files with fopen(), check your php.ini file - read php.ini online -
• Learn HTML CSS - prove it - Web Design Workshop
• Install Apache PHP MySQL - test it
• Write a HTML form - connect it to a PHP file - prove it
<?php
echo '<p>♡ Hello World! Welcome to our PHP Workshop ♡</p>';
?>
2014-4-1, 16:50 Bln - VE FO - AN Grafik Präs. fertig mit fremden Bildern ok + gute Texte oder Buch Seitenbeispiele FO hilft englisch - VE GO FI Kinder HH Charity PS O - FO WD dann parallel: PHP MySQL 2 Wo - JS iQuery 1 Wo - HTML5 CSS3 1 Wo - = 4 Wochen +/- 1 Wo Puffer - abzügl. TS eV PD IDL eG O Coaching PS P Kinder WD Aufträge oder Jobs etc. - Tag = 16 Arbeitsstunden Wo = 7 Tage - WD + Grafik Aufträge können ab sofort auf IDL Webdesign Grundlage angenommen und ausgeführt werden je nach Einschränkung mit Absagen oder Aufschieben Warten oder Delegation - AD sollte durch VE AN TO JU KI getätigt werden solange vorübergehend bis FO übernimmt
Haus Berlin
1 - 99T - 300/1.406 qm - 6 Zi - Bezug sofort - Wernsdorfer Str. 44, 12527 Berlin (Schmöckwitz)
2 - 125T - 400/1.319 qm - 12524 Berlin-Treptow-Köpenick OT Altglienicke (Bohnsdorf)
3 - 180T - 201/962 qm - 8 Zi - 12526 Berlin (Bohnsdorf)
4 - 185T - 200/760 qm - 5 Zi - 12526 Berlin (Bohnsdorf)
5 - 163T - 163/622 qm - 5 Zi - 12355 Berlin (Rudow)
6 - 152T - 152/791 qm - Oberspreestraße 97, 12489 Berlin (Adlershof)
7 - 180T - 201/962 qm - 8 Zi - 12526 Berlin
Session 8 - 2014-4-5, Bln, 18:25-19:40 PQ p28 - (11:30-13:20 + 15:15-16:30 u.a. + 19:40-5:20 PS + PD SI + Kinder) = 1:15 total time
Session 7 - 2014-4-4, Bln, 5:05-6:00=0:55 Editor compare + check Text Wrangler - Sublime - Komodo etc. - 6:00-7:40=1:40 WR Sessions time :-) - 23:00- 0:15=1:15 PQ p27 = 0:55+1:40+1:15 = 3:50 total time
Session 6 - Thu, 2014-4-3, Berlin, 6:00-7:35=1:35 p24, 12:00-13:30=1:30 p25 (GA Operation) - 16:05-16:40=0:35 processorder1.php - 19:30-23:25=3:55 orderform1.html works :-) - 23:25-23:55=0:30 = 1:35+1:30+0:35+3:55+0:30 = 8:05 total time
Session 5 - Wed, 2014-4-2, Bln, 2:35-6:00=3:25 WD LR - Mac Localhost zeigt nicht mehr an ... :-(( Recherche IN - 11:55-12:10=0:15 VE RP - 13:15-13:55=0:40 Localhost repair :-) Fehler: SSL install - undo :-) 13:55-17:35=3:40 PQ LR p20 ♡ - 18:55-21:10=2:15 LR PQ - 21:35-22:40=1:05 PQ LR p28 - 23:05-0:15=1:10 PQ Ges. Buch R + check = 3:25+0:15+0:40+3:40+2:15+1:05+1:10 = 12:30 total time
Session 4 - Tue, 2014-4-1, Bln, 15:15-17:00=1:45 VE Plan FO 1 Wo HTML CSS - 1 Wo JavaScript iQuery - 2 Wo PHP MySQL - Tag = 16 Arbeitsstunden WD - Wo = 7 Tage :-) ♡ - also 4 Wo +/- 1 Wo Puffer (HTML CSS Abzug, kann auch nebenher gemacht werden - oder sonst. Abzüge wenn schneller LR :-) - 18:00-18:25_0:25 RP AN - 18:25-20:20=1:55 PQ (= PHP and MySQL Web Development :-) Ch 1 = 1:45+0:25+1:55 = 4:05 total time
Session 3 - Mon, 2014-3-31, Bln, 12:05-13:30=1:25 RP VE AN PHP INstall etc. - 13:30-17:10=3:40 Install SSL failed - IN WD books + personalities - 17:30-20:25=2:55 PHP books R - 21:25-2:55=5:30 PHP & MySQL WR LR Introduction + Ch 1 Start ♡ - 2:55-7:00=4:05 HR YT Luke + Laura about PHP and MySQL ♡ - JSQ WR - Sites WD TW Top + YT WD Harvard Course ♡ - 7:00-7:40=0:40 RP VE AN = 1:25+3:40+2:55+5:30+4:05+0:40 = 17:55 total time
Session 2 - Sun, 2014-3-30, Bln, 12:00-13:10=1:10 VE RP Computersprachen Entscheidung PHP LR - 13:20-14:05=0:45 RP AN - 14:05-15:30=1:25 R PHP and MySQL Web Development ♡ - 17:40-18:20=0:40 RP VE AN - 18:20-19:00=0:40 Install Apache ♡ - 20:10-3:40=7:30 Install PHP + MySQL ♡ = 1:10+0:45+1:25+0:40+0:40+7:30 = 12:10 total time
Session 1 - Sat, 2014-3-29, Berlin, 9:15-11:00=1:45 LR JavaScript & jQuery Ch. 2 ♡ - 13:15-15:00=1:45 JSQ LR AJAX AMP etc. - 15:00-17:40=2:40 p351 Need to LR PHP - Wikipedia & books research - 17:40-20:40=3:00 Rasmus Lerdorf On PHP - YT - PHP Testing Site online ♡ - 20:40-23:30=2:50 Demo PHP VE AN + R PHP books ♡ - 2:00-5:30=3:30 Best Webdesign IN WR HP + Sublime Editor = 1:45+1:45+2:40+3:00+2:50+3:30 = 15:30 total time