PHP IF($VARIABLE)

Standard

this construct tests to see if $variable evaluates to any “truthy” value
it can be a boolean TRUE, or a non-empty, non-NULL value, or non-zero number

list of boolean evaluations
var_dump((bool) “”);
// bool(false)

var_dump((bool) 1);
// bool(true)

var_dump((bool) -2);
// bool(true)

var_dump((bool) “foo”);
// bool(true)

var_dump((bool) 2.3e5);
// bool(true)

var_dump((bool) array(12));
// bool(true)

var_dump((bool) array());
// bool(false)

var_dump((bool) “false”);
// bool(true)

var_dump((bool) false);
// bool(false)

if($variable) is not appropriate to use when testing if a variable or array key has been initialized
if it the variable or array key does not yet exist, this would result in an E_NOTICE Undefined variable $variable

Advertisements

JS WINDOW.LOCATION

Standard

window.location object can be used to get the current page address (URL) and to redirect the browser to a new page

window.location.href
returns the href (URL) of the current page
returns the URL of the current page

document.getElementById(“demo”).innerHTML = “page location is ” + window.location.href;

// outputs
page location is https://www.w3schools.com/js/js_window_location.asp

window.location.hostname
returns the domain name of the web host
returns the name of the internet host (of the current page)

document.getElementById(“demo”).innerHTML = “page hostname is ” + window.location.hostname;

// outputs
page hostname is http://www.w3schools.com

window.location.pathname
returns the path and filename (the pathname) of the current page
document.getElementById(“demo”).innerHTML = “page path is ” + window.location.pathname;

// outputs
/js/js_window_location.asp

window.location.protocol
returns the web protocol used (http: or https:)
it is the web protocol of the page

document.getElementById(“demo”).innerHTML = “page protocol is ” + window.location.protocol;

// outputs
page protocol is https

window.location.port
returns the number of the internet host port (of the current page)

document.getElementById(“demo”).innerHTML = “port number is ” + window.location.port;

// outputs
port name is

** most browsers will not display default port numbers (80 for http and 443 for https) **

window.location.assign()
this method, window.location.assign(), loads a new document

<html>
<head>

function newDoc() {
window.location.assign(“https://www.w3schools.com&#8221;)
}

</head>
<body>

<input type=”button” value=”Load new document” onclick=”newDoc()”>

</body>
</html>

PHP MISC

Standard

dir()
returns an instance of the directory class
$dir = “.”;
$handle = opendir($dir);

// or create a directory instance from the class
$d = dir(“.”);
// accessing the properties of the directory class
echo “handle: ” . $d->handle . “<br>”;
echo “path: ” . $d->path . “<br>”;
while (($file = $d->read()) !== false){
echo “filename: ” . $file . “<br>”;
}
$d->close();

// outputs
Handle: Resource id #2
Path: /etc/php
filename: .
filename: ..
filename: ajax.gif
filename: books.xml
filename: cdcatalog.xml
filename: default.asp

## instances of directory are created by the dir() function, not by the new operator ##
Directory {
## properties ##
public string $path ;
public resource $handle ;
## methods ##
public void close ([ resource $dir_handle ] )
public string read ([ resource $dir_handle ] )
public void rewind ([ resource $dir_handle ] )
}

Directory::read
read entry from directory handle

the same is readdir(), only dir_handle defaults to $this: returns the name of the next entry in the directory and the entries are returned in the order in which they are stored by the filesystem

getcwd()
returns the current working directory
echo getcwd()
// print /home/desktop

opendir(path)
opens a directory handle, where path is the directory path to be opened
$dir = “/images/”;
// open a directory and read its contents
if (is_dir($dir)){
if ($handle = opendir($dir)){
while (($file = readdir($handle)) !== false){
echo “filename:” . $file . “<br>”;
}
closedir($handle);
}
}

// outputs
filename: dog.txt
filename: jack.txt
filename: russel.txt

returns the directory handle resource on success
false on failure, throwing an error of level E_WARNING if path is not a valid directory, or if the directory cannot be opened due to permission restrictions or filesysytem errors
hide the error output of opendir() by adding @ to the front of the function name

readdir(dir_handle)
returns an entry name (filename) from a directory handle on success
the directory handle resource previously opened with opendir() can be specified as a parameter
if this parameter is not specified, the last link opened by opendir() is assumed
returns false on failure

define()
defines a constant
define(name, value, case_insensitive)
the case_insensitive option can be setted to true or false

dirname()
return the directory name component from a path
echo dirname(“c:/demo/index.php”);
// outputs c:/demo

basename()
return the file name component from a path
basename(path, suffix)
the suffix option specifies a file extension: if the filename has this file extension, the file extension will not show

echo basename(“c:/demo/index.php”);
// outputs index.php

echo basename(“c:/demo/index.php”, “.php”);
// outputs index

BOM OBJECTS

Standard

window object
l’oggetto window rappresenta una finestra aperta in un browser.
se un documento contiene iframe, definiti da appositi tag <iframe>, il browser crea un oggetto window per il documeno HTML, e un oggetto window addizionale per ogni frame.
l’oggetto window ha varie proprietà e metodi che sono supportati dalla maggior parte dei browser, ma non c’è uno standard ufficiale che li definisce.

lista delle window object properties
windowProperties

lista dei window object methods
windowMethods
navigator object
l’oggetto navigator contiene informazioni che riguardano il browser.
navigatorObject
screen object
l’oggetto screen contiene informazioni che riguardano lo schermo dell’utente.
screenObject
history object
l’oggetto history contiene le URL visitate dall’utente (all’interno della finestra del browser): l’oggetto history fa parte dell’oggetto window, si accede a esso tramite la window.history property.
historyObject
location object

l’oggetto location contiene informazioni che riguardano l’URL corrente: anch’esso è parte dell’oggetto window e ci si può accedere tramite la window.location property.
locationObject

JS REGULAR EXPRESSIONS

Standard

a regular expression is a sequence of characters that forms a search pattern
this search pattern can be used when searching data into a text, to describe what you are searching for
a regular expression can be a single character, or a more complicated pattern: they can be used to perform all types of text search and text replace operations

syntax
/pattern/modifiers;

var patt = /stringtofind/i;

/stringtofind/i is a regular expression, where
stringtofind is a pattern (to be used in a search),
i is a modifier (modifies the search to be case-insensitive)

string methods
regular expressions are often used with the two string methods: search() and replace()
search() method uses an expression to search for a match, and returns the position of the match (counting from 0)
replace() method returns a modified string where the pattern is replaced

string search() with regular expression
// doing a case-insensitive search for “hamburger” in a string
var str = “I love hamburGer”;
var n = str.search(/hamburger/i);
// n will be 7

string search() with string
the search method will also accept a string as search argument (the string argument will be converted to a regular expression)

// using a string search for “hamburger” in a string
var str = “I love hamburger”;
var n = str.search(“hamburger”);
// n will be 7 (but the search will be case-sensitive)

string replace() with regular expression
// using a case insensitive regular expression to replace hamburger with beer in a string
var str = “i love hamburger”;
var res = str.replace(/hamburger/i, “beer”);
// outputs: I love beer

string replace() with string
// the replace() method will also accept a string as search argument
var str = “I love hamburger”;
var res = str.replace(“hamburger”, “beer”);
// outputs: I love beer

regular expressions modifier
– case-insensitive matching
– global match (find all matches rather than stopping after the first match)
m – multiline matching

regular expression patterns
brackets are used to find a range of characters
[abc] – find any of the characters between the brackets
[0-9] – find any of the digits between the brackets
(x|y) – find any of the alternatives separated with |

metacharacters are characters with a special meaning
\d – find a digit
\s – find a whitespace character
\b – find a match at the beginning or at the end of a word
\uxxxx – find the unicode character specified by the hexadecimal number xxxx

quantifiers define quantities
n+ – matches any string that contains at least one n
n* – matches any string that contains zero or more occurrences of n
n? – matches any string that contains zero or one occurrences of n

using the RegExp Object
the RegExp object is a regular expression object with predefined properties and methods

test() method is a RegExp expression method
it searches a string for a pattern, and returns true or false, depending on the result

// searching a string for the character “e”
var patt = /e/;
patt.test(“the best things in life are free”);
// outputs true since there is an “e” in the string
the two lines above can be shortened to one:
/e/.test(“the best things in life are free”);

exec() method is a RegExp expression method
it searches a string for a specified pattern, and returns the found text
if no match is found, it returns null

// searching a string for the character “e”
/e/.exec(“the best things in life are free”);
// outputs e

JS DEBUGGING

Standard

tutti i moderni browser hanno delle funzioni javascript built-in che consentono di effettuare un minimo di debugging sul codice.
queste funzioni possono essere spente o accese a seconda della necessità.

console.log()
questo metodo permette di mostrare i valori javscript nella finestra di debug.

a = 5;
b = 6;
c = a + b;
console.log(c);
// se la finestra di debug non è stata attivata, selezionare “console” nel menù di debugging di chrome o di firefox (a cui si accede con f12)

breakpoints
sempre nella finestra di debug, è possibile selezionare dei breakpoint nel codice javascript.
a ogni breakpoint, il codice smette di essere eseguito ed è possibile esaminarlo prima di continuare.
solitamente, per tornare all’esecuzione, è necessario premere il pulsante play.

debugger keyword
la parola debugger stoppa l’esecuzione del codice e chiama (se disponibile) la funzione di debugging: essa non è nient’altro che un’alternativa alla definizione dei breakpoint.
nel caso non ci sia alcuna console di debug attiva, la direttiva debugger viene ignorata.

var x = 5 * 5;
debugger;
document.getElement”no-bok”>ById(“test”).innerHTML = x;
// se la finestra di debugging è aperta, appare un messaggio che indica che il codice è in pausa

tool di debugging dei brower maggiori
– chrome: aprire la console con f12 o scegliere dal menu del browser “developer tools”, selezionando console

– firefox firebug
http://www.getfirebug.com

– internet explorer: settings> select tools> developer tools> console

PHP SESSIONS

Standard

a session is a way to store information (in variables) to be used across multiple pages
this information is not stored on the users computer like a cookie

when you work with an application, you open it, do some changes, and then you close it: this is a session
the local computer knows who you are, when you start the application and when you end
however, on the internet the web server does not know who you are or what you do, because the HTTP address doesn’t maintain state

session variables solve this problem by storing user information to be used across multiple pages (like username, favorite color, etc)
by default, session variables last until the user closes the browser and hold information about one single user, make them available to all pages in an application (if is needed a permanent storage, store data in a database)

SESSION_START()
a session is started with the session_start() function
session variables are set with the PHP global variable: $_SESSION

in the page demo_session1.php is started a new PHP session, with the setting of some session variables
<?php
// session_start() function must be the very first thing in your document, before any HTML tags
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// set session variables
$_SESSION[“favcolor”] = “orange”;
$_SESSION[“favanimal”] = “dog”;
echo “session variables are set.”;
?>

</body>
</html>

from another page, called demo_session2.php, it’s possible to access the session information we set on the first page, demo_session1.php
session variables are not passed individually to each new page, instead they are retrieved from the session opened at the beginning of each page with session_start()
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// echo session variables that were set on previous page
echo “favorite color is ” . $_SESSION[“favcolor”] . “<br>”;
echo “favorite animal is ” . $_SESSION[“favanimal”];
?>

</body>
</html>

another way to show all the session variable values for a user session is to run the following code
<?php
session_start();
?>

<!DOCTYPE html>
<html>
<body>

<?php
print_r($_SESSION);
?>

</body>
</html>

***
how does it work? how does it know it’s me?
most sessions set a user-key on the user’s computer that looks something like this: 765487cf34ert8dede5a562e4f3a7e12
when a session is opened on another page, it scans the computer for a user-key
if there is a match, it accesses that session, if not, it starts a new session
***

to change a session variable, just overwrite it:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// to change a session variable, just overwrite it
$_SESSION[“favcolor”] = “yellow”;
print_r($_SESSION);
?>

</body>
</html>
// outputs Array ( [favcolor] => yellow )

SESSION_UNSET() and SESSION_DESTROY()
to remove all global session variables and destroy the session, use session_unset() and session_destroy()
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// remove all session variables
session_unset();

// destroy the session
session_destroy();
?>

</body>
</html>