PHP Reference: Beginner to Intermediate PHP5
If multiple pages will see the same functions, then make a different onefunctions.php file (name it whatever you like) and require() or
require_once() with pages that will need to use those functions. For speed
and file size, page specific functions should be included directly on the
necessary page.
exit([$string])
die([$string])
Stops the current script and outputs the optional $string.
Example:
$result = @mysql_connect('db', 'user', 'pw')
or die('Unable to connect to database!'); echo 'If it fails, this will never be seen';
Unable to connect to database!
Note: The above output would only display if it failed. If the @ was not present before mysql_connect(), PHP would output a warning as well.
eval($string)
Evaluates a string as if it was code. This can be used to store code in a database and have it processed dynamically by PHP as if it were part of the page. All appropriate aspects of code must be included, such as escaping items with a backslash (\) and including a semicolon (;) at the end of the string.
Example:
$name = 'Mario';
$string = 'My name is $name.'; // Note the single quotes echo $string;
$code = "\$evalstring = \" $string \" ;";
// Effect of backslash escape: $code = "$evalstring = " $string " ;"; eval($code); // eval($evalstring = " My name is $name " ;);
// $evalstring is the same as $string, except with double quotes now echo $evalstring;
My name is $name. My name is Mario.
sleep($integer)
Pauses PHP for $integer amount of seconds before continuing.
Example:
sleep(2); // pause for 2 seconds
usleep($integer)Pauses PHP for $integer amount of microseconds before continuing.
Example:
usleep(1000000); // pause for 1 second
uniqid([$scalar [, entropy]])
entropy – [optional] $boolean default: FALSE, 13 character output
Generate a unique ID based on the $scalar. If no input is given, the current time in microseconds is used automatically. This is best used in combination with other functions to generate a more unique value. If the $scalar is an empty string ('') and entropy is set to TRUE, a 26 character output is provided instead of a 13 character output.
Examples:
$id = uniqid();
echo $id;
47cc82c917c99
$random_id = uniqid(mt_rand());
echo $random_id;
63957259147cc82c917cdb
$md5 = md5($random_id);
echo $md5;
ea573adcdf20215bb391b82c2df3851f
See Also:
md5() – MD5 algorithm based encryption
setcookie(name [, value] [, time] [, path] [, domain] [, secure] [, httponly])
name – $string
value – [optional] $string
time – [optional] $integer default: till the end of the session
path – [optional] $string default: current directory
domain – [optional] $string default: current domain (e.g.
http://www.example.com)
secure – [optional] $boolean default: FALSE, does not require a secure connection
httponly – [optional] $boolean default: FALSE, available to scripting languages
PHP Reference: Beginner to Intermediate PHP5
Sets a cookie2, visible to the server on the next page load. To send then default value, use a set of single quotes ('') for each argument you want to skip except the time argument, which should use 0 to send the default value. In most cases, providing the name, value, time, and domain will cover most uses (with '' for path).
Examples:
setcookie('Cookie','Set till end of this session',0);
// This will display properly after the page has been reloaded print_r($_COOKIE);
Array ( [Cookie] => Set till end of this session )
setcookie('Cookie','Set for 60 seconds for all subdomains of example.com, such as www., mail., etc.',time()+60,'','.example.com'); print_r($_COOKIE);
Array ( [Cookie] => Set for 60 seconds for all subdomains of example.com, such as www., mail., etc. )
Some common times used for expiration: time()+60*60*24 is equal to 1 day time()+60*60*24*30 is equal to 30 days
time()-1 is one second in the past, used to expire/delete a cookie
setcookie('Cookie','',time()-1);
// expires the Cookie named 'Cookie'. Note the empty string for value
urlencode($string)
Changes the formatting of $string to the proper format for passing through a URL, such as part of a GET query, returning the new string.
Example:
$string = 'Hello There! How are you?'; echo urlencode($string);
Hello+There%21+How+are+you%3F
urldecode($string)
Changes the formatting of $string from the URL compatible (such as a GET query) format to human readable format, returning the new string.
Example:
$string = 'Hello+There%21+How+are+you%3F'; echo urldecode($string);
Hello There! How are you?
Must be sent prior to any headers or anything else is sent to the page (including the <html> tag). See ob_start() for an easy way to make this work
get_magic_quotes_gpc()
Returns 0 if it is off, 1 otherwise.
Used to determine if magic quotes is on. This check is used for code portability and determining if the addition of backslashes is necessary for security purposes and preventing SQL injection. Magic_quotes_gpc processes GET/POST/Cookie data and, if turned on, automatically processes the above data every time with addslashes().
Example:
if (get_magic_quotes_gpc()){
echo 'Magic Quotes is on!';
}else{
echo 'Magic Quotes is NOT on, use addslashes()!';
}
// This is the default setting for PHP5 installations Magic Quotes is NOT on, use addslashes()!
See Also:
addslashes() – Add backslashes to certain special characters in a string stripslashes() – Remove backslashes from certain special characters in a string
phpinfo([option])
option – [optional] Used with a specific $integer or $string to display only a portion of phpinfo(). Specific options excluded for simplicity.
By default, phpinfo() will display everything about the PHP installation, including the modules, version, variables, etc.
Example:
phpinfo();
Display All PHP Errors and Warnings
To catch programming errors, mistakes, or make sure that PHP is not making any assumptions about your code, troubleshooting is best done with all PHP errors being displayed. The following two lines of code will enable this mode:
error_reporting(E_ALL);
ini_set('display_errors', '1');
mail(to, subject, message [, headers] [, parameters])
to – $string
subject – $string
message – $string
headers – [optional] $string
parameters – [optional] $string
This uses the sendmail binary which may not be configured or available
Example:
$to = 'johndoe@example.com';
$subject = 'Hello';
$message = 'Hi John Doe';
$headers = 'From: janedoe@example.com' . "\r\n" .
'Reply-To: janedoe@example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
exec(command [, output] [, return])
command – $string to execute the external program
output – [optional] Variable name to assign all the output of the command as an array
return – [optional] Variable name to assign the return status as an $integer.
Works only when output is also present.
The function will return the last line of the executed program's output. If the program fails to run and both output and return are both present, return will be most commonly set to 0 when successfully executed and 127 when the command fails.
Example (Linux specific program):
$lastline = exec('cal', $output, $return);
echo '<pre>'; // For better formatting of print_r()
print_r($output);
var_dump($lastline, $return);
Array
(
[0] => March 2008
[1] => Su Mo Tu We Th Fr Sa
[2] => 1
[3] => 2 3 4 5 6 7 8
[4] => 9 10 11 12 13 14 15
[5] => 16 17 18 19 20 21 22
[6] => 23 24 25 26 27 28 29
[7] => 30 31
)
string(5) "30 31"
int(0)
header($string [, replace_flag] [, http_response_code])
replace_flag – [optional] $boolean default: TRUE, replace similar header http_response_code – [optional] $integer
Sends an HTTP header specified as $string.
Note: Header() must be used prior to any other output is sent to the user/browser.
Use ob_start() to workaround this.
Examples:
header('Location: http://www.someotherplace.com');
// Redirects the user to the provided URL header('HTTP/1.0 404 Not Found');
// Sends the HTTP status code 404
See Also:
ob_start() – Start the output buffer
Classes & Object Oriented PHP
While this is outside of the scope of this book, I have included a few notes here on basic usage to extend the flexibility of this book.
Class Structure: ( brackets[] delineate optional syntax )
class class_name [extends base_class]{
var variable_name; // Defines a variable function function_name([arguments]) {
// Stuff to do goes here
}
}
Refer to the containing class – use the reserved variable $this
Declare a class: $variable = new class_name();
Creating an object: $variable->function_name();
Static call to an object: class_name::function_name();
No comments:
Post a Comment