Difference between revisions of "PHP"
m |
|||
(19 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
PHP is a server side scripting language. | PHP is a server side scripting language. | ||
My notes originate from | My notes originate from these books and [http://php.net/ PHP site]: | ||
* Build Your Own Database Driven Website Using PHP & MySQL 2nd Edition by Kevin Yank | * Build Your Own Database Driven Website Using PHP & MySQL 2nd Edition by Kevin Yank | ||
* PHP and MySQL for Dynamic Web Sites 4th Edition by Larry Ullman | * PHP and MySQL for Dynamic Web Sites 4th Edition by Larry Ullman | ||
** [http://www.larryullman.com/books/php-and-mysql-for-dynamic-web-sites-visual-quickpro-guide-4th-edition/errata/ errata page] | |||
For [[MySQL]] information. | For [[MySQL]] information. | ||
== Useful sites == | |||
A collection of sites I have found useful | |||
[http://phpmaster.com/ PHP Master] | |||
[http://techtalk.virendrachandak.com/php-isset-vs-empty-vs-is_null/ Virendra's TechTalk] discussing "PHP isset() vs empty() vs is_null()" | |||
[http://coursesweb.net/php-mysql/multidimensional-array-functions Multidimensional arrays and array functions] | |||
[https://github.com/lotsofcode Lots of Code] | |||
== Basic Syntax & Commands == | == Basic Syntax & Commands == | ||
Line 231: | Line 243: | ||
<code>$weight['julie'] = 103;</code> | <code>$weight['julie'] = 103;</code> | ||
To temporarily view array contents in web page (e.g., troubleshooting or testing) use print_r function. | |||
Example: | |||
<code>print_r($weight);</code> | |||
== Array Variables == | == Array Variables == | ||
Line 312: | Line 330: | ||
<pre> | <pre> | ||
$ | $dbc = @mysql_connect ('db_hostname', 'db_user_name', 'db_user_password'); | ||
if (!$ | if (!$dbc) { | ||
echo ( '<p>Unable to connect to the ' . | echo ( '<p>Unable to connect to the ' . | ||
Line 329: | Line 347: | ||
* exit() function causes php to stop reading the page | * exit() function causes php to stop reading the page | ||
==== Example testing connection to db ==== | |||
// Connect to database: | |||
<pre>require ('<RELATIVE PATH TO DB CONNECT FILE>');</pre> | |||
// Check db connection | |||
<pre>if (!$dbc) { | |||
die('Connect Error (' . mysqli_connect_errno() . ') ' | |||
. mysqli_connect_error()); | |||
} | |||
echo 'Success... ' . mysqli_get_host_info($dbc) . "\n";</pre> | |||
=== mysql_select_db example === | === mysql_select_db example === | ||
Line 375: | Line 408: | ||
* False is always returned if query fails. | * False is always returned if query fails. | ||
==== mysql_query debugging ==== | |||
Some examples to debug code: | |||
<pre> | |||
$r = mysqli_query ($dbc, $q); | |||
// Debugging | |||
if ($r == FALSE) { | |||
echo '<p>$r is FALSE so myqli_query failed error: ' . mysqli_error($dbc) . '</p>'; | |||
} | |||
// debugging end | |||
</pre> | |||
<pre> | <pre> | ||
Line 523: | Line 567: | ||
|} | |} | ||
=== More examples === | |||
[https://stackoverflow.com/questions/49306970/correct-input-type-for-ip-address Regex with HTML input for IPv4 and IPv6] | |||
My post: | |||
<pre>Yes, there is a way to take an IP address via HTML using input without using text type, like a type number. The options would require four input boxes, one for each octet. | |||
Since there is no HTML input type that matches IPv4 address exactly and if you want to stick to a single input field type text is relatively simple with minlength, maxlength, and pattern attributes. | |||
Bare bones HTML: | |||
<input type="text" minlength="7" maxlength="15" size="15" pattern="^(?>(\d|[1-9]\d{2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?1)$"> | |||
For security reasons ensure you always validate submitted data server side, not just client side. You can use same regex pattern. | |||
*** Update 2024/6/29 *** Due to @Southernal suggestion (thx), I shortened pattern from 73 char to 53. I took this opportunity to fix accepting two-digit octets that start with 0 (i.e., 00 to 09 fail now). | |||
*** Update 2019/3/2 *** Added three IPv6 address regex formats. | |||
Only accepts IPv6 addresses in long form: | |||
<input type="text" pattern="^([0-9a-fA-F]{4}:){7}[0-9a-fA-F]{4}$"> | |||
Accepts long and medium form IPv6 addresses (medium allows leading zeros): | |||
<input type="text" pattern="^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$"> | |||
Accepts long and medium form IPv6 addresses (medium without leading zeros): | |||
<input type="text" pattern="^(([0-9a-fA-F]{1}|[1-9a-fA-F]{1}[0-9a-fA-F]{1,3}):){7}([0-9a-fA-F]{1}|[1-9a-fA-F]{1}[0-9a-fA-F]{1,3})$"></pre> | |||
=== Regular Expression Resources === | |||
[http://www.regex101.com/ Regex 101] | |||
[http://www.regular-expressions.info/tutorial.html Regular Expression Tutorials] | |||
[http://www.mkyong.com/regular-expressions/10-java-regular-expression-examples-you-should-know/ 10 Regular Expression Examples You Should Know] | |||
== User Interaction & Forms == | == User Interaction & Forms == | ||
Line 549: | Line 629: | ||
== Control Structures == | == Control Structures == | ||
if-else statement | === if-else statement === | ||
<pre> | <pre> | ||
if ( condition ) { | if ( condition ) { | ||
Line 560: | Line 640: | ||
</pre> | </pre> | ||
while loop | === while loop === | ||
<pre> | <pre> | ||
while ( conditions ) { | while ( conditions ) { | ||
Line 569: | Line 649: | ||
</pre> | </pre> | ||
for loop | === for loop === | ||
<pre> | <pre> | ||
Line 578: | Line 658: | ||
} | } | ||
</pre> | </pre> | ||
Example:<pre> | |||
for ($i = 0; $i < 30; $i++) { | |||
echo 'Iteration ' . $i; | |||
}</pre> | |||
== Operators == | == Operators == | ||
Line 634: | Line 719: | ||
| <code>exprTrue ?: exprFalse</code> | | <code>exprTrue ?: exprFalse</code> | ||
|} | |} | ||
==== Useful URLs ==== | |||
[http://davidwalsh.name/php-ternary-examples Ternary examples] | |||
=== Arithmetic Operators === | === Arithmetic Operators === | ||
Line 662: | Line 751: | ||
| Decrement | | Decrement | ||
|} | |} | ||
== PHPMailer == | |||
A useful [https://code.google.com/a/apache-extras.org/p/phpmailer/wiki/UsefulTutorial PHPMailer tutorial] that describes how to use PHPMailer and explains the use of the class functions by Tom Klingenberg. | |||
Another [http://wiki.dreamhost.com/PHPMailer PHPMailer tutorial] on Dreamhost wiki. | |||
== Troubleshooting Tips == | |||
=== Web resources === | |||
[https://3v4l.org/ 3v4l.org] (leetspeak for eval) is an online shell that allows you to run your code on my server. | |||
=== Print contents of an array === | |||
<nowiki>echo '<pre>';</nowiki><br /> | |||
<nowiki>print_r($arrayVar);</nowiki><br /> | |||
<nowiki>echo '</pre><br />';</nowiki> | |||
or | |||
var_dump($arrayVar); |
Latest revision as of 12:32, 3 July 2024
PHP is a server side scripting language.
My notes originate from these books and PHP site:
- Build Your Own Database Driven Website Using PHP & MySQL 2nd Edition by Kevin Yank
- PHP and MySQL for Dynamic Web Sites 4th Edition by Larry Ullman
For MySQL information.
Useful sites
A collection of sites I have found useful
Virendra's TechTalk discussing "PHP isset() vs empty() vs is_null()"
Multidimensional arrays and array functions
Basic Syntax & Commands
PHP statements are always terminated with semicolon (;).
Single quotes are used to mark start and end of text (' ')
All variable names in PHP start with dollar sign ($).
PHP is a loosely typed language. Variables may contain any type of data.
Example:
$variable_name = "Semper Fidelis";
Equal sign is called the assignment operator since it assigns values to variables.
Three ways to create comments. None of these are viewable to users via web browser.
//
/* */
#
arithmetic operators enable you to add, subtract, multiply, & divide.
Concatenation
The concatenation operator, the period "." allows you to add strings of text.
Example:
$variable_name = "Hello" . " there" . " world!"; Assigns value of "Hello there world!" without quotes.
Examples:
variable | comment |
---|---|
$var1 = 'PHP'; | Assigns value of "PHP" to var1 |
$var2 = 5; | Assigns value of 5 to $var2 |
$var3 = $var2 + 1; | Assigns value of 6 to $var3 |
$var2 = $var1; | Assigns value of "PHP" to $var2 |
echo($var1); | Outputs "PHP" |
echo($var2); | Outputs "PHP" |
echo($var3); | Outputs 6 |
echo($var1 . ' rules!'); | Outputs "PHP rules!" |
echo("var1 rules!"); | Outputs "PHP rules!" |
echo('var1 rules!'); | Outputs '$var1 rules!' |
\ | Escape character. Tells PHP to treat next character as text. |
NOTE: Double quotes around text enables the variable name to be inserted & value is displayed. This is called variable interpolation. Single quotes will not interpolate the variable name.
Some of PHP Built-In Functions
echo( "add_text" );
passes a string
Variable interpolation = process of converting variable names to their values
Example: $variable1 = 'PHP4'; // assigns variable1 the value "PHP4" echo("$variable1 rocks!"); // output "PHP4 rocks!" echo('$variable1 rocks!"); // output '$variable1 rocks!'
Arrays: $variable = array('string1','string2',integer);
Integer indexes start from 0 and used to reference contents of array.
Examples:
echo($variable[0]); // output "string1"
echo($variable[1]); // output "string2"
echo($variable[2]); // output "integer"
$variable[3] = 95; // assigns 95 to 4th index (n-1)
$variable[0] = 'string0'; // assigns string0 to index 0.
$variable[] = 55; // assigns 55 to end of array
Associative array:
Use a string as the index. Associate the value with index.
$phone['Joe'] = '555-1212';
$phone['Mike'] = '555-1313';
Example: echo('Mikes phone number is ' . $phone['Mike']);
Predefined Variables
variable | comment |
---|---|
$_GET | is an associative array that PHP will automatically create so values
passed through a URL query string can be accessed. |
$_SERVER | is an array variable that contains information provided by the users
web browser |
Examples of using predefined variables
Example $_SERVER use | comment |
---|---|
$_SERVER['PHP_SELF'] | Identifies the name of script being run. You can use to set browser to reference itself. |
$_SERVER['HTTP_USER_AGENT'] | Identifies web browser and operating system accessing script |
$_SERVER['REMOTE_ADDR'] | Identifies the IP address of the computer accessing script |
urlencode(); will convert special characters within input sting to special codes in order to appear query string
isset(); outputs a true value if variable provided has been assigned a value
exit(); causes PHP to stop reading contents
die(); acts like echo(); immediately followed by exit();
Back
Constants
Constants are a specific data type in PHP that retain their original value throughout the execution of a script.
To create a constant use define() function. Example syntax:
define ('CONSTANT_NAME', 'value');
Constants require special echo syntax for printing.
Constructs
Arrays
A special variable that contains multiple values.
Simple format:
$array_name = array('test1', 'test2', 69);
To retrieve a value stored in an array you need the index.
Generally, arrays use incrementing integers that start with zero as their indices. Indices act as pointers to precisely locate a value in an array.
Expanding on simple format:
code | comment |
---|---|
echo($array_name[0]); | Outputs 'test1' |
echo($array_name[1]); | Outputs 'test2' |
echo($array_name[2]); | Outputs 69 |
$array_name[1] = 'wiki1'; | Assign a new value |
$array_name[3] = 'wiki2'; | Create a new element |
$array_name[] = 'transformers'; | Add element to end of array. |
echo($array_name[4]); | Outputs "transformers" |
Arrays can use strings for indices. This is called an associative array because we can associate values with meaningful indices.
Example:
$weight['robert'] = 225;
$weight['gene'] = 180;
$weight['julie'] = 103;
To temporarily view array contents in web page (e.g., troubleshooting or testing) use print_r function.
Example:
print_r($weight);
Array Variables
Array variables useful to HTML
Array variable | comment |
---|---|
$_GET | |
$_POST | |
$_REQUEST | |
$_SERVER | |
$_FILES | Using HTML to upload files automatically creates this PHP array. Information about the uploaded files is in the $_FILES array. |
blah | blah |
Functions
Functions are good for your health.
function syntax | description |
---|---|
echo
|
outputs data to browser |
urlencode
|
takes any special characters in a string (like spaces) & converts them into special codes to appear in php query strings |
mysql_connect
|
Enables connection to MySQL database, returns a number that identifies the connection that has been established |
mysql_select_db
|
Selects database table that PHP will use. |
mysql_query
|
Enables PHP to send MySQL queries to MySQL db |
exit( );
|
Commands PHP to stop reading page. |
mysql_affected_rows
|
Returns number of rows affected for DELETE, INSERT, and UPDATE queries. MySQL tracks the number of rows that were affected. |
isset
|
returns a value of true if the identified variable has a value |
mysql_fetch_array
|
Accepts a result as a parameter and returns the next row in the result set as an array. No row returns a false. |
CURDATE()
|
returns current date |
split
|
takes a regular expression string of text and breaks it into an array based on char matches |
spliti
|
same as split except ignores case
|
blah | blah |
mysql_connect example
Example code:
$dbc = @mysql_connect ('db_hostname', 'db_user_name', 'db_user_password'); if (!$dbc) { echo ( '<p>Unable to connect to the ' . 'database server at this time.</p>' ); exit (); }
- The '@' symbol tells the function to fail silently which enables the coder to display your own message.
- The '!' symbol flips the $dbcnx value. A returned number for $dbcnx is true (your code successfully connected to MySQL db. !$dbcnx means a successful db connection results in false and the
if
statement would not execute. !$dbcnx means a failed db connection results in true and theif
statement would execute (print the custom error message).
- exit() function causes php to stop reading the page
Example testing connection to db
// Connect to database:
require ('<RELATIVE PATH TO DB CONNECT FILE>');
// Check db connection
if (!$dbc) { die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error()); } echo 'Success... ' . mysqli_get_host_info($dbc) . "\n";
mysql_select_db example
After your code successfully connects to the MySQL db you must tell PHP which db table to use.
Example basic code:
mysql_select_db ('db_name', $dbcnx );
- The function contains the db identifier $dbcnx. This parameter is optional but I will use it for completeness. The function will default to the last connection opened.
- Function returns true when it's successful and false if an error occurs.
Example basic code with error handling:
if (! @mysql_select_db('db_name', $dbcnx) ) { die ( '<p>Unable to locate the db_name ' . 'database at this time.</p>' ); }
die
function works likeecho
except the script exits after- Executing
die
is equivalent toecho
followed byexit
mysql_query example
Example code:
mysql_query ( query, connection_id ) ;
query
is a string that contains the SQL command we want to executeconnection_id
is optional parameter- Returns true (success) or false (failure) for most SQL queries. SELECT queries view data in db so it requires more than true or false.
- With SELECT query mysql_query returns a number that identifies a result set which contains a list of all the rows (entries) returned from the query.
- False is always returned if query fails.
mysql_query debugging
Some examples to debug code:
$r = mysqli_query ($dbc, $q); // Debugging if ($r == FALSE) { echo '<p>$r is FALSE so myqli_query failed error: ' . mysqli_error($dbc) . '</p>'; } // debugging end
$result = @mysql_query ('SELECT column_name0, column_name1, ... FROM table_name'); if ( !$result ) { die ('<p>Error performing query: ' . mysql_error() . '</p>'); }
File Functions
Functions to manipulate files
function syntax | description |
---|---|
fopen
|
opens file for modification |
fclose
|
closes file |
fread
|
read data from file |
fwrite
|
writes data from a PHP variable into a file |
copy
|
copy a file |
Number Functions
function syntax | description |
---|---|
round() | Rounds a decimal to nearest integer. Specify the number of decimals to round by using format round($number, 3) |
number_format() | Converts number into commonly written version. Specify the number of decimals to round by using format number_format($number, 2) |
Regular Expressions
A regular expression is a string of text that contains special codes. Enables use of a few PHP functions to search and manipulate other strings of text.
ereg - searches text for string match & is case sensitive.
eregi - like ereg except is not case sensitive.
$text = 'Be nice and respectful.'; if (ereg('nice', $text)){ echo( '$text contains the string "nice".'); } else { echo( '$text does not contain the string "nice".'); }
ereg_replace - same as ereg plus it replaces every match of the regular expression with another string
eregi_replace - same except is not case sensitive.
$new_string = ereg_replace(regexp, replacewith, old_string);
special code | comment |
---|---|
A caret " ^ " | Marks start of text. |
A dollar sign " $ " | Marks end of text. |
Backslash " \ " | Prefix with a backslash to remove special meaning of a character. |
Square brackets " [ ] " | Matches any string with any character within brackets. |
Question mark " ? " | Trailing char is optional |
Addition sign " + " | one or more of the previous char |
Asterisk " * " | zero or more of the previous char |
Period " . " | Matches any string of one or more char with no line breaks. |
Parentheses " ( ) " | May be used to group string char together to apply ?, +, or * to them as a whole. |
Examples:
Example | Result |
---|---|
[6789] | Matches 6, 7, 8, 9, or any text with those characters. |
[6-9] | Same as [6789] |
^[0-9]$ | Matches any single number |
^[a-z]$ | Matches any single lower case letter |
[0-9a-zA-Z] | Matches any string with a letter or number |
^[a-zA-Z]+$ | Matches any string of one ore more letters. |
bana?na | Matches "banana" and "banna", but not "banaana". |
bana+na | Matches "banana" and "banaana", but not "banna". |
bana*na | Matches "banna", "banana", and "banaaana". |
ba(na)+na | Matches "banana" and "banananana", but not "bana" or "banaana". |
More examples
Regex with HTML input for IPv4 and IPv6
My post:
Yes, there is a way to take an IP address via HTML using input without using text type, like a type number. The options would require four input boxes, one for each octet. Since there is no HTML input type that matches IPv4 address exactly and if you want to stick to a single input field type text is relatively simple with minlength, maxlength, and pattern attributes. Bare bones HTML: <input type="text" minlength="7" maxlength="15" size="15" pattern="^(?>(\d|[1-9]\d{2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?1)$"> For security reasons ensure you always validate submitted data server side, not just client side. You can use same regex pattern. *** Update 2024/6/29 *** Due to @Southernal suggestion (thx), I shortened pattern from 73 char to 53. I took this opportunity to fix accepting two-digit octets that start with 0 (i.e., 00 to 09 fail now). *** Update 2019/3/2 *** Added three IPv6 address regex formats. Only accepts IPv6 addresses in long form: <input type="text" pattern="^([0-9a-fA-F]{4}:){7}[0-9a-fA-F]{4}$"> Accepts long and medium form IPv6 addresses (medium allows leading zeros): <input type="text" pattern="^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$"> Accepts long and medium form IPv6 addresses (medium without leading zeros): <input type="text" pattern="^(([0-9a-fA-F]{1}|[1-9a-fA-F]{1}[0-9a-fA-F]{1,3}):){7}([0-9a-fA-F]{1}|[1-9a-fA-F]{1}[0-9a-fA-F]{1,3})$">
Regular Expression Resources
10 Regular Expression Examples You Should Know
User Interaction & Forms
Formats, tips, and suggestions for user interaction & forms.
Variables can be separated in s query string by an ampersand (&). You may use the ampersand multiple times.
Web pages that can decide whether to display more than one pages is a multipurpose page.
Sample multipurpose page in the HTML body tags:
<?php if ( condition ) { ?> HTML content to display if condition is true <?php } else { ?> HTML content to display if condition is false <?php } ?>
Control Structures
if-else statement
if ( condition ) { executed if condition is true } else { executed if condition false
while loop
while ( conditions ) { statements execute if true, then repeat, until false }
for loop
for ( initialize; condition; update ) { statement(s) to execute repeatedly while condition is true }
Example:
for ($i = 0; $i < 30; $i++) { echo 'Iteration ' . $i; }
Operators
operator | meaning | structure |
---|---|---|
and or && | compares two conditions both must be true | |
or or || | compares two and either must be true | |
! | negation operator or not operator, reverses a returned value from true to false or vice versa | |
== | equal-to operator | |
!= | not equal | |
< | less than | |
> | greater than | |
<= | less than or equal | |
>= | greater than or equal | |
.= | String concatenation operator - adds a new string on the end of another string | |
? | Ternary operator evaluates to exprTrue if expr1 evaluates to TRUE & exprFalse if FALSE. | expr1 ? exprTrue : exprFalse
|
? | PHP version 5.3+ Ternary operator returns exprTrue if exprTrue evaluates to TRUE, & exprFalse otherwise. | exprTrue ?: exprFalse
|
Useful URLs
Arithmetic Operators
operator | meaning |
---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
% | Modulus |
++ | Increment |
-- | Decrement |
PHPMailer
A useful PHPMailer tutorial that describes how to use PHPMailer and explains the use of the class functions by Tom Klingenberg.
Another PHPMailer tutorial on Dreamhost wiki.
Troubleshooting Tips
Web resources
3v4l.org (leetspeak for eval) is an online shell that allows you to run your code on my server.
Print contents of an array
echo '<pre>';
print_r($arrayVar);
echo '</pre><br />';
or
var_dump($arrayVar);