Use LEFT and RIGHT arrow keys to navigate between flashcards;
Use UP and DOWN arrow keys to flip the card;
H to show hint;
A reads text to speech;
194 Cards in this Set
- Front
- Back
PHP (abbr)
|
Hypertext Preprocessor
PHP is a server-side scripting language, like ASP PHP scripts are executed on the server PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.) |
|
PHP server scripts are surrounded by delimiters, which?
|
<?php
echo "Hello World"; ?> |
|
When using the POST method, variables are displayed in the URL true or false
|
False
|
|
What is the correct way to include the file "time.inc" ?
|
<?php include_once('<path_to_file>/time.inc'); ?>
|
|
What is the correct way to connect to a MySQL database?
|
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
Then you can use mysqli to query the database with $results = $mysqli->query("SELECT a FROM b"); |
|
The correct way of declaring a variable in PHP:
|
$var_name = value;
|
|
PHP is a Loosely Typed Language
|
In PHP, a variable does not need to be declared before adding a value to it.
|
|
Naming Rules for Variables
|
A variable name must start with a letter or an underscore "_"
A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and _ ) A variable name should not contain spaces. If a variable name is more than one word, it should be separated with an underscore ($my_string), or with capitalization ($myString) |
|
Concatenation Operator
|
<?php
$txt1="Hello World!"; $txt2="What a nice day!"; echo $txt1 . " " . $txt2; ?> |
|
return the length of a string
|
<?php
echo strlen("Hello world!"); ?> |
|
search for a character/text within a string
|
strpos() function
<?php echo strpos("Hello world!", "world"); ?> |
|
Returns a string with backslashes in front of the specified characters
|
addcslashes()
<?php $str = "Hello, my name is Kai Jim."; echo $str."<br />"; echo addcslashes($str,'m')."<br />"; echo addcslashes($str,'K')."<br />"; ?> Hello, my name is Kai Jim. Hello, \my na\me is Kai Ji\m. Hello, my name is \Kai Jim. |
|
converts a string of ASCII characters to hexadecimal values. The string can be converted back using the pack() function
|
bin2hex(string)
- <?php $str = "Hello world!"; echo bin2hex($str) . "<br />"; echo pack("H*",bin2hex($str)) . "<br />"; ?> - 48656c6c6f20776f726c6421 Hello world! |
|
function will remove a white space or other predefined character from the right end of a string
|
chop()
- <?php $str = "Hello World!\n\n"; echo $str; echo chop($str); ?> The source output of the code above will be: <html> <body> Hello World! Hello World!</body> </html> - Hello World! Hello World! |
|
function returns a character from the specified ASCII value
|
chr()
- <?php echo chr(52)."<br />"; echo chr(052)."<br />"; echo chr(0x52)."<br />"; ?> - 4 * R |
|
function splits a string into a series of smaller parts
|
chunk_split(string,length,end)
- <?php $str = "Hello world!"; echo chunk_split($str,1,"."); ?> - H.e.l.l.o. .w.o.r.l.d.!. |
|
function decodes a uuencoded string
|
convert_uudecode(string)
- <?php $str = ",2&5L;&\@=V]R;&0A `"; echo convert_uudecode($str); ?> - Hello world! |
|
unction encodes a string using the uuencode algorithm
|
convert_uuencode(string)
- <?php $str = "Hello world!"; echo convert_uuencode($str); ?> The output of the code<?php $str = "Hello world!"; echo convert_uuencode($str); ?> - ,2&5L;&\@=V]R;&0A ` ,2&5L;&\@=V]R;&0A ` |
|
function returns how many times an ASCII character occurs within a string and returns the information
|
count_chars(string, mode)
- <?php $str = "Hello World!"; print_r(count_chars($str,1)); ?> - Array ( [32] => 1 [33] => 1 [72] => 1 [87] => 1 [100] => 1 [101] => 1 [108] => 3 [111] => 2 [114] => 1 ) |
|
function calculates a 32-bit CRC (cyclic redundancy checksum) for a string
|
crc32()
- <?php $str = crc32("Hello world!"); echo 'Without %u: '.$str."<br />"; echo 'With %u: '; printf("%u",$str); ?> - Without %u: 461707669 With %u: 461707669 |
|
if Statement
|
<html>
<body> <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; ?> </body> </html> |
|
if...else Statement
|
<html>
<body> <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; else echo "Have a nice day!"; ?> </body> </html> |
|
if...elseif....else Statement
|
<html>
<body> <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; elseif ($d=="Sun") echo "Have a nice Sunday!"; else echo "Have a nice day!"; ?> </body> </html> |
|
PHP Switch Statement
|
<html>
<body> <?php switch ($x) { case 1: echo "Number 1"; break; case 2: echo "Number 2"; break; case 3: echo "Number 3"; break; default: echo "No number between 1 and 3"; } ?> </body> </html> |
|
Numeric Arrays sores each array element with a numeric index
|
--Method 1 $cars=array("Saab","Volvo","BMW","Toyota");
--Method 2 $cars[0]="Saab"; $cars[1]="Volvo"; $cars[2]="BMW"; $cars[3]="Toyota"; |
|
Associative Arrays each ID key is associated with a value
|
--Method 1
$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34); --Method 2 $ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34"; |
|
Multidimensional Arrays
|
$families = array
( "Griffin"=>array ( "Peter", "Lois", "Megan" ), "Quagmire"=>array ( "Glenn" ), "Brown"=>array ( "Cleveland", "Loretta", "Junior" ) ); |
|
while Loop
|
<html>
<body> <?php $i=1; while($i<=5) { echo "The number is " . $i . "<br />"; $i++; } ?> </body> </html> |
|
do...while Statement
|
<html>
<body> <?php $i=1; do { $i++; echo "The number is " . $i . "<br />"; } while ($i<=5); ?> </body> </html> |
|
for Loop
|
<html>
<body> <?php for ($i=1; $i<=5; $i++) { echo "The number is " . $i . "<br />"; } ?> </body> </html> |
|
foreach Loop
|
<html>
<body> <?php $x=array("one","two","three"); foreach ($x as $value) { echo $value . "<br />"; } ?> </body> </html |
|
Create a PHP Function
|
<html>
<body> <?php function writeName() { echo "Kai Jim Refsnes"; } echo "My name is "; writeName(); ?> </body> </html> |
|
PHP Functions - Adding parameters
|
<html>
<body> <?php function writeName($fname) { echo $fname . " Refsnes.<br />"; } echo "My name is "; writeName("Kai Jim"); echo "My sister's name is "; writeName("Hege"); echo "My brother's name is "; writeName("Stale"); ?> </body> </html> |
|
PHP Functions - Return values
|
<html>
<body> <?php function add($x,$y) { $total=$x+$y; return $total; } echo "1 + 16 = " . add(1,16); ?> </body> </html> |
|
PHP Form Handling
<html> <body> <form action="welcome.php" method="post"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> </body> </html> |
"welcome.php" looks like this:
<html> <body> Welcome <?php echo $_POST["fname"]; ?>!<br /> You are <?php echo $_POST["age"]; ?> years old. </body> </html> |
|
$_GET Variable
<form action="welcome.php" method="get"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> How the URL looks |
http://www.w3schools.com/welcome.php?fname=Peter&age=37
Welcome <?php echo $_GET["fname"]; ?>.<br /> You are <?php echo $_GET["age"]; ?> years old! |
|
$_POST Variable
<form action="welcome.php" method="post"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> How the URL looks> |
http://www.w3schools.com/welcome.php
Welcome <?php echo $_POST["fname"]; ?>!<br /> You are <?php echo $_POST["age"]; ?> years old. |
|
PHP $_REQUEST Variable
|
The predefined $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE.
The $_REQUEST variable can be used to collect form data sent with both the GET and POST methods. Example Welcome <?php echo $_REQUEST["fname"]; ?>!<br /> You are <?php echo $_REQUEST["age"]; ?> years old. |
|
what PHP date() function does
|
formats a timestamp to a more readable date and time
date(format,timestamp) <?php echo date("Y/m/d") . "<br />"; echo date("Y.m.d") . "<br />"; echo date("Y-m-d"); ?> --- 2009/05/11 2009.05.11 2009-05-11 |
|
PHP Date() - Adding a Timestamp
|
The optional timestamp parameter in the date() function specifies a timestamp. If you do not specify a timestamp, the current date and time will be used.
The mktime() function returns the Unix timestamp for a date. |
|
Syntax for mktime()
|
To go one day in the future we simply add one to the day argument of mktime():
<?php $tomorrow = mktime(0,0,0,date("m"),date("d")+1,date("Y")); echo "Tomorrow is ".date("Y/m/d", $tomorrow); ?> The output of the code above could be something like this: Tomorrow is 2009/05/12 |
|
SSI
EOF |
SSI - Server Side Includes
EOF - End Of File |
|
You can insert the content of one PHP file into another PHP file before the server executes it, with what function(s)
|
include()
generates a warning, but the script will continue execution --- require() generates a fatal error, and the script will stop |
|
function used to open files in PHP
|
fopen() function
<html> <body> <?php $file=fopen("welcome.txt","r"); ?> </body> </html> |
|
mode for opening a file with fopen() (r,r+,w,w+)
|
r - read only. start at beginning of file
r+ - read/write. start at beginning of file w - write only. open and clear the contents of file. or creates a new file if it doesn't exist w+ - read/write. opens ad clear the contents of file; or creates a new file i it doesn't exist |
|
mode for opening a file with fopen() (a,a+,x,x+)
|
a - append. opens and writes to the end of the file or create a new file if it doesn't exist
a+ - read/append. preserves file content by writing to the end of the file x - write only. create a new file. returns FALSE and an error if file already exists x+ - read/write. create a new file. returns FALSE and an error if file already exist |
|
function for closing a file
|
fclose()
<?php $file = fopen("test.txt","r"); //some code to be executed fclose($file); ?> |
|
Check End-of-file function
|
if (feof($file)) echo "End of file";
|
|
Reading a File Line by Line function
|
fgets()
<?php $file=fopen("welcome.txt","r") or exit("Unable to open file!"); while (!feof($file)) { echo fgetc($file); } fclose($file); ?> |
|
Reading a File Character by Character function
|
fgetc()
<?php $file=fopen("welcome.txt","r") or exit("Unable to open file!"); while (!feof($file)) { echo fgetc($file); } fclose($file); ?> |
|
Create an Upload-File Form HTML
|
<html>
<body> <form action="upload_file.php" method="post" enctype="multipart/form-data"> <label for="file">Filename:</label> <input type="file" name="file" id="file" /> <br /> <input type="submit" name="submit" value="Submit" /> </form> </body> </html> |
|
Create The Upload Script PHP
|
<?php
if ($_FILES["file"]["error"] > 0) { echo "Error: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Stored in: " . $_FILES["file"]["tmp_name"]; } ?> |
|
using the global PHP $_FILES array
|
you can upload files from a client computer to the remote server.
The first parameter is the form's input name and the second index can be either "name", "type", "size", "tmp_name" or "error". Like this: $_FILES["file"]["name"] - the name of the uploaded file $_FILES["file"]["type"] - the type of the uploaded file $_FILES["file"]["size"] - the size in bytes of the uploaded file $_FILES["file"]["tmp_name"] - the name of the temporary copy of the file stored on the server $_FILES["file"]["error"] - the error code resulting from the file upload This is a very simple way of uploading files. For security reasons, you should add restrictions on what the user is allowed to upload. |
|
how to get PHP $_FILES array the name of the uploaded file
|
$_FILES["file"]["name"] - the name of the uploaded file
|
|
how to get PHP $_FILES array the type of the uploaded file
|
$_FILES["file"]["type"] - the type of the uploaded file
|
|
how to get PHP $_FILES array the size in bytes of the uploaded file
|
$_FILES["file"]["size"] - the size in bytes of the uploaded file
|
|
how to get PHP $_FILES array the name of the temporary copy of the file stored on the server
|
$_FILES["file"]["tmp_name"] - the name of the temporary copy of the file stored on the server
|
|
how to get PHP $_FILES array the error code resulting from the file upload
|
$_FILES["file"]["error"] - the error code resulting from the file upload
|
|
script we add some restrictions to the file upload. The user may only upload .gif or .jpeg files and the file size must be under 20 kb
|
<?php
if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 20000)) { if ($_FILES["file"]["error"] > 0) { echo "Error: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Stored in: " . $_FILES["file"]["tmp_name"]; } } else { echo "Invalid file"; } ?> |
|
Saving the Uploaded File
The temporary copied files disappears when the script ends. To store the uploaded file we need to copy it to a different location |
<?php
if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 20000)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />"; if (file_exists("upload/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); echo "Stored in: " . "upload/" . $_FILES["file"]["name"]; } } } else { echo "Invalid file"; } ?> |
|
What is a Cookie?
|
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.
|
|
Create a cookie
|
<?php
setcookie("user", "Alex Porter", time()+3600); ?> <html> we will create a cookie named "user" and assign the value "Alex Porter" to it |
|
How to Retrieve a Cookie Value?
|
PHP $_COOKIE variable is used to retrieve a cookie value.
<?php // Print a cookie echo $_COOKIE["user"]; // A way to view all cookies print_r($_COOKIE); ?> |
|
function to find out if a cookie has been set
|
<html>
<body> <?php if (isset($_COOKIE["user"])) echo "Welcome " . $_COOKIE["user"] . "!<br />"; else echo "Welcome guest!<br />"; ?> </body> </html> |
|
How to Delete a Cookie?
|
<?php
// set the expiration date to one hour ago setcookie("user", "", time()-3600); ?> |
|
PHP Session Variables
|
A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application.
|
|
Starting a PHP Session
|
Before you can store user information in your PHP session, you must first start up the session.
Note: The session_start() function must appear BEFORE the <html> tag: <?php session_start(); ?> <html> <body> </body> </html> |
|
Storing a Session Variable
|
<?php
session_start(); // store session data $_SESSION['views']=1; ?> <html> <body> <?php //retrieve session data echo "Pageviews=". $_SESSION['views']; ?> </body> </html> |
|
correct way to store and retrieve session variables is to use the
|
PHP $_SESSION
|
|
delete a session data
|
unset() function is used to free the specified session variable:
<?php unset($_SESSION['views']); ?> |
|
completely destroy the session
|
<?php
session_destroy(); ?> Note: session_destroy() will reset your session and you will lose all your stored session data. |
|
function used to send emails from inside a script
|
mail(to,subject,message,headers,parameters)
|
|
PHP Simple E-Mail
|
<?php
$to = "someone@example.com"; $subject = "Test mail"; $message = "Hello! This is a simple email message."; $from = "someonelse@example.com"; $headers = "From:" . $from; mail($to,$subject,$message,$headers); echo "Mail Sent."; ?> |
|
most common error checking methods in PHP (3)
|
Simple "die()" statements
Custom errors and error triggers Error reporting |
|
Basic Error Handling: Using the die() function
|
<?php
if(!file_exists("welcome.txt")) { die("File not found"); } else { $file=fopen("welcome.txt","r"); } ?> |
|
Creating a Custom Error Handler
|
error_function(error_level,error_message, error_file,error_line,error_context)
error_level and error_message are required |
|
error_function error_file parameter option
|
optional
specifies the filename in which the error occurred |
|
error_function error_line parameter option
|
optional
specifies the line number in which the error occurred |
|
error_function error_context parameter option
|
optional
specifies an array containing every variable, and their values, in use when the error occurred |
|
error_function error_level parameter option
|
required
specifies the error report level for the user-defined error. Must be a value number |
|
error_function error_message parameter level
|
required
specifies the error message for the user-defined error |
|
error_function error_level possible report levels
2 8 256 |
2 - E_WARNING - Non-fatal run time error. Execution of script is not halted
8 - E_NOTICE - run-time notices. The script found something that might be an error but could also happen when running a script normally 256 - E_USER_ERROR - fatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function error() |
|
error_function error_level possible report levels
512 1024 4096 8191 |
512 - E_USER_WARNING - Non-fatal user-generated warning. This is like an E_WARNING set by the programmer using the PHP function trigger_error()
1024 - E_USER_NOTICE - User-generated notice. This is like an E_NOTICE set by the programmer using the PHP function trigger_error() 4096 - E_RECOVERABLE_ERROR - Catchable fatal error. This is like an E_ERROR but can be caught by a user defined handle 8191 - E_ALL - All errors and warnings, except level E_STRICT (E_STRICT will be part of E_ALL as of PHP 6.0) |
|
function to handle errors (code)
|
function customError($errno, $errstr)
{ echo "<b>Error:</b> [$errno] $errstr<br />"; echo "Ending Script"; die(); } |
|
Set Error Handler
|
default error handler for PHP is the built in error handler using set_error_handler("customError");
|
|
Trigger an Error
|
script where users can input data it is useful to trigger errors when an illegal input occurs. In PHP, this is done by the trigger_error() function
<?php $test=2; if ($test>1) { trigger_error("Value must be 1 or below"); } ?> |
|
Error Logging
|
By default, PHP sends an error log to the servers logging system or a file, depending on how the error_log configuration is set in the php.ini file. By using the error_log() function you can send error logs to a specified file or a remote destination.
|
|
What is an Exception
|
Exception handling is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs. This condition is called an exception.
|
|
This is what normally happens when an exception is triggered:
|
1)The current code state is saved
2)The code execution will switch to a predefined (custom) exception handler function 3)Depending on the situation, the handler may then resume the execution from the saved code state, terminate the script execution or continue the script from a different location in the code |
|
Basic Use of Exceptions
|
When an exception is thrown, the code following it will not be executed, and PHP will try to find the matching "catch" block.
If an exception is not caught, a fatal error will be issued with an "Uncaught Exception" message. |
|
exception without catching it (code)
|
<?php
//create function with an exception function checkNum($number) { if($number>1) { throw new Exception("Value must be 1 or below"); } return true; } //trigger exception checkNum(2); ?> |
|
Try, throw and catch (def)
|
1)Try - A function using an exception should be in a "try" block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is "thrown"
2)Throw - This is how you trigger an exception. Each "throw" must have at least one "catch" 3)Catch - A "catch" block retrieves an exception and creates an object containing the exception information |
|
trigger an exception with valid code
|
<?php
//create function with an exception function checkNum($number) { if($number>1) { throw new Exception("Value must be 1 or below"); } return true; } //trigger exception in a "try" block try { checkNum(2); //If the exception is thrown, this text will not be shown echo 'If you see this, the number is 1 or below'; } //catch exception catch(Exception $e) { echo 'Message: ' .$e->getMessage(); } ?> |
|
create an exception class (code)
|
<?php
class customException extends Exception { public function errorMessage() { //error message $errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile() .': <b>'.$this->getMessage().'</b> is not a valid E-Mail address'; return $errorMsg; } } $email = "someone@example...com"; try { //check if if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) { //throw exception if email is not valid throw new customException($email); } } catch (customException $e) { //display custom message echo $e->errorMessage(); } ?> |
|
Re-throwing Exceptions (def)
|
Sometimes, when an exception is thrown, you may wish to handle it differently than the standard way. It is possible to throw an exception a second time within a "catch" block.
A script should hide system errors from users. System errors may be important for the coder, but is of no interest to the user. To make things easier for the user you can re-throw the exception with a user friendly message |
|
re-throwing Exceptions (code)
|
<?php
class customException extends Exception { public function errorMessage() { //error message $errorMsg = $this->getMessage().' is not a valid E-Mail address.'; return $errorMsg; } } $email = "someone@example.com"; try { try { //check for "example" in mail address if(strpos($email, "example") !== FALSE) { //throw exception if email is not valid throw new Exception($email); } } catch(Exception $e) { //re-throw exception throw new customException($email); } } catch (customException $e) { //display custom message echo $e->errorMessage(); } ?> |
|
Set a Top Level Exception Handler
|
The set_exception_handler() function sets a user-defined function to handle all uncaught exceptions.
<?php function myException($exception) { echo "<b>Exception:</b> " , $exception->getMessage(); } set_exception_handler('myException'); throw new Exception('Uncaught Exception occurred'); ?> The output of the code above should be something like this: Exception: Uncaught Exception occurred In the code above there was no "catch" block. Instead, the top level exception handler triggered. This function should be used to catch uncaught exceptions. |
|
What is a PHP Filter?
|
A PHP filter is used to validate and filter data coming from insecure sources.
To test, validate and filter user input or custom data is an important part of any web application. The PHP filter extension is designed to make data filtering easier and quicker. |
|
To filter a variable, use one of the following filter functions: (4)
|
1) filter_var() - Filters a single variable with a specified filter
2) filter_var_array() - Filter several variables with the same or different filters 3) filter_input - Get one input variable and filter it 4) filter_input_array - Get several input variables and filter them with the same or different filters |
|
validate an integer using the filter_var() function example
|
<?php
$int = 123; if(!filter_var($int, FILTER_VALIDATE_INT)) { echo("Integer is not valid"); } else { echo("Integer is valid"); } ?> |
|
Validating filers (3)
|
Are used to validate user input
Strict format rules (like URL or E-Mail validating) Returns the expected type on success or FALSE on failure |
|
Sanitizing filters(3)
|
Are used to allow or disallow specified characters in a string
No data format rules Always return the string |
|
Options and Flags in filtering
|
Options and flags are used to add additional filtering options to the specified filters.
Different filters have different options and flags. |
|
Validate Input from a form to see if it is an email (code)
|
<?php
if(!filter_has_var(INPUT_GET, "email")) { echo("Input type does not exist"); } else { if (!filter_input(INPUT_GET, "email", FILTER_VALIDATE_EMAIL)) { echo "E-Mail is not valid"; } else { echo "E-Mail is valid"; } } ?> |
|
Sanitize Input an URL sent from a form (code)
|
<?php
if(!filter_has_var(INPUT_POST, "url")) { echo("Input type does not exist"); } else { $url = filter_input(INPUT_POST, "url", FILTER_SANITIZE_URL); } ?> |
|
Filter Multiple Inputs desc
|
A form almost always consist of more than one input field. To avoid calling the filter_var or filter_input functions over and over, we can use the filter_var_array or the filter_input_array functions.
|
|
Filter Multiple Inputs code
|
In this example we use the filter_input_array() function to filter three GET variables. The received GET variables is a name, an age and an e-mail address:
<?php $filters = array ( "name" => array ( "filter"=>FILTER_SANITIZE_STRING ), "age" => array ( "filter"=>FILTER_VALIDATE_INT, "options"=>array ( "min_range"=>1, "max_range"=>120 ) ), "email"=> FILTER_VALIDATE_EMAIL, ); $result = filter_input_array(INPUT_GET, $filters); if (!$result["age"]) { echo("Age must be a number between 1 and 120.<br />"); } elseif(!$result["email"]) { echo("E-Mail is not valid.<br />"); } else { echo("User input is valid"); } ?> |
|
Using Filter Callback (desc)
|
It is possible to call a user defined function and use it as a filter using the FILTER_CALLBACK filter. This way, we have full control of the data filtering.
You can create your own user defined function or use an existing PHP function The function you wish to use to filter is specified the same way as an option is specified. In an associative array with the name "options" |
|
Using Filter Callback to convert "_" in user input to whitespaces (code)
|
<?php
function convertSpace($string) { return str_replace("_", " ", $string); } $string = "Peter_is_a_great_guy!"; echo filter_var($string, FILTER_CALLBACK, array("options"=>"convertSpace")); ?> Result is: Peter is a great guy! |
|
Create a Connection to a MySQL Database
|
mysql_connect(servername,username,password);
|
|
following example we store the connection in a variable ($con) for later use in the script. The "die" part will be executed if the connection fails (code)
|
<?php
$con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } // some code ?> |
|
Closing a Connection to a MySQL Database
|
connection will be closed automatically when the script ends. To close the connection before, use the mysql_close() function
<?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } // some code mysql_close($con); ?> |
|
following example creates a database called "my_db"
|
<?php
$con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } if (mysql_query("CREATE DATABASE my_db",$con)) { echo "Database created"; } else { echo "Error creating database: " . mysql_error(); } mysql_close($con); ?> |
|
The following example creates a table named "Persons", with three columns. The column names will be "FirstName", "LastName" and "Age":
|
<?php
$con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } // Create database if (mysql_query("CREATE DATABASE my_db",$con)) { echo "Database created"; } else { echo "Error creating database: " . mysql_error(); } // Create table mysql_select_db("my_db", $con); $sql = "CREATE TABLE Persons ( FirstName varchar(15), LastName varchar(15), Age int )"; // Execute query mysql_query($sql,$con); mysql_close($con); ?> |
|
how to create an ODBC connection to a MS Access Database
|
1)Open the Administrative Tools icon in your Control Panel.
2)Double-click on the Data Sources (ODBC) icon inside. 3)Choose the System DSN tab. 4)Click on Add in the System DSN tab. 5)Select the Microsoft Access Driver. Click Finish. 6)In the next screen, click Select to locate the database. 7)Give the database a Data Source Name (DSN). 8)Click OK |
|
function is used to connect to an ODBC data source
|
odbc_connect()
this function takes 4 parameter: data source name username password an optional cursor type |
|
function is used to execute an SQL statement once connected to ODBC data source
|
odbc_exec()
$conn=odbc_connect('northwind','',''); $sql="SELECT * FROM customers"; $rs=odbc_exec($conn,$sql); |
|
Retrieving Records ODBC records function and source
|
odbc_fetch_row() function is used to return records from the result-set. This function returns true if it is able to return rows, otherwise false
The function takes two parameters: the ODBC result identifier and an optional row number: odbc_fetch_row($rs) |
|
Retrieving Fields from a Record ODBC records function and source
|
odbc_result() function is used to read fields from a record. This function takes two parameters: the ODBC result identifier and a field number or name.
The code line below returns the value of the first field from the record: $compname=odbc_result($rs,1); The code line below returns the value of a field called "CompanyName": $compname=odbc_result($rs,"CompanyName"); |
|
Closing an ODBC Connection
|
odbc_close($conn);
|
|
What is XML?
|
XML is used to describe data and to focus on what data is. An XML file describes the structure of the data.
In XML, no tags are predefined. You must define your own tags. |
|
What is Expat?
|
To read and update - create and manipulate - an XML document, you will need an XML parser.
There are two basic types of XML parsers: Tree-based parser: This parser transforms an XML document into a tree structure. It analyzes the whole document, and provides access to the tree elements. e.g. the Document Object Model (DOM) Event-based parser: Views an XML document as a series of events. When a specific event occurs, it calls a function to handle it The Expat parser is an event-based parser. Event-based parsers focus on the content of the XML documents, not their structure. Because of this, event-based parsers can access data faster than tree-based parsers. |
|
Tree-based parser (def)
|
This parser transforms an XML document into a tree structure. It analyzes the whole document, and provides access to the tree elements. e.g. the Document Object Model (DOM)
|
|
Event-based parser (def)
|
Views an XML document as a series of events. When a specific event occurs, it calls a function to handle it
|
|
Look at the following XML fraction:
<from>Jani</from> An event-based parser reports the XML above as a series of three events: |
Start element: from
Start CDATA section, value: Jani Close element: from |
|
XML Expat parser installation
|
XML Expat parser functions are part of the PHP core. There is no installation needed to use these functions.
|
|
Initialize the XML parser
|
$parser=xml_parser_create();
Initializing the XML Parser We want to initialize the XML parser in PHP, define some handlers for different XML events, and then parse the XML file. |
|
W3C DOM is separated into different parts _________,
______, ____________ and different levels ______, _____, ____ |
The W3C DOM is separated into different parts (Core, XML, and HTML) and different levels (DOM Level 1/2/3):
* Core DOM - defines a standard set of objects for any structured document * XML DOM - defines a standard set of objects for XML documents * HTML DOM - defines a standard set of objects for HTML documents If you want to learn more about the XML DOM, please visit our XML DOM tutorial. |
|
Looping through XML
|
We want to initialize the XML parser, load the XML, and loop through all elements of the <note> element:
Example <?php $xmlDoc = new DOMDocument(); $xmlDoc->load("note.xml"); $x = $xmlDoc->documentElement; foreach ($x->childNodes AS $item) { print $item->nodeName . " = " . $item->nodeValue . "<br />"; } ?> The output of the code above will be: #text = to = Tove #text = from = Jani #text = heading = Reminder #text = body = Don't forget me this weekend! #text = |
|
What is SimpleXML?
|
SimpleXML is new in PHP 5. It is an easy way of getting an element's attributes and text, if you know the XML document's layout.
Compared to DOM or the Expat parser, SimpleXML just takes a few lines of code to read text data from an element. SimpleXML converts the XML document into an object |
|
SimpleXML converts the XML document into an object, like this:
|
Elements - Are converted to single attributes of the SimpleXMLElement object. When there's more than one element on one level, they're placed inside an array
Attributes - Are accessed using associative arrays, where an index corresponds to the attribute name Element Data - Text data from elements are converted to strings. If an element has more than one text node, they will be arranged in the order they are found |
|
Using SimpleXML
|
<?php
$xml = simplexml_load_file("test.xml"); echo $xml->getName() . "<br />"; foreach($xml->children() as $child) { echo $child->getName() . ": " . $child . "<br />"; } ?> The output of the code above will be: note to: Tove from: Jani heading: Reminder body: Don't forget me this weekend! |
|
AJAX (abr)
|
Asynchronous JavaScript and XML
AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page. |
|
AJAX is based on internet standards, and uses a combination of:
|
XMLHttpRequest object (to exchange data asynchronously with a server)
JavaScript/DOM (to display/interact with the information) CSS (to style the data) XML (often used as the format for transferring data) |
|
Explain basic steps that need to be taken by code when an input field is entered and hind is offered to user
|
Create an XMLHttpRequest object
Create the function to be executed when the server response is ready Send the request off to a file on the server Notice that a parameter (q) is added to the URL (with the content of the input field) |
|
AJAX can interact with
|
PHP file predefined values in array
XML file SQL/MySQL |
|
basic sin-taxis for a function to show an AJAX pulled result
|
function showRSS(str)
{ if (str.length==0) { document.getElementById("rssOutput").innerHTML=""; return; } if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("rssOutput").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","getrss.php?q="+str,true); xmlhttp.send(); } |
|
function to create an array
|
array()
array(key => value) --- <?php $a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse"); print_r($a); ?> Array ( [a] => Dog [b] => Cat [c] => Horse ) --- <?php $a=array("Dog","Cat","Horse"); print_r($a); ?> Array ( [0] => Dog [1] => Cat [2] => Horse ) |
|
function splits an array into chunks of new arrays
|
array_chunk()
array_chunk(array,size,preserve_key) --- <?php $a=array("a"=>"Cat","b"=>"Dog","c"=>"Horse","d"=>"Cow"); print_r(array_chunk($a,2)); ?> --- Array ( [0] => Array ( [0] => Cat [1] => Dog ) [1] => Array ( [0] => Horse [1] => Cow ) ) |
|
function creates an array by combining two other arrays, where the first array is the keys, and the other array is the values
|
array_combine()
array_combine(array1,array2) --- <?php $a1=array("a","b","c","d"); $a2=array("Cat","Dog","Horse","Cow"); print_r(array_combine($a1,$a2)); ?> --- Array ( [a] => Cat [b] => Dog [c] => Horse [d] => Cow ) |
|
function returns an array, where the keys are the original array's values, and the values is the number of occurrences
|
array_count_values()
array_count_values(array) --- <?php $a=array("Cat","Dog","Horse","Dog"); print_r(array_count_values($a)); ?> --- Array ( [Cat] => 1 [Dog] => 2 [Horse] => 1 ) |
|
function compares two or more arrays, and returns an array with the keys and values from the first array, only if the value is not present in any of the other arrays
|
array_diff()
array_diff(array1,array2,array3...) --- <?php $a1=array(0=>"Cat",1=>"Dog",2=>"Horse"); $a2=array(3=>"Horse",4=>"Dog",5=>"Fish"); print_r(array_diff($a1,$a2)); ?> --- Array ( [0] => Cat ) |
|
function returns an array filled with the values you describe
|
array_fill(start,number,value)
<?php $a=array_fill(2,3,"Dog"); print_r($a); ?> Array ( [2] => Dog [3] => Dog [4] => Dog ) |
|
function passes each value in the array to a user-made function, which returns either true or false, and returns an array only with the values that returned true
|
array_filter(array,function)
------------------------------------ <?php function myfunction($v) { if ($v==="Horse") { return true; } return false; } $a=array(0=>"Dog",1=>"Cat",2=>"Horse"); print_r(array_filter($a,"myfunction")); ?> |
|
function returns an array with all the original keys as values, and all original values as keys
|
array_flip() function returns an array with all the original keys as values, and all original values as keys.
<?php $a=array(0=>"Dog",1=>"Cat",2=>"Horse"); print_r(array_flip($a)); ?> |
|
function compares two or more arrays, and returns an array with the keys and values from the first array, only if the value is present in all of the other arrays
|
array_intersect() function compares two or more arrays, and returns an array with the keys and values from the first array, only if the value is present in all of the other arrays
Syntax array_intersect(array1,array2,array3...) Example <?php $a1=array(0=>"Cat",1=>"Dog",2=>"Horse"); $a2=array(3=>"Horse",4=>"Dog",5=>"Fish"); print_r(array_intersect($a1,$a2)); ?> The output of the code above will be: Array ( [1] => Dog [2] => Horse ) |
|
function compares two or more arrays, and returns an array with the keys and values from the first array, only if they are present in all of the other arrays
|
The array_intersect_assoc() function compares two or more arrays, and returns an array with the keys and values from the first array, only if they are present in all of the other arrays.
<?php $a1=array(0=>"Cat",1=>"Dog",2=>"Horse"); $a2=array(3=>"Horse",1=>"Dog",0=>"Cat"); print_r(array_intersect_assoc($a1,$a2)); ?> Array ( [0] => Cat [1] => Dog ) |
|
function checks an array for a specified key, and returns true if the key exists and false if the key does not exist.
|
array_key_exists() function checks an array for a specified key, and returns true if the key exists and false if the key does not exist.
syntax - array_key_exists(key,array) <?php $a=array("a"=>"Dog","b"=>"Cat"); if (array_key_exists("a",$a)) { echo "Key exists!"; } else { echo "Key does not exist!"; } ?> |
|
function returns an array containing the keys
|
array_keys() function returns an array containing the keys
- Syntax - <?php $a=array("a"=>"Horse","b"=>"Cat","c"=>"Dog"); print_r(array_keys($a)); ?> Result - Array ( [0]=> a [1]=>b [2]=>c) |
|
function sends each value of an array to a user-made function, and returns an array with new values, given by the user-made function
|
array_map() function sends each value of an array to a user-made function, and returns an array with new values, given by the user-made function
syntax - array_map(function,array1,array2,array3...) Example - <?php function myfunction($v) { if ($v==="Dog") { return "Fido"; } return $v; } $a=array("Horse","Dog","Cat"); print_r(array_map("myfunction",$a)); ?> Result - Array ( [0] => Horse [1] => Fido [2] => Cat ) |
|
function merges one ore more arrays into one array
|
array_merge() function merges one ore more arrays into one array
syntax - array_merge(array1,array2,array3...) example - <?php $a1=array("a"=>"Horse","b"=>"Dog"); $a2=array("c"=>"Cow","b"=>"Cat"); print_r(array_merge($a1,$a2)); ?> Result - Array ( [a] => Horse [b] => Cat [c] => Cow ) |
|
function returns a sorted array
|
You can assign one or more arrays. The function sorts the first array, and the other arrays follow, then, if two or more values are the same, it sorts the next array, and so on.
syntax - array_multisort(array1,sorting order,sorting type,array2,array3...) example - <?php $a1=array("Dog","Cat"); $a2=array("Fido","Missy"); array_multisort($a1,$a2); print_r($a1); print_r($a2); ?> result - Array ( [0] => Cat [1] => Dog ) Array ( [0] => Missy [1] => Fido ) |
|
function inserts a specified number of elements, with a specified value, to an array
|
array_pad() function inserts a specified number of elements, with a specified value, to an array
syntax - array_pad(array, size, value) example - <?php $a=array("Dog","Cat"); print_r(array_pad($a,5,0)); ?> result - Array ( [0] => Dog [1] => Cat [2] => 0 [3] => 0 [4] => 0 ) |
|
function deletes the last element of an array
|
array_pop() function deletes the last element of an array
syntax - array_pop(array) example - <?php $a=array("Dog","Cat","Horse"); array_pop($a); print_r($a); ?> result - Array ( [0] => Dog [1] => Cat ) |
|
function inserts one or more elements to the end of an array
|
array_push() function inserts one or more elements to the end of an array
syntax - array_push (array, value1, value2 ...) example - <?php $a=array("Dog","Cat"); array_push($a,"Horse","Bird"); print_r($a); ?> result - Array ( [0] => Dog [1] => Cat [2] => Horse [3] => Bird ) |
|
function sends the values in an array to a user-defined function, and returns a string.
|
The array_reduce() function sends the values in an array to a user-defined function, and returns a string.
syntax - array_reduce(array,function,initial) example - <?php function myfunction($v1,$v2) { return $v1 . "-" . $v2; } $a=array("Dog","Cat","Horse"); print_r(array_reduce($a,"myfunction")); ?> result - -Dog-Cat-Horse |
|
function returns an array in the reverse order
|
array_reverse() function returns an array in the reverse order
syntax - array_reverse(array, preserve) example - <?php $a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse"); print_r(array_reverse($a)); ?> result - Array ( [c] => Horse [b] => Cat [a] => Dog ) |
|
function search an array for a value and returns the key
|
array_search() function search an array for a value and returns the key
syntax - array_Search (value, array, strict) example - <?php $a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse"); echo array_search("Dog",$a); ?> result - a |
|
function removes the first element from an array, and returns the value of the removed element
|
array_shift() function removes the first element from an array, and returns the value of the removed element.
syntax - array_shift(array) example - <?php $a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse"); echo array_shift($a); print_r ($a); ?> result - Dog Array ( [b] => Cat [c] => Horse ) |
|
function returns selected parts of an array
|
array_slice() function returns selected parts of an array
syntax - array_slice(array,start,length,preserve) example - <?php $a=array(0=>"Dog",1=>"Cat",2=>"Horse",3=>"Bird"); print_r(array_slice($a,1,2)); ?> result - Array ( [0] => Cat [1] => Horse ) |
|
function removes selected elements from an array and replaces it with new elements. The function also returns an array with the removed elements.
|
array_splice() Function
--------------------------------- <?php $a1=array(0=>"Dog",1=>"Cat",2=>"Horse",3=>"Bird"); $a2=array(0=>"Tiger",1=>"Lion"); array_splice($a1,0,2,$a2); print_r($a1); ?> |
|
function returns the sum of all the values in the array.
|
array_sum() Function
------------------------------- <?php $a=array(0=>"5",1=>"15",2=>"25"); echo array_sum($a); ?> |
|
function compares two or more arrays, in a user-made function, and returns an array containing the elements from the first array, if the user-made function allows it. The user-made function compares array values, and returns a numeric value, a positive number (1) if the returned array should contain this element, and 0, or a negative number (-1), if not.
|
array_udiff() Function
------------------------------ <?php function myfunction($v1,$v2) { if ($v1===$v2) { return 0; } return 1; } $a1=array("a"=>"Cat","b"=>"Dog","c"=>"Horse"); $a2=array(1=>"Cat",2=>"Dog",3=>"Fish"); print_r(array_udiff($a1,$a2,"myfunction")); ?> |
|
function removes duplicate values from an array. If two or more array values are the same, the first appearance will be kept and the other will be removed.
|
array_unique() Function
---------------------------------- <?php $a=array("a"=>"Cat","b"=>"Dog","c"=>"Cat"); print_r(array_unique($a)); ?> The output of the code above will be: Array ( [a] => Cat [b] => Dog ) |
|
function inserts new elements to an array. The new array values will be inserted in the beginning of the array. The function's return value is the new number of elements in the array
|
array_unshift() Function
------------------------------------------- <?php $a=array("a"=>"Cat","b"=>"Dog"); array_unshift($a,"Horse"); print_r($a); ?> The output of the code above will be: Array ( [0] => Horse [a] => Cat [b] => Dog ) |
|
function returns an array containing all the values of an array.
|
array_values() Function
--------------------------------- <?php $a=array("a"=>"Cat","b"=>"Dog","c"=>"Horse"); print_r(array_values($a)); ?> The output of the code above will be: Array ( [0] => Cat [1] => Dog [2] => Horse ) |
|
function sorts an array by the values in reverse order. The values keep their original keys.
|
arsort() Function
----------------------- <?php $my_array = array("a" => "Dog", "b" => "Cat", "c" => "Horse"); arsort($my_array); print_r($my_array); ?> |
|
asort() Function Syntax
|
asort(array,sorttype)
----------------------------- Optional. Specifies how to sort the array values. Possible values: SORT_REGULAR - Default. Treat values as they are (don't change types) SORT_NUMERIC - Treat values numerically SORT_STRING - Treat values as strings SORT_LOCALE_STRING - Treat values as strings, based on local settings |
|
function sorts an array by the values. The values keep their original keys.
|
asort() Function
----------------------- <?php $my_array = array("a" => "Dog", "b" => "Cat", "c" => "Horse"); asort($my_array); print_r($my_array); ?> |
|
function counts the elements of an array, or the properties of an object.
|
count() Function
------------------------ <?php $people = array("Peter", "Joe", "Glenn", "Cleveland"); $result = count($people); echo $result; ?> |
|
function returns the value of the current element in an array.
|
current() Function
-------------------------- <?php $people = array("Peter", "Joe", "Glenn", "Cleveland"); echo current($people) . "<br />"; ?> The output of the code above will be: Peter |
|
function returns the current element key and value, and moves the internal pointer forward.
|
each() Function
----------------------- <?php $people = array("Peter", "Joe", "Glenn", "Cleveland"); print_r (each($people)); ?> The output of the code above will be: Array ( [1] => Peter [value] => Peter [0] => 0 [key] => 0 ) |
|
function moves the internal pointer to, and outputs, the last element in the array.
|
end() Function
--------------------- <?php $people = array("Peter", "Joe", "Glenn", "Cleveland"); echo current($people) . "<br />"; echo end($people); ?> The output of the code above will be: Peter Cleveland |
|
function searches an array for a specific value.
This function returns TRUE if the value is found in the array, or FALSE otherwise. |
in_array() Function
-------------------------- <?php $people = array("Peter", "Joe", "Glenn", "Cleveland"); if (in_array("Glenn",$people)) { echo "Match found"; } else { echo "Match not found"; } ?> |
|
function returns the element key from the current internal pointer position.
This function returns FALSE on error. |
key() Function
--------------------- <?php $people = array("Peter", "Joe", "Glenn", "Cleveland"); echo "The key from the current position is: " . key($people); ?> The output of the code above will be: The key from the current position is: 0 |
|
function sorts an array by the keys in reverse order. The values keep their original keys.
This function returns TRUE on success, or FALSE on failure. |
krsort() Function
------------------------ <?php $my_array = array("a" => "Dog", "b" => "Cat", "c" => "Horse"); krsort($my_array); print_r($my_array); ?> |
|
function sorts an array by the keys. The values keep their original keys.
This function returns TRUE on success, or FALSE on failure. |
ksort() Function
------------------------- <?php $my_array = array("a" => "Dog", "b" => "Cat", "c" => "Horse"); ksort($my_array); print_r($my_array); ?> |
|
function is used to assign values to a list of variables in one operation.
|
list() Function
-------------------- <?php $my_array = array("Dog","Cat","Horse"); list($a, $b, $c) = $my_array; echo "I have several animals, a $a, a $b and a $c."; ?> The output of the code above will be: I have several animals, a Dog, a Cat and a Horse. |
|
function moves the internal pointer to, and outputs, the previous element in the array.
This function returns the value of the previous element in the array on success, or FALSE if there are no more elements. |
prev() Function
---------------------- <?php $people = array("Peter", "Joe", "Glenn", "Cleveland"); echo current($people) . "<br />"; echo next($people) . "<br />"; echo prev($people); ?> |
|
function creates an array containing a range of elements.
This function returns an array of elements from low to high. |
range() Function
----------------------- <?php $number = range(0,5); print_r ($number); ?> |
|
function moves the internal pointer to the first element of the array.
This function returns the value of the first element in the array on success, or FALSE on failure. |
reset() function
---------------------- <?php $people = array("Peter", "Joe", "Glenn", "Cleveland"); echo current($people) . "<br />"; echo next($people) . "<br />"; echo reset($people); ?> |
|
function randomizes the order of the elements in the array.
This function assigns new keys for the elements in the array. Existing keys will be removed. This function returns TRUE on success, or FALSE on failure. |
shuffle() Function
------------------------ <?php $my_array = array("a" => "Dog", "b" => "Cat", "c" => "Horse"); shuffle($my_array); print_r($my_array); ?> |
|
function counts the elements of an array, or the properties of an object.
This function is an alias of the count() function. |
sizeof() Function
------------------------ <?php $people = array("Peter", "Joe", "Glenn", "Cleveland"); $result = sizeof($people); echo $result; ?> |
|
function sorts an array by the values.
This function assigns new keys for the elements in the array. Existing keys will be removed. This function returns TRUE on success, or FALSE on failure. |
sort() function
------------------- <?php $my_array = array("a" => "Dog", "b" => "Cat", "c" => "Horse"); sort($my_array); print_r($my_array); ?> |
|
function returns the number of days in a month of a specified year and calendar.
|
cal_days_in_month() Function
-------------------------------------------- <?php $d=cal_days_in_month(CAL_GREGORIAN,10,2005); echo("There was $d days in October 2005"); ?> The output of the code above will be: There was 31 days in October 2005 |
|
function returns the day of a week.
|
JDDayOfWeek() Function
------------------------------------- <?php $jd=cal_to_jd(CAL_GREGORIAN,date("m"),date("d"),date("Y")); echo(jddayofweek($jd,1)); ?> The output of the code above could be: Thursday |
|
function returns a month name.
|
JDMonthName() Function
------------------------------------- <?php $jd=cal_to_jd(CAL_GREGORIAN,date("m"),date("d"),date("Y")); echo(jdmonthname($jd,1)); ?> |
|
function returns true if the specified date is valid, and false otherwise.
A date is valid if: month is between 1 and 12 inclusive day is within the allowed number of days for the particular month year is between 1 and 32767 inclusive |
checkdate() Function
------------------------------ <?php var_dump(checkdate(12,31,2000)); var_dump(checkdate(2,29,2003)); var_dump(checkdate(2,29,2004)); ?> The output of the code above will be: bool(true) bool(false) bool(true) |
|
function returns the default timezone used by all date/time functions in a script.
|
date_default_timezone_get() Function
------------------------------------------ <?php echo(date_default_timezone_get()); ?> The output of the code above will be: Europe/Paris |
|
function sets the default timezone used by all date/time functions.
|
date_default_timezone_set() Function
------------------------------------------- <?php echo(date_default_timezone_set("Europe/Paris")); ?> The output of the code above will be: 1 |
|
function formats a local time/date
|
date() Function
<?php echo("Result with date():<br />"); echo(date("l") . "<br />"); ?> |
|
function returns an array that contains date and time information for a Unix timestamp.
|
getdate() Function
-------------------------- <?php $my_t=getdate(date("U")); print("$my_t[weekday], $my_t[month] $my_t[mday], $my_t[year]"); ?> Wednesday, January 25, 2006 |
|
php start tag
|
<?php
?> |
|
Most servers are set to suppress PHP errors which can leave you guessing why something isn't working and make troubleshooting code almost impossible. uckily forcing PHP to display errors is very easy.
The most basic way to accomplish this is to just add the following 2 lines to the top of your PHP code. |
error_reporting(E_ALL);
ini_set( 'display_errors','1'); You can just individually place this code in each page your debugging |