PHP
Server-side code.
Normally in public_html
Normally named like:
file.php
File contains normal HTML, and PHP code mixed in, delimited as follows:
<html>
<body>
html code
<?php
php code
?>
more html code
-
PHP gets interpreted on server side before resulting HTML stream is returned to client.
Whatever the PHP writes to
standard output (stdout)
appears in the browser.
-
Client can't see PHP code:
Unlike with Javascript, client can't see the code that generated the HTML.
-
PHP used for interaction with databases/files on server.
Basics
Environment
- PHP demo
- Return a single environment variable:
- Debugging can be difficult.
- The issue:
- If PHP writes error messages to stdout (to web page), hackers can use this to experiment, and test for server-side vulnerabilities.
- So servers often turn off PHP error output.
- Over-ride server defaults: Turn on error output for your own PHP. Include these lines:
ini_set ( 'display_errors', true );
ini_set ( 'display_startup_errors', true );
error_reporting ( E_ALL );
and then error messages are displayed.
- Comment/uncomment this block.
Exercise:
Put this error in a PHP file:
nonExistentFunction();
View it with and without those 3 lines above inserted.
Dump variables
- You can dump variables to stdout:
print "x is $x";
- To display full structure of a complex object:
var_dump($x);
print_r($x);
Multi-line string
A multi-line string can be useful.
Assign a chunk of HTML to a string, and maybe re-use it in different places.
Strings in PHP
shows ways of doing a multi-line string:
- Let quote run over:
Advantages: Simple syntax.
Disadvantages: All double quotes in the text must be changed to single quotes or else "escaped".
Can't just dump HTML in here.
- Use a heredoc:
$var = <<<MULTILINE_DELIMITER
text
text
MULTILINE_DELIMITER;
Advantages: Can have single and double quotes in the text unchanged.
Can just dump HTML in here.
Disadvantages: Complex syntax.
Tutorials