<audio>
, <video>
, and <canvas>
, although there are many others such as <article>
, <summary>
, <footer>
, and more.<?php...?>
, which can be shortened to <?...?>
but is not recommended practice.//
for a single-line comment or /*...*/
to span multiple lines.;
).$
.$variable = 1
is an assignment statement, whereas $variable == 1
is a comparison operator. Use $variable = 1
to set the value of $variable
. Use $variable == 1
to find out later in the program whether $variable
equals 1
. If you mistakenly use $variable = 1
where you meant to do a comparison, it will do two things you probably don’t want: set $variable
to 1
and return a true
value all the time, no matter what its previous value was.$current-user
would be harder to interpret if hyphens were also allowed in variable names and, in any case, would lead programs to be ambiguous.$This_Variable
is not the same as $this_variable
._
(underscore).++$j
and $j++
unless the value of $j
is being tested, assigned to another variable, or passed as a parameter to a function. In such cases, ++$j
increments $j
before the test or other operation is performed, whereas $j++
performs the operation and then increments $j
.&&
and and
are interchangeable except where precedence is important, in which case &&
has a high precedence, while and
has a low one.<<<_END..._END;
construct to create a multiline echo
or assignment. The closing tag must begin at the start of a line, and end with a semicolon followed by a new line.\'
or \"
to escape either a single or double quote.echo
and print
commands are similar in that they are both constructs, except that print
behaves like a PHP function and takes a single argument, while echo
can take multiple arguments.global
.TRUE
represents the value 1
, and FALSE
represents NULL
, which can be thought of as “nothing” and is output as the empty string.if
, switch
, and the ?:
operator.continue
statement.for
statements are more powerful than while
loops, because they support two additional parameters to control the loop handling.if
and while
statements are literal (or Boolean) and therefore trigger execution when they evaluate to TRUE
. Numeric expressions trigger execution when they evaluate to a nonzero value. String expressions trigger execution when they evaluate to a nonempty string. A NULL
value is evaluated as false and therefore does not trigger execution.include
or require
directives, or their safer variants, include_once
and require_once
.To create a new object in PHP, use the new
keyword like this:
$object = new Class;
To create a subclass, use the extends
keyword with syntax such as this:
class Subclass extends Parentclass ...
__construct
within the class and place your code there.array
keyword is that it enables you to assign several values at a time to an array without repeating the array name.each
function and the foreach...as
loop construct return elements from an array; both start at the beginning and increment a pointer to make sure the next element is returned each time; and both return FALSE
when the end of the array is reached. The difference is that the each
function returns just a single element, so it is usually wrapped in a loop. The foreach...as
construct is already a loop, executing repeatedly until the array is exhausted or you explicitly break out of the loop.count
function to count the number of elements in an array.explode
function is to extract sections from a string that are separated by an identifier, such as extracting words separated by spaces within a sentence.reset
function.%f
.To take the input string "Happy Birthday"
and output the string "**Happy"
, you could use a printf
statement such as this:
printf("%'*7.5s", "Happy Birthday");
printf
to a variable instead of to a browser, you would use sprintf
instead.To create a Unix timestamp for 7:11 a.m. on May 2nd, 2016, you could use the following command:
$timestamp = mktime(7, 11, 0, 5, 2, 2016);
w+
file access mode with fopen
to open a file in write and read mode, with the file truncated and the file pointer at the start.The PHP command for deleting the file file.txt is as follows:
unlink('file.txt');
file_get_contents
is used to read in an entire file in one go. It will also read them from across the Internet if provided with a URL.$_FILES
contains the details about uploaded files.exec
function enables the running of system commands.<hr /
>) or the standard HTML4 style (such as <hr>
). It’s entirely up to you or your company’s coding style.SHOW databases
. To see tables within a database that you are using, type SHOW tables
. (These commands are case-insensitive.)To create this new user, use the GRANT
command like this:
GRANT PRIVILEGES ON newdatabase.* TO 'newuser'@'localhost' IDENTIFIED BY 'newpassword';
DESCRIBE tablename
.FULLTEXT
index enables natural-language queries to find keywords, wherever they are in the FULLTEXT
column(s), in much the same way as using a search engine.FULLTEXT
index or using in searches. However, it does participate in a search when it is part of a larger string bounded by double quotes.SELECT DISTINCT
essentially affects only the display, choosing a single row and eliminating all the duplicates. GROUP BY
does not eliminate rows, but combines all the rows that have the same value in the column. Therefore, GROUP BY
is useful for performing an operation such as COUNT
on groups of rows. SELECT
DISTINCT
is not useful for that purpose.To return only those rows containing the word Langhorne somewhere in the column author of the table classics, use a command such as this:
SELECT * FROM classics WHERE author LIKE "%Langhorne%";
The three rules of First Normal Form are as follows:
There should be no repeating columns containing the same kind of data.
All columns should contain a single value.
There should be a primary key to uniquely identify each row.
BEGIN
or the START TRANSACTION
command. To terminate a transaction and cancel all actions, issue a ROLLBACK
command. To terminate a transaction and commit all actions, issue a COMMIT
command.EXPLAIN
command.To back up the database publications to a file called publications.sql, you would use a command such as:
mysqldump -u user -ppassword publications > publications.sql
mysqli
, call the mysqli
method, passing the hostname, username, password, and database. A connection object will be returned on success.mysqli
, ensure you have first created a connection object to a database, and call its query
method, passing the query string.mysqli
error occurs, the error
property of the connection object contains the error message. If the error was in connecting to the database, then the connect_error
property will contain the error message.mysqli
query, use the num_rows
property of the result object.mysqli
results, call the data_seek
method of the result object, passing it the row number (starting from 0); then call the fetch_array
or other retrieval method to obtain the required data.real_escape_string
method of a mysqli
connection object, passing it the string to be escaped.mysqli
methods, your programs carry the risk of running out of memory, especially on high-traffic websites. If there’s a program flow logic error in your code, it also ensures you won’t accidentally access old results.$_GET
for the GET
method and $_POST
for the POST
method.register_globals
setting was the default in versions of PHP prior to 4.2.0. It was not a good idea, because it automatically assigned submitted form-field data to PHP variables, thus opening up a security hole for potential hackers who could attempt to break into PHP code by initializing variables to values of their choice.choices[]
, instead of a regular field name. Each value is then placed into the array, whose length will be the number of elements submitted.type="hidden"
.<label>
and </label>
tags.htmlentities
function.autocomplete
attribute, which prompts the user with possible values.required
attribute to essential inputs.set_cookie
function.set_cookie
, but set its expiration date in the past.$_SERVER['PHP_AUTH_USER']
and $_SERVER['PHP_AUTH_PW']
.hash
function is a powerful security measure, because it is a one-way function that converts a string to a 32-character hexadecimal number that cannot be converted back, and is therefore almost uncrackable.hash
conversion. This makes it nearly impossible for a brute-force dictionary attack to succeed.session_start
function.<script>
and </script>
tags.<script src='filename.js'>
tag.echo
and print
commands used in PHP is the JavaScript document.write
function (or method).//
for a single-line comment or surround it with /*
and */
for a multiline comment.+
symbol.var
keyword upon first assignment.To display the URL assigned to the link ID thislink
in all main browsers, you can use the two following commands:
document.write(document.getElementById('thislink').href) document.write(thislink.href)
The commands to change to the previous page in the browser’s history array are:
history.back() history.go(-1)
To replace the current document with the main page at the oreilly.com website, you could use the following command:
document.location.href = 'http://oreilly.com'
TRUE
, true
, FALSE
, and false
, whereas only true
and false
are supported in JavaScript. Additionally, in PHP, TRUE
has a value of 1
, and FALSE
is NULL
; in JavaScript they are represented by true
and false
, which can be returned as string values.$
) to define a JavaScript variable name. JavaScript variable names can start with and contain uppercase and lowercase letters as well as underscores; names can also include digits, but not as the first character.if
, switch
, and the ?:
operator.if
and while
statements are literal or Boolean and therefore trigger execution when they evaluate to TRUE
. Numeric expressions trigger execution when they evaluate to a nonzero value. String expressions trigger execution when they evaluate to a nonempty string. A NULL
value is evaluated as false and therefore does not trigger execution.for
statements are more powerful than while
loops, because they support two additional parameters to control loop handling.with
statement takes an object as its parameter. Using it, you specify an object once; then for each statement within the with
block, that object is assumed.Count
, count
, and COUNT
are all different.arguments
array, which is a member of all functions.this
keyword to refer to the current object.this
object within the class definition.new
keyword.prototype
keyword to create a single instance, which is then passed by reference to all the objects in a class.The syntax you would use to create an associative array is key : value
, within curly braces, as in the following:
assocarray = { "forename" : "Paul", "surname" : "McCartney", "group" : "The Beatles" }
A statement to sort an array of numbers into descending numerical order would look like this:
numbers.sort(function(a, b){ return b – a })
onsubmit
attribute to the <form>
tag. Make sure that your function returns true
if the form is to be submitted, and false
otherwise.test
method./[^\w]/
, /[\W]/
, /[^a-zA-Z0-9_]/
, and so on./f[oi]x/
./\w+\W/g
.A JavaScript function using regular expressions to test whether the word fox exists in the string "The quick brown fox"
could be as follows:
document.write(/fox/.test("The quick brown fox"))
A PHP function using a regular expression to replace all occurrences of the word the in "The cow jumps over the moon"
with the word my could be as follows:
$s=preg_replace("/the/i", "my", "The cow jumps over the moon");
value
, which is placed within an <input>
tag and takes the form value="
value
"
.XMLHttpRequest
objects, because Microsoft browsers use two different methods of creating them, while all other major browsers use a third. By writing a function to test the browser in use, you can ensure that code will work on all major browsers.try...catch
construct is to set an error trap for the code inside the try
statement. If the code causes an error, the catch
section will be executed instead of a general error being issued.XMLHttpRequest
object has six properties and six methods (see Tables 17-1 and 17-2).readyState
property of an object has a value of 4
.status
will have a value of 200
.responseText
property of an XMLHttpRequest
object contains the value returned by a successful Ajax call.responseXML
property of an XMLHttpRequest
object contains a DOM tree created from the XML returned by a successful Ajax call.XMLHttpRequest
object’s onreadystatechange
property. You can also use an unnamed, inline function.XMLHTTPRequest
object’s send
method is called.GET
and POST
request are that GET
requests append the data to the URL and not as a parameter of the send
method, and POST
requests pass the data as a parameter of the send
method and require the correct form headers to be sent first.To import one style sheet into another, you use the @import
directive, like this:
@import url('styles.css');
To import a style sheet into a document, you can use the HTML <link>
tag:
<link rel='stylesheet' type='text/css' href='styles.css'>
To directly embed a style into an element, use the style
attribute, like this:
<div style='color:blue;'>
#
character (e.g., #myid
), and class names with a .
character (e.g., .myclass
)./*
and */
opening and closing comment markers.*
universal selector.Given a pair of CSS declarations with equal precedence, to make one have greater precedence over the other, you append the !important
declaration to it, like this:
p { color:#ff0000 !important; }
^=
, $=
, and *=
match the start, end, or any portion of a string, respectively.The property you use to specify the size of a background image is background-size
, like this:
background-size:800px 600px;
You can specify the radius of a border using the border-radius
property:
border-radius:20px;
To flow text over multiple columns, you use the column-count
, column-gap
, and column-rule
properties or their browser-specific variants, like this:
column-count:3; column-gap :1em; column-rule :1px solid black;
The four functions with which you can specify CSS colors are hsl
, hsla
, rgb
, and rgba
; for example:
color:rgba(0%,60%,40%,0.4);
To create a gray text shadow under some text, offset diagonally to the bottom right by 5 pixels, with a blurring of 3 pixels, you would use this declaration:
text-shadow:5px 5px 3px #888;
You can indicate that text is truncated with an ellipsis by using this declaration:
text-overflow:ellipsis;
You include a Google Web Font in a web page by first selecting it from http://google.com/fonts. Then assuming, for example, you chose Lobster, include it in a <link>
tag, like this:
<link href='http://fonts.googleapis.com/css?family=Lobster' rel='stylesheet' type='text/css'>
and also refer to the font in a CSS declaration such as this:
h1 { font-family:'Lobster', arial, serif; }
The CSS declaration you would you use to rotate an object by 90 degrees is:
transform:rotate(90deg);
To set up a transition on an object so that when any of its properties are changed the change will transition immediately in a linear fashion over the course of half a second, you would use this declaration:
transition:all .5s linear;
O
function returns an object by its ID, the S
function returns the style
property of an object, and the C
function returns an array of all objects that access a given class.You can modify a CSS attribute of an object using the setAttribute
function, like this:
myobject.setAttribute('font-size', '16pt')
You can also (usually) modify an attribute directly (using slightly modified property names where required), like this:
myobject.fontSize = '16pt'
window.innerHeight
and window.innerWidth
.onmouseover
and onmouseout
events.To create a new element, use code such as this:
elem = document.createElement('span')
To add the new element to the DOM, use code such as this:
document.body.appendChild(elem)
visibility
property to hidden
(or visible
to restore it again). To collapse an element’s dimensions to zero, set its display
property to none
(the value block
is one way to restore it).setTimeout
function, passing it the code or function name to execute and the time delay in milliseconds.setInterval
function, passing it the code or function name to execute and the time delay between repeats in milliseconds.position
property to relative
, absolute
, or fixed
. To restore it to its original place, set the property to static
.$
. Alternatively, you can use the method name jQuery
.To link to minified release 1.11.1 of jQuery from the Google CDN, you could use HTML such as this:
<script src='http://ajax.googleapis.com/ajax/libs/jquery/ 1.11.1/jquery.min.js'></script>
$
factory method accepts CSS selectors in order to build a jQuery object of matching elements.css
method, supplying just a property name. To set the property’s value, supply a property name and a value to the method.To attach a method to the element elem
’s click event to make it slowly hide, you could use code such as the following:
$('#elem').click(function() { $(this).hide('slow') } )
fixed
, relative
, or absolute
to its position
property.Methods can be run at once (or sequentially if animations) by chaining them together with periods, like this:
$('#elem').css('color', 'blue').css('background', 'yellow').slideUp('slow')
$('#elem')[0]
, or use the get
method, like this: $('#elem').get(0)
.To display the sibling element immediately preceding one with the ID of news
in bold, you could use this statement:
$('#news').prev().css('font-weight', 'bold')
You can make a jQuery Ajax Get request using the $.get
method, like this:
$.get('http://server.com/ajax.php?do=this', function(data) { alert('The server said: ' + data) } )
<canvas>
tag.<audio>
or <video>
tags.To create a canvas element in HTML, use a <canvas>
tag and specify an ID that JavaScript can use to access it, like this:
<canvas id='mycanvas'>
To give JavaScript access to a canvas element, ensure the element has been given an ID such as mycanvas
, and then use the document.getElementdById
function (or the O
function from the OSC.js file supplied on the companion website) to return an object to the element. Finally, call getContext
on the object to retrieve a 2D context to the canvas, like this:
canvas = document.getElementById('mycanvas') context = canvas.getContext('2d')
To start a canvas path, issue the beginPath
method on the context. After creating a path, you close it by issuing closePath
on the context, like this:
context.beginPath() // Path creation commands go here context.closePath()
You can extract the data from a canvas using the toDataURL
method, which can then be assigned to the src
property of an image object, like this:
image.src = canvas.toDataURL()
To create a gradient fill (either radial or linear) with more than two colors, specify all the colors required as stop colors assigned to a gradient object you have already created, and assign them each a starting point as a percent value of the complete gradient (between 0
and 1
), like this:
gradient.addColorStop(0, 'green') gradient.addColorStop(0.3, 'red') gradient.addColorStop(0,79, 'orange') gradient.addColorStop(1, 'brown')
To adjust the width of drawn lines, assign a value to the lineWidth
property of the context, like this:
context.lineWidth = 5
clip
method.bezierCurveTo
method, supplying two pairs of x and y coordinates for the attractors, followed by another pair for the end point of the curve. A curve is then created from the current drawing location to the destination.getImageData
method returns an array containing the specified pixel data, with the elements consecutively containing the red, green, blue, and alpha pixel values, so four items of data are returned per pixel.transform
method takes six arguments (or parameters), which are in order: horizontal scale, horizontal skew, vertical skew, vertical scale, horizontal translate, and vertical translate. Therefore, the arguments that apply to scaling are numbers 1 and 4 in the list.<audio>
and <video>
tags.play
and pause
methods of an audio or video element.To request geolocation data from a web browser, you call the following method, passing the names of two functions you have written for handling access or denial to the data:
navigator.geolocation.getCurrentPosition(granted, denied)
To determine whether or not a browser supports local storage, test the typeof
property of the localStorage
object, like this:
if (typeof localStorage == 'undefined') // Local storage is not available}
localStorage.clear
method.postMessage
method to send information, and by attaching to the web worker object’s onmessage
event to retrieve it.To inform a web browser that the document can be run offline as a local web app, create a file to use as a manifest; in that file, list the files required by the application, and then link to the file in the <html>
tag, like this:
<html manifest='filename.appcache'>
preventDefault
method in your ondragover
and ondrop
event handlers.To make cross-document messaging more secure, you should always supply a domain identifier when posting messages, and check for that identifier when receiving them, like this for posting:
postMessage(message, 'http://mydomain.com')
And this for receiving:
if (event.origin) != 'http://mydomain.com') // Disallow
You can also encrypt or obscure communications to discourage injection or eavesdropping.