PHP syntax |
Basic structure of PHP
PHP documents look like HTML with code inside,
but it is not HTML and
the PHP code itself will not render inside a browser.
<?php
... php code (each statement ends with a semicolon) ...
?>
How to save your PHP pages
Internal to the file
Comments in PHP
Three syntax styles for comments
- // this is a comment
- # this is a comment
- /* this is for
multiple lines of comments */
Variables
- Variable name begins with a $
- variable names are case-sensitive
$variable_name = value;
- Variables may be initialized without being declared
Arrays
- Each array element consists of two parts: key and value
(key may be integer or string)
- To create an array
- Use the assignment operation
$states[0] = "Virginia";
$states[] = "Georgia"; // implicit key = the array's current key + 1
$capitals['VA'] = "Richmond";
$matrix[7][11] = 2.718;
- Use the
array construct
$list = array(17, 24, 30); // specify values without keys, PHP interpreter will furnish the numeric keys 0, 1, 2
$agelist = array("Joe" => 17, "Mary" => 24, "Ann" => 30); // specify values with keys
- To access array elements
$list[2] = 34;
$agelist['Mary'] = 44;
Functions and control structures
Output statements
echo $myVar;
print "Hello World!";
printf("Your total bill is %5.2f", $price);
note: examples on formatting
%10s — a character string field of 10 characters
%6d — an integer field of six digits
%5.2f — a float or double field of five spaces,
with two digits to the right of the decimal point, the decimal point,
and two digits to the left
- String concatenation uses .
print "Hello, ".$_POST['name'];
Handling data from the client
- Often called form variable or form data
- Store in implicit arrays
$_GET['form_input_name'] // The form data is sent with the HTTP GET method.
$_POST['form_input_name'] // The form data is sent with the HTTP POST method.
$_SERVER['PHP_SELF']; // PHP super global variable which holds information about headers, paths, and script locations.
// Returns the filename of the currently executing script
<?php
if ( isSet($_POST['submit']) )
{
print "Hello, ".$_POST['name'];
}
else
{
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
Your name: <input type="text" name="name"> <br />
<input type="submit" name="submit">
</form>
<?php
}
?>
Reading and writing files
- Open file:
fopen(filename, mode)
- Read file:
fgets(file, length)
- Write file:
fputs(file, string, length)
<?php
$file = fopen("infilename.txt", "r"); // r: read only
while ( !feof($file) ) {
echo fgets($file), "<br />";
}
?>
<?php
$file = fopen("outfilename.txt", "a"); // a: write only, append
fputs($file, $HTTP_USER_AGENT."\n");
?>
|