TO ACCESS the LOCAL SERVER: IN THE BROWSER TYPE localhost - this is connected to the htdocs folder which is the root folder of the local server on your computer Tag: Note: you can write html/css/scripts in php files and it will function properly. Important function: phpinfo(); //this can be called in a php pagefile and it will show all settings and configuration for php. SETTINGS TO CHECK IN PHPINFO() display found in php.ini file: DISPLAY_ERRORS: For debugging: in php.ini file, make sure that display_errors is on for debugging. OUTPUT BUFFERING: -Make sure output_buffering is set to a value and is on (value could be 4096). You need to turn this on on pages that use the header() function to redirect to another page for the function to work. Turn it on by calling ob_start(); at the very first line of the page: header("Location: somepage.php"); //now this will work with ob_start() called at the top. ----------------- INSTALLING A SERVER: Note: for the future, consider doing a custom installation of Apache-PHP-MySQL (look up how to do this), which is much better to manage. If something breaks on Xampp or wamp, then you will have to wait for them to fix it. It also makes updating PHP much easier and quicker. Use XAMPP. can download for windows mac or linux. To access localhost and databases etc. in the browser, type: localhost/phpmyadmin To access the index of the local server, in the broswer just type localhost Note: the starting page can be index.php or index.html - the server will recognize both as the starting page. ------------------------- VARIABLES: Use the $ at the beginning. keyword var is not needed. Syntax: $variableName = variableValue; $string1 = 'hello'; $string2 = 'world'; -Use the dot separator to concatonate (instead of + like in JS): Ex: echo string1.' '.string2; -Will print hello world. QUOTATION MARKS NOTE: it is slightly faster to use single quote marks over double quote marks when possible. good article from stackoverflow: https://stackoverflow.com/questions/3446216/what-is-the-difference-between-single-quoted-and-double-quoted-strings-in-php Note: Double quotes function different than single quotes - lines inside double quotes can include variables that will parse in double quotes.Variables will not parse in single quotes and php views it as a literal string. Single quotes print out exactly what you type in them verbatim (no parsing of variable, html tags still work though). ACCESSING GLOBAL VARIABLES INSIDE FUNCTION: -The global keyword is used to access a global variable from within a function. To do this, use the global keyword before the variables (inside the function): -declare the variables as global to access them with global keyword - function myTest() { global $x, $y; $y = $x + $y; } STATIC VARIABLES: When a function runs, it deletes the local variables. the static keyword prevents this, for repeated use of the variable in the function; each time the function is called, that variable will still have the information it contained from the last time the function was called. Note: The variable is still local to the function: "; myTest(); echo "
"; myTest(); ?> (This prints 0, 1, 2 on the screen) --- CONSTANTS (Variables) Constants are like variables except that once they are defined they cannot be changed or undefined. Unlike variables, constants are automatically global across the entire script. constances can be used inside a function, even if they are defined outside the function: -To create a constant, use the define() function. Synatx: define(name, value, case-insensitive) Note: case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false. example below creates a constant with a case-sensitive name: example below creates a constant with a case-insensitive name: Note: you don't use a $ sign in front of constant variable names. ---------- Casting Variables: change and convert the variable value to a different type. Syntax: $varName = (conversionKeyword) valueOrVariable; Ex: $float = 3.14; $floatConvert = (int) $float; echo $floatConvert; -this prints out 3 (converted from the float to whole integer) instead of the original float value. ------------ OBJECTS in PHP: In PHP, an object must be explicitly declared. First we must declare a class of object. For this, we use the class keyword. A class is a structure that can contain properties and methods: model = "VW"; } } // create an object $herbie = new Car(); // show object properties echo $herbie->model; ?> ------ String methods: PHP strlen("string or variable goes here") function returns the length of a string. (1 based) PHP str_word_count("string goes here") function counts the number of words in a string. PHP strrev() function reverses a string PHP strpos() function searches for a specific text within a string. If a match is found, the function returns the character position of the first match. If no match is found, it will return FALSE. PHP str_replace("wordToReplace", "wordTo Insert", "originaTextString") function replaces some characters with some other characters in a string: ---------------- Comparison operators: xor: $x xor $y //True if either $x or $y is true, but not both or (||) $x || $y //true if either x, y, or both are true <> (same as !=) - $x <> $y //returns true if x is not equal to y. Arithmetic Operators - same as JS, but ** is exponential. 5**2 is 5 to the power of 2 (25). ---------------- SWITCH STATEMENTS: Executes a line of code from a set if the value of the switch condition is true and matches the case value: switch (variable to check the value of) { case possibleValueOfVariable: code to be executed if n=the value specified after case; //note:for integers don't use quotes, for strings, use quotes break; case label2: code to be executed if n=label2; break; case label3: code to be executed if n=label3; break; ... default: code to be executed if n is different from all labels or the value of the variable to check is not matched in any of the cases; } //note: no break is needed after default line. Ex: ------------------------------- LOOPS: 4 types: 1)while - executes code while a condition is true 2) do while - executes a code at least one initial time, and repeats as long as the condition is true 3) for - used to execute a code a specific number of times 4) foreach loop: used to loop through elements in an array and execute code on each key. WHILE - loops through a block of code as long as the specified condition is true while (condition is true) { code to be executed; } Ex: "; $x++; } ?> DO WHILE - loops through a block of code once, and then repeats the loop as long as the specified condition is true. *** in a do while loop the condition is tested AFTER executing the statements within the loop. This means that the do while loop would execute its statements at least once, even if the condition is false the first time. Syntax: do { code to be executed; } while (condition is true); Ex: "; $x++; } while ($x <= 5); ?> FOR - loops through a block of code a specified number of times ( for loop is used when you know in advance how many times the script should run.) FOREACH - loops through a block of code for each element in an array (works only on arrays, and is used to loop through each key/value pair in an array.). Syntax: foreach ($array as $value) { code to be executed; } Example: "35", "Ben"=>"37", "Joe"=>"43"); foreach($age as $x => $x_value) { echo "Key=" . $x . ", Value=" . $x_value; echo "
"; } ?> The condition selects an array and then assigns a variable name to each index element of the array (in this case $value). (think of it as: "for each element in the array in the parameter, assign that element 'as' the variable name(s) inputed in the parameter after 'as'). Ex: "; } ?> --------------- FUNCTIONS: **Make sure the function just does one thing and not a bunch of different things. The idea is to be able to use it throughout your website in multiple contexts instead of just in one place. The purpose of the function should be to prevent the need to write something over and over again. Function Default Values: Syntax: functionName($variable = defaultValue){ code to execute;} example shows how to use a default parameter. If we call the function setHeight() without arguments it takes the default value as argument: Example: "; } setHeight(350); //this replaces the default value with the input 350 setHeight(); // will use the default value of 50 and return 50. setHeight(135); setHeight(80); ?> ----------------- ARRAYS: In PHP, there are three types of arrays: Indexed arrays - Arrays with a numeric index Associative arrays - Arrays with named keys Multidimensional arrays - Arrays containing one or more arrays Syntax to create an array in PHP: $varName = array("item1","item2","item3"); to access the elements in the array, use syntax: $arrayName['indexNumber']; i.e. echo $cars['0']; (Definition: Key = the array element name.) The count() function is used to return the length (the number of elements) of an array: Syntax: count($arrayName); Use this function to loop through array elements in lieu of a length property (like in javascript), by assigning a variable to the count function and calling it in a for loop: "; } ?> ----------------- Array Sorting: PHP - Sort Functions For Arrays: sort($arrayName); - sort arrays in ascending order rsort($arrayName); - sort arrays in descending order asort($arrayName); - sort associative arrays in ascending order, according to the value ksort($arrayName); - sort associative arrays in ascending order, according to the key arsort($arrayName); - sort associative arrays in descending order, according to the value krsort($arrayName); - sort associative arrays in descending order, according to the key ------------------------------- SUPERGLOBAL VARIABLES: https://www.w3schools.com/php/php_superglobals.asp Superglobals are variable arrays containing built in elements/values. Syntax: commandKeyWord $_superGlobalVariable['element']; built-in variables that are always available in all scopes. PHP superglobal variables are: $GLOBALS - used to access global variables from anywhere in the PHP script (also from within functions or methods). PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable. $_SERVER - holds information about headers, paths, and script locations. see https://www.w3schools.com/php/php_superglobals.asp for list of information to access with this superglobal Ex: echo $_SERVER['PHP_SELF']; $_REQUEST - used to collect data after submitting an HTML form. $_POST - method of sending data to a server (more secure) $_GET - another method of sending data to a server (less secure) $_FILES $_ENV $_COOKIE $_SESSION --------------- ------------ FORMS: Used to receive user input data. The data inputed by the user has a name attribute attached to it used for pulling it. The inputed data is assigned in an array to the superglobal variable $_POST or $_GET depending on the method attribute value used in the input tags. You can access the data index in the superglobals by assigning a variable to the data name id. 2 main attributes to form tag: 1)action attribute sends the data to the specified location (url, file, etc.). Note: use the echo keyword to print a superglobal variable to the action path (i.e.
" -- note that this is insecure - to make it secure add the htmlspecialchars function: "> -this converts scripting hacks to html and renders them harmless. Note: action = "" is usually used in case the file name is changed later on (it refers to data being sent to the current page). 2)method attribute specifies the method of sending (usually "get" or "post". Ex: Name:
E-mail:
-This sends the user input values to the url/file welcome.php for printing or further processing/use there. The welcome.php code would be: Welcome
Your email address is: --------------------- GET AND POST METHODS IN FORMS: ***USE POST METHOD FOR SECURE DATA TRANSFER (Get method puts data in the url which is visible). GET: variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases. Use Get for sending nonsensitive data. *** GET should NEVER be used for sending passwords or other sensitive information! Developers prefer POST for sending form data. NOTE ON $_GET: -All of the information seen in the link after the page file name is stored in the $_GET superglobal in an array when used with proper syntax (i.e. index.php?keyname=value -->this stores a key called keyname with a value of value in the $_GET superglobal assoc. array). -like $_POST, this holds an array of data; the index key can be set with ? followed by a keyname and = to set a value (i.e. ?id=1 or ?searchresults=5found, etc.) -additional array index keys can be added to it by using & (i.e. ?id=1&searchresults=5, etc.) The $_GET superglobal with then hold: $_GET ['id=>1', 'searchresults=>5'] -This information is stored and displayed in the URL. Note that if the URL contains the syntax above (?keyname=value&keyname=value, etc.), then the $_GET superglobal will be set with those values. (using if(isset()) will return true. ------------------- (Lecture 61-62 in Edwin Diaz PHP/CMS Udemy Course) COOKIES: -A cookie is stored inside the browser and are used to store data values about a user who visits the site so that when they visit the site again, they will be recognized and page data can be tailored to the user. -Sites can store cookies in your browser which expire after a certain amount of time specified or by a data specified. -Cookies can be viewed or removed in the settings of the browser by the user. ------------ HOW TO SET A COOKIE: Note: you can set multiple cookies when user visits site. -Use a built-in function called setcookie();\ Takes 3 parameters - (name, value, expiration) -the information for the user is saved in a superglobal called $_COOKIE in an associative array. To Create and set cookies: -The following code sets a cookie in user browser when the user visits the page that the code is on. (set variables to the parameters and set the cookie with setcookie()): //Now you can do things with the saved variables ----- HOW TO GET VALUES STORED IN COOKIES: $_COOKIE holds the values as an associative array. -Check if the cookie is set with information from the user -Check the value of the cookie to match with the revisiting user - Ex: if(isset($_COOKIE["SomeName"])) { $someUserValue = $_COOKIE["userName"]; ***//$someUser stores the value data of the cookie!!! } else { $someUser = ""; //stops script if no value is present and set. } -------------- (lecture 64 from Edwin Diaz PHP/CMS Udemy Course) SESSIONS: -A session stores a cookie on the user's browser that has a reference to data stored on the server. -A lot more information can be stored from a session vs. a cookie since the information is stored on the server and not just in the browser (like a cookie). -Used for carrying values to different pages that are personalized for the user. TO START AND USE A SESSION: -Start a session with session_start() builtin function. -this creates and sets a cookie to the filepage it is called in that has a reference to a session (a file on the server) -- this can be seen under settings in the cookie under the 'contents' label. **Make sure that session_start(); is at the top of the page in php code on every page you are using session values! Do it every time you want to get or set any session information. Data stored in the $_SESSION array will only be available after the session is started. -Now, when the user goes to a different page on the website that has the session started (with session_start();) you can access the $_SESSION superglobal with the stored values from the cookie referencing the server. then in the of the page: if(isset($_SESSION["greeting"])) { echo $_SESSION["greeting"]; //this echoes the value "Hello Visitor!" stored in $_SESSION above. } else { $someUser = ""; //stops script if no value is present and set. } ----------------------------------------- ----------------- FORM SECURITY AND SANITIZATION: **ALWAYS USE POST METHOD FOR SECURE SENDING OF SENSITIVE DATA 1. use the htmlspecialchars() function when referencing $_SERVER[PHP_SELF] Superglobal in the action attribute in the form tag. use in action attribute for example, using post method- ex:
"> 2. Strip unnecessary characters (extra space, tab, newline) from the user input data (with the PHP trim() function) 3. Remove backslashes (\) from the user input data (with the PHP stripslashes() function) Create a function that tests the user input data by assigning empty values to userdata variables, and then making an if statement to test if the request method on the form is "post", followed by assigning user input variables to the created function that returns the value passed into the parameter after it is modified with the three security measure functions listed. Example: ---------------------------------- FORM VALIDATION: Note: you don't sanitize when data is input - you sanitize when it's used. E.g. as late as possible. That will give you the best level of security. you limit the attack surface. If you sanitize early (when input), you have to be certain that there are no other holes in the application where bad data could enter through. Whereas if you do it late, then your output function doesn't have to "trust" that it is given safe data - it simply assumes that everything is unsafe Validating username and name info: from https://www.dreamhost.com/blog/php-security-user-validation-sanitization/ -Use strip_tags() to remove any html or php tags entered, and trim() to remove whitespace before or after the entered string (not in between). $username = $_POST['username’]; $username = strip_tags(trim($username)); ---- YOU CAN LIMIT THE MIN MAX length of user input (i.e. username for ex.) To check the length of a user input: (under the if(isset($_POST)) code:) $min = 5; //set min and max lengths to variables for ease $max = 10; if(strlen($username) < $min) { echo "Username is too short!"; } can also use > to check if value is longer than a maximum value. ---------- Validating User input length: *checking the length of variables is important. Without checking variables, a user could cause buffer overflow issues. ------------- htmlentities(): ***If you embed strings within HTML markup, you must escape it with htmlspecialchars. This means that every single echo or print statement should use htmlspecialchars. Note: if you want to allow the user to enter a link or html tag, then user htmlentities() on the user input to encode the tags inserted into the database. Ex: if ( isset( $_POST[ ‘comment’ ] ) ) $comment = htmlentities ( trim ( $_POST[ ‘comment’ ] ) , ENT_NOQUOTES ); ------ Vaidating if username exists: $usernames = Array ($usersindb); Ex: -make an array and use if(!in_array($usernames)) { echo "user not found"; } Then you can check if the username matches one in the array (holds users in database): if (in_array($usernames)) { echo "Welcome! you are logged in!"; } ------ For regular expressions in general, and in PHP, you may give a look to: regular-expressions.info/tutorial.html and regular-expressions.info/php.html this site helped me a lot. --------- Good way to validate emails using filter_var() - email validation - https://stackoverflow.com/questions/12026842/how-to-validate-an-email-address-in-php/12026863#12026863 Note: It might be wise to trim or sanitize (FILTER_SANITIZE_EMAIL) your email variable before validating to remove spaces: filter_var(trim($email), FILTER_VALIDATE_EMAIL) List of available Functions/methods for Validating user input (put these inside the parameter of a filter function, i.e. filter_var(variableName, filterFunctionMethod); Ex: filter_var($email, filter_validate_email); filter_validate_boolean filter_validate_email "" "" _float "" "" _int "" "" _ip "" "" _regexp "" "" _url Sanitization functions (cleans up unnecessary characters): filter_sanitize_email "" "" _encoded "" "" _number_float "" "" _number_int "" "" _spcial_chars "" "" _string "" "" _url ----------------------------------- PHP - Required Fields 1) in addition to the field name variables, create variables to hold error messages for the required fields (i.e. $nameErr, $emailErr, etc.) and set them to empty values. 2) inside the if ($_SERVER["REQUEST_METHOD"] == "POST") statement, nest an if else statement to check if the required field is empty by using the built in empty() function (this function returns a boolean value of false if the field is empty, which would make the condition false in the if else statements). Define the error message if the condition is true, and define the field input variable using the test_input function to clean it up if it is false. Ex: if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["name"])) { $nameErr = "Name is required"; } else { $name = test_input($_POST["name"]); } 3) In the form html code, create a script (span) with a class of error for styling, and echo the error message defined in the php code if the field is empty on submission. (Note: the reason the spanned error message is not echoed on the screen on load is because the condition of the field being submitted and returning as empty has not occurred, and so the error message is not triggered to echo by the if statement for it.) Ex: "> Name: * Full Example:

PHP Form Validation Example

* required field.

"> Name: *

E-mail: *

Website:

Comment:

Gender: Female Male *

--------------------------- Validate Name, E-mail, and URL: NOTE: You should always validate external data! Invalid submitted data can lead to security problems and break your webpage! By using PHP filters you can be sure your application gets the correct input! 1) NAME - check if the name field contains only whitespaces and letters. preg_match() (builtin function of php) - returns a boolean value of true or false. use the preg_match() function to check a match for characters in a string. two parameters are the characters to compare, and the target string. enclose the characters in quotes and / slash delimiters. To check for multiple characters, create character classes by enclosing them in [] brackets. Ex: [a-z] or [A-Z] or [1-9] etc. ^ means pattern must match the beginning of the string $ means pattern must match the end of the string Enclosing the options in ^$ means that only these characters should be included (??) * means there should be 0 or more occurences of the preceeding character or expression -just copy and paste examples of validation patterns, assign them to a variable and use that to test in the parameter of the function. Ex: $pattern = "/^[/w|/s]{1,16}$/"; if (preg_match($pattern,$string){ code here} etc. If the field is not valid, then store an error message: $name = test_input($_POST["name"]); if (!preg_match("/^[a-ZA-Z ]*$/",$name)){ $nameErr = "Only letters and white spaces allowed"; } --- 2) VALIDATE EMAIL: Use the built in filter_var() function. filter_var() function filters a single variable with a specified filter. It takes two parameters: The variable you want to check The type of check to use Ex: $email = test_input($_POST["email"]); if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $emailErr = "Invalid email format"; } Using filters: // Remove all illegal characters from email $email = filter_var($email, FILTER_SANITIZE_EMAIL); if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) { echo("$email is a valid email address"); } else { echo("$email is not a valid email address"); } ----------------- PHP FILTERS filter_var($varToCheck,filterToUse); this built in function uses 2 types of filters: -SANITIZE(removes bad characters) -VALIDATE(ensures format is correct) Ex: filter_var($email, FILTER_SANITIZE_EMAIL); or filter_var($email, FILTER_VALIDATE_EMAIL); ---------------------------- Further notes on Sanitizing/Validating user input inserted into a database: SQL Injections can occur when quote marks are inputted by user (i.e. if user inputes ''; DROP TABLE users;' --adding a quote in the middle of the string, then the sql parser will read the command) *The solution is to escape the quote marks and characters that allow for sql injections. mysqli_real_escape_string($dbconnection, $stringToEscape); --used to create a legal SQL string that you can use in an SQL statement. The given string is encoded to an escaped SQL string, taking into account the current character set of the connection. Ex: $city = "'s Hertogenbosch"; //assign the string to a variable. $city = mysqli_real_escape_string($link, $city); //now you can insert $city into a MySql query. For percent sign and underscore I use this: str_replace() is another function which can be used to specify escape characters. Note: Charset needs to be set preferrable on the server side. These escape/encoding functions will not use the character set that is defined with a query, http://php.net/manual/en/mysqlinfo.concepts.charset.php ---- Prepared Statements: Prepared statements are very useful against SQL injections, because parameter values, which are transmitted later using a different protocol, need not be correctly escaped. If the original statement template is not derived from external input, SQL injection cannot occur. --- Advantages: Prepared Statements work a bit better than mysqli_real_escape_string() in that you don't need to worry about escaping every single variable that will be in your query. They are by nature "prepared" before they go into the database. There are other advantages to this as well, in that: you do not need to addslashes() to be able to handle characters with apostrophes etc. for large databases, they will considerably speed up your queries (much like PDO). --- "INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)"; //? = substitute in an integer, string, double or blob value. bind_param("sss", $firstname, $lastname, $email); This function binds the parameters to the SQL query and tells the database what the parameters are. "sss" is the types of data for each of the variables (in this case each variable is a string): The argument may be one of four types: i - integer d - double s - string b - BLOB We must have one of these for each parameter. By telling mysql what type of data to expect, we minimize the risk of SQL injections Note: Any data used that is user input needs to be sanitized and validated first.\ Ex: Step 1) Create the statement template: $query = prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)"); Step 2) Bind values to the prepared statement with bind_param(); Step 3) assign values to the parameters and send statement to query ------------------ DATE: date(); function Parameters: format,timestamp-optional Format options: d - Represents the day of the month (01 to 31) m - Represents a month (01 to 12) Y - Represents a year (in four digits) l (lowercase 'L') - Represents the day of the week Can use punctuation of choice in between numbers: "; echo "Today is " . date("Y.m.d") . "
"; echo "Today is " . date("Y-m-d") . "
"; echo "Today is " . date("l"); ?> update copyright year automatically example: © 2010- TIME: characters that are commonly used for times: h - 12-hour format of an hour with leading zeros (01 to 12) i - Minutes with leading zeros (00 to 59) s - Seconds with leading zeros (00 to 59) a - Lowercase Ante meridiem and Post meridiem (am or pm) The example below outputs the current time in the specified format: Example Note that the PHP date() function will return the current date/time of the server! --------------------------------- COOKIES: use the setcookie($name); function to store a cookie on the users computer. syntax: setcookie(name, value, expire, path, domain, secure, httponly); *ONLY NAME IS REQUIRED, others are optional) ***setcookie function must be before the html tags (outside of it on top). Ex: //<---beginning of html code. --------------------------------- Creating/Opening a file in PHP: fopen(); NOTE: When opening a file to write using the 'w' parameter, you erase the contents automatically - be careful about this!! -------------------- DELETING A FILE: use unlink("filename"); Ex: unlink("test.txt"); Note: sometimes a file can continue to take up space if running under a process. May be better to use: use fclose("filename"); then unlink("filename"); to ensure the file is completely deleted. --------------------- DELETING MULTIPLE FILES IN A DIRECTORY: -use glob() to gather files in an array -uses array_map() to run the unlink() function on the returned array of files gathered with glob(): --------------------- OBJECT ORIENTED PROGRAMMING: Definitions: Instance: an object(represented by a variable) that holds the properties and methods of a class. Instantiation: calling the class to make the properties and methods accessible to an object (by assigning a variable to it). ----- Benefits: -enables modular functionality in code and enables complex functionality while simplifying the code and making it cleaner. **Uses classes (blueprints for objects) and Objects (data set grouped by a common theme and based on a class). --------- CLASSES: class is the keyword to create a class, then indicate the name, then : Note: The first letter of the name of the class must be CAPITALIZED! ex: class Car { //methods and properties here; function moveWheels(){echo "Wheels are moving!";} } -To check if a class exists use class_exists("clssName"); returns a boolean. When creating a class, create the properties before creating the methods. You can use method_exists("methodName"); for debugging if trying to find methods in a lot of code. --- Creating properties in the class: use keyword var to create properties (you can assign values or not): class Car { var $wheels = 4; //create properties with var keyword. var $hood = 1; var $engine = 1; var $doors = 4; //To modify or assign values to properties use $this (refers to the object/class that it is in): function changeWheels() { $this->wheels = 10; //changes the wheels property value in the class. Note: you don't use the $ when setting/accessing the properties in the function } function moveWheels(){echo "Wheels are moving!";} } -------- OBJECTS: To use the properties and methods of a class: -Create an instance of the class: use the keyword new and then the class name(); i.e. new Car(); <---this creates an 'instance' of the class. -Assign the instance of the class to a variable - the variable now stores the instance of the class and is an object and has access to properties and methods of the class. i.e. $hondaFit = new Car(); //this creates an instance of the Car class called $hondaFit (which can be called an object). To access methods/properties: to access a property/method use the -> operator and the name of the property/method (without the $ included): Ex (prop access): $hondaFit->wheels; or echo $hondaFit->wheels; <--this echoes '4'. Ex (method access): $hondaFit->moveWheels(); -Modify or assign a value to the object property: Ex: $hondaFit->wheels = 10; //reassigns the value of $wheels to 10. --------------- INHERITANCE: A class can inherit and access the properties and methods of other classes by using the extends keyword: Ex: class Class_A extends Parent_ClassB { //Class_A now has access to props and methods of Parent_ClassB. //Props and methods can be added which Class_A will have in addition to those of Class_B. //you can override the parent property by using var and assigning a new value to it: var $propNameFromClass_A = newValue; } ----------------------- CONSTRUCTORS: -Constructor functions execute every time a new instance is created of the parent class they're created in (with the new keyword). Can be used to create default values when a user is created or some default values of a new object that are automatically created when the object is instantiated. Also can be used for automatic validations and site housekeeping when new objects are created. -Create a function constructor in PHP using function keyword, two underscores, and construct keyword: Ex: class Class_A { function __construct(){ //do something code; this runs everytime a new instance of Class_A occurs. } } ------- DATA ACCESSORS: good stackoverflow post explaining in detail: https://stackoverflow.com/questions/4361553/what-is-the-difference-between-public-private-and-protected 3 types: 1) Public -- available to the whole program - scope is global. 2) Protected -- only available to the parent class or subclasses (extended) that inherit from the parent. 3) Private -- only available to the parent class (not accessible by extended classes You can use accessors on methods/properties as well as classes. Syntax: put the access type before the class keyword or variable/prop name: Ex: public class Class_A { private $prop1 = value; //only accessible inside the class } Uses: can be used to hide as much of the inner workings of an object as possible. That way it is less likely to break. If you make everything public, then another programmer might alter a variable which you don't want changed by anything other than the inner workings of your object. --------------------- STATIC MODIFIERS: This makes a method or property only accessible by the class and not by an instance or object of the class. Use: -It allows the use of a property or method of a class without having to make an instance of it. -Static properties can be referenced in methods inside the class by using ClassName::$property Use the static keyword in place of var: class Class_A { static $property = value; //the prop is attached to the class and not the instance of it. function funcName { Class_A::$property = newValue; //use :: syntax to access static property in the class } } To access the static property or method: Note: when using static data, use the $ in the variable name if present (as opposed to ommitting when working with an instance). -use :: to access after the class name: Ex: echo Class_A::$property; or Ex: Class_A::funcName(); //executes the method using the static prop. ----------------------------------------- PASSWORD ENCRYPTION: ----------- Newer simpler method besides crypt(): password_hash() function takes 3 parameters: (password, format method, array of options). Ex: password_hash('password', PASSWORD_BCRYPT, array('cost'=>12) ); The cost is how many cycles the generator runs - the higher the number, the more performance is slowed, so don't make it too big. 12 is a good number. PASSWORD_BCRYPT uses blowfish algorhithm. Use password_verify() in the login to match user entered password with the hashed version: Ex: $password = $_POST['password']; if (password_verify($password, $db_user_password)) { //Assigns $_SESSION variables to data from the user table in db: $_SESSION['user_id'] = $db_user_id; $_SESSION['username'] = $db_username; $_SESSION['password'] = $db_user_password; $_SESSION['firstname'] = $db_user_firstname; } ------------- Encrypt the password before sending to the db using crypt() and passing in the password and the salt string: (this is usually done on the registration phase when creating a user password, and then accessed with crypt() again for logging in) -use crypt() builtin function with PHP Note: using cypt() encrypts the password, but used alone is weak protection. Need to pass in parameters to make it stronger: salt -Choose a format of encryption: Diaz uses Blowfish. Ex: CRYPT_BLOWFISH -- the hash format is indicated by $2a$07$ in the parameter. Note: MD5 hash format is commonly used as well in a lot of Wordpress sites. Blowfish is more updated. To set Hash Format (check the php documentation for crypt() to see what is the latest) $hashFormat = $2y$10$"; <--the last number indicates the number of cycles the random generator runs. in this case 10 times. More cycles means it's more difficult for the hacker to go through the permeutations. Salt - an extra long/random string that is added to the password to make it more secure. -Set the salt parameter (you can make this up and end with numbers): Make a long string that is 22 characters in length: $salt = "usecrazystringwithch22"; -Combine the hashformat (blowfish format in this case) with the salt string: $hashFormat_and_salt = $hashFormat . $salt; <--this combines the strings to increase security. -Then, pass in the hash format and salt combo into the crypt() function along with the user password: $password = crypt($password, $hashFormat_andsalt); -The user password is now encrypted and can be passed into the query to insert and store it in the user database (under the password field). tip: for additional protection you can add the SHA (look it up on the php crypt() documentation), but this is probably not necessary. ------ To allow the user to login with their original password (unencrypted because it will not match the encrypted version in the db): In the login PHP code: Underneath the assigning of variables to the user data pulled from the db, reassign the user entered password in the login page to crypt($passwordFromLogin, $passwordFromUserDb); Ex: In login.php file: while ($row = $stmt->fetch()) { $db_user_id = $row['user_id']; $db_username = $row['username']; $db_user_password = $row['user_password']; $db_user_firstname= $row['user_firstname']; } //Converts the encrypted password from the db to match with the encrypted password in the db from registration: $password = crypt($password, $db_user_password); ======================== CREATE SECURE LOGIN ARTICLE: https://m.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL =============================================== =============================================== Misc and Definitions: stdClass - this always relates to an object in PHP. Comments: // single line comment # Single line comment as well /* multi line comment */ ! = NOT OPERATOR: The logical not operator forces the variable it’s in front of to be read as a boolean. Can be used in if conditionals to check if a variable or object is falsey (6 values: undefined, null, NaN, 0, "" (empty string), false) var_dump($varName); //shows what is stored in a variable/object ---------- From: https://stackoverflow.com/questions/14037290/what-does-this-mean-in-php-or Object and double arrow operators: -> and => syntax: double arrow operator, =>, is used as an access mechanism for arrays. This means that what is on the left side of it will have a corresponding value of what is on the right side of it in array context. This can be used to set values of any acceptable type into a corresponding index of an array. The index can be associative (string based) or numeric. $myArray = array( 0 => 'Big', 1 => 'Small', 2 => 'Up', 3 => 'Down' ); The object operator, ->, is used in object scope to access methods and properties of an object. It’s meaning is to say that what is on the right of the operator is a member of the object instantiated into the variable on the left side of the operator. Instantiated is the key term here. // Create a new instance of MyObject into $obj $obj = new MyObject(); // Set a property in the $obj object called thisProperty $obj->thisProperty = 'Fred'; // Call a method of the $obj object named getProperty $obj->getProperty(); Basically, -> is like the . in JS to access properties and functions. ----- If you get locked out of PHPMyAdmin after setting Password for root user: Go to this directory "xampp/phpmyadmin" and open config.inc.php file. On a Mac, go to /Applications/XAMPP/xamppfiles/phpmyadmin. Then change and configure the below code with your desired requirements. It worked with me. I installed both MySQL and XAMPP and worked successfully. $cfg['Servers'][$i]['controluser'] = 'Your Username'; $cfg['Servers'][$i]['controlpass'] = 'Your password'; *inser the $cfg['Servers'][$i]['auth_type'] = 'config'; $cfg['Servers'][$i]['user'] = 'Your Username'; $cfg['Servers'][$i]['password'] = 'Your password'; (from https://stackoverflow.com/questions/2570003/cant-get-access-to-phpmyadmin-after-setting-a-root-password-and-using-instant-r) ========================================== DEFINITIONS: Class: Describes the properties and methods of an object (a blueprint or definition of it). Properties can be variables, arrays, or data; methods are functions that create/define behaviors of the object. Object: A set of data grouped together by a common theme. i.e. variable, function, data structure, etc. Float: A float (floating point number) is a number with a decimal point or a number in exponential form. Arguments: (used in Function parameters) Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma. Key: the array element in the index. Instance: an object(represented by a variable) that holds the properties and methods of a class. Instantiation: calling the class to make the properties and methods accessible to an object (by assigning a variable to it). INHERITANCE: A class can inherit (access) the properties and methods of a parent class by using the extends keyword. class ClassA extends ParentClass {} =============== If difficulty on a particular, try http://www.phpforkids.com for learning