Fichas
ITECH3108 - Dynamic Web Development
Fichas del conjunto (171)
- 1HTTPThe web is built on this
Client-server
1989 - 2HTTP ConnectionEstablish a connection
Tunnel Over SSH
IF the transport is reliable HTTP doesn't care - 3HTTP RequestGET or POST
Containing the location
and protocol version - 4HeadersThes give additional information to the server about the request
In Key Value format - 5User-AgentBrowser Identifier
- 6HostIf the server hosts multiple websites
- 7HTTP ProcessHere’s when your server-side code usually runs
- 8HTTP ResponseLots of data here
- 9HTTP Response Status CodeCode on how the request went
e.g. 404, 200 - 10HTTP Response Connection: Keep-aliveWhether more requests should use this connection
- 11HTTP Response Cache-ContolWhether browsers should cache this and how long
- 12HTTP Response Content-Encoding Content-Length Content-TypeWhat the server is sending back
- 13HTTP Response Set-CookieTells the browser to remember this value with this key.
Usually has a timeout too.
Path says which locations the cookie should be sent back under - 14HTTP Response X-PoweredHeaders starting with X- are not part of HTTP specification
- 15HTTP Response ContentFollows after 2 lines
- 16Web Servershandles the web request
Most (not all!) web servers allow some type of code to be run on requests. - 17Server-side codePHP
Web browsers don't understand PHP but use it to generate HTML, CSS, etc. - 18Client-side codeClient-side code is always some variant of JavaScript.
- 19Client-side code capabilitiesadding and removing elements (including elements!)
changing attributes
connecting to servers
reading form contents
loading new pages - 20Where to write PHP code
- 21SyntaxUse Semicolon ;
Comments start with // or #
Multi-Line /* */ - 22VariablesDon't need to be declared before use
$name = "Leonardo"; - 23Double quotes versus single quotesThe difference is that double-quoted strings do variable interpolation. That is, you can embed variables in double-quoted strings.
- 24Variable namesCase Sensitive
- 25FunctionsAt their core, functions are used for organizing code to avoid repetitive work and to simplify code
Take arguments
ANd can have a return value - 26Function Examplefunction do_something_amazing($x, $y) {
return $x * $y;
}
echo do_something_amazing(2, 5); - 27Argument evaluationArguments are evaluated before being passed to the function
- 28Overloadingyou can't declare multiple functions with the same name but different arguments in PHP
- 29Passing arguments by referenceYou can declare that a function takes a reference to a variable as an argument using &
function swap (&$a, &$b) - 30Adding to an array without declaring// Create and populate an array.
$students[0] = "John";
$students[1] = "Dorothy"; - 31Appending to an array// Create and populate an array
$students[] = "John";
$students[] = "Dorothy"; - 32Types of PHP arraySequential arrays
Associative arrays
Both declared with the same syntax and you can mix and match - 33Sequential arraysSequential arrays are what we've just seen - an in-order list of stuff that you can look up by index
- 34Associative arraysAssociative arrays map a key to a value.These are like a Map or HashMap in Java, except ordered
$nicknames = array(
'Leonardo' => 'Leo',
print $nicknames['Leonardo']; - 35Accessing nested arrays$a = array( 'numbers' => array(1, 2, 3), 'letters' => array('a', 'b', 'c'));
$numbers_array = $a['numbers'];
$index_one = $numbers_array[1];
echo $index_one; // prints 2 - 36Comparison Operators=== is the identical comparison operator
== is the equal comparison operator - 37Switch statementswitch($a) {
case 0:
case 1:
echo '$a is zero or one';
break; - 38Foreach Loops$students = array("John", "Dorothy", "Sasha", "Deanna");
foreach($students as $student) {
echo "" . $student . "
";
} - 39PHP Variable ScopeLocal (function) scope
Global Scope
Super-global scope
Class scope - 40Local and Global ScopeOutside of a function has a global scope
Inside a function has local scope - 41PHP Variable ScopeGlobal scope is not visible inside a function
use keyword global
e.g.
global $a; - 42GlobalKeyword not needed when its a superglobal
$a = 1;
function test() {
echo $GLOBALS['a']; - 43require versus includerequire produces a fatal error if the file is not found
include produces a warning if the file is not found (which may be hidden in production) - 44Including non-code files
- 45JavaScriptOften used for validation on the client-side
Use this when looping back is going to be slow - 46GET and POSTGET
Use for queries that don’t change the state or database
POST
Use for other queries
$_POST
$_GET
Super Globals - 47Passing data between pagesHidden fields
Cookies
Session variables
Or:
Do it all client side - 48Hidden FieldsHidden fields similar to text fields, but aren't displayed by the browser.
- 49Drawbacks of hidden fields- If there are too many forms and questions
- Breaks back button - 50CookiesCan be used to remember info between requests
Cookies are stored locally by the browser on disk - 51setcookie ( )A function that adds a Set-Cookie header to the response
Pass
the name of the cookie,
the value of the cookie
an expiry time (in seconds) - 52Reading a cookieAll cookie values are available in the $_COOKIE Superglobal array
$uid = $_COOKIE['uid']; - 53Session Functionssession_start()
Starts a new session or resumes an existing session - 54Session variablesSession variables are not visible to the client, only the session ID is.
This is good! You can store sensitive stuff in there and the client can't manipulate it. - 55Problems with sessions- Session Hijacking
- 56Alternatives to using a database- Cookies
- LocalStorage
- WebDB
- IndexedDB - 57Using filesPHP's file functions are pretty easy to use
However - they are not thread-safe - 58Database advantagesConcurrent access by multiple threads/processes
Database, table and row-level permissions to keep content safe and private
Multiple sites (using replication)
Indexing for performance - 59MySQL extensionsmysqli
mysql (deprecated) - 60Database AbstractionsLet you connect with different databases using the same API
PHP Data Objects (PDO)
dbx
ODBC - 61MySQLi Steps1. Connect to the database
2. Prepare a query
3. Execute the query, and get results
4. Loop through the results and display them - 62Connect to the database$conn = mysqli_connect( 'host', 'username', 'password', 'database_name');
- 63Prepare a query$query = "SELECT name FROM goat WHERE id=1";
- 64Execute, get the results$results = mysqli_query($conn, $query);
- 65Loop through the results$row = mysqli_fetch_assoc($results); echo $row['name'];
- 66PDO - PHP Data ObjectsPDO is PHP's abstracted database interface
The same code can be used for MySQL, PostgreSQL, and others - 67OOPHP// Instantiate an object
$goat = new Goat();
// Call a method
echo $goat->toString();
// Access a property
echo $goat->breed; - 68PDO ProcessConnect to the DB
Prepare a query
Execute it and get the results
Loop through them - 69PDO Connect$connection = new PDO(
'mysql:dbname=db;host=localhost;charset=utf8', // DSN
'username',
'password',
[ /* other options go here */ ]
); - 70PDO Prepare$query = "SELECT name FROM goat WHERE id=1";
- 71PDO Execute$results = $connection->query($query);
- 72PDO Use the resultsforeach($results as $row) {
echo $row['name'];
} - 73Preventing SQL injectionString Escaping
Query parameterization - 74String escapingTo perform string escaping in PDO, use the PDO::quote function
- 75String escaping drawbacksDoesn't work quite well for anything other than strings
- 76Query ParameterizationPDO allows this using PDO::prepare, adding an extra step to the process
Then BindValues - 77CookiesThe special glue is that the browser will remember the values sent by the Set-Cookie header, and will send them with subsequent requests using the Cookie header
- 78CookiesCan be used to identify session
- 79EncryptionPHP mcrypt_encrypt / mcrypt_decrypt
You do not ever really need to know the plain-text password! - 80How can I possibly tell if a user entered the right password if I don't know what their password is?hashing
- 81HashingHashing is a one way conversion of data from one form to another.
- 82Hashing AlgorithmsSHA1
MD5 - 83SALTAlgorithms by themselves are not good enough,
Add some salt to fix this - 84Types of saltGlobal salt:
Per-user salt: - 85Using cryptcrypt() takes a string to hash and a specially formatted salt.
- 86ECMAScriptECMAScript is the standard that JavaScript, JScript and other implementations follow.
- 87What is JavaScript?duck-typed
multi-paradigm
scripting language - 88JavaScript variablesvar - Function or Global scope
let - Block scope
const - Cannot reassign value - Same scope as let - 89Anonymous functionsAnonymous functions do not know their own name.
function(x, y, width, height) {
// do something
} - 90Arrow functionslet sayIt = toSay => { console.log(toSay); }
Arrow functions are most useful when passing anonymous functions as arguments - 91HoistingThis means all variables declared with var inside a function are available anywhere in the function
- 92Block scopeBlock scope limits visibility to the containing block { }
- 93UndefinedAll declared variables contain the special value undefined until they are assigned a value
- 94JavaScript Objectsex: { key: "value", "quoted key": 3}
Objects are JavaScript's Dictionary or Map type
Objects, like arrays, are indexed using [square brackets] - 95JavaScript Objects Lookupvar ninja = {"name": "Leo", "weapon": "Sword"};
console.log(ninja['name']); // using []
console.log(ninja.weapon); // using dot - 96Running JS in the browserEmbedded
console.log('hello');
External - 97Object-Oriented Programmingdecomposing and modeling problems
designing software architecture - 98Object-Oriented Programmingencapsulate their own data and behavior into a single package (or capsule!)
specialize their behavior through inheritance - 99PHP OO Class Examplename . " is " .
$this->age . " years old";
}
} - 100Creating instances of a class$s = new Student();
- 101Member visibilityPublic means anyone can access the member
Protected means accessible by this class, and inherited classes
Private means only accessible by this class - 102Static membersStatic members belong to the class, not to instances
- 103Class scopestatic and constant members
- 104Constructors__construct()
- 105Destructors__destruct() that takes no parameters
- 106Using inheritanceUse the extends keyword
- 107Abstract ClassesAn abstract class cannot be instantiated
An abstract method has no body
A class that declares an abstract method must also be abstract
A class that extends an abstract class must either implement all the abstract methods, or be abstract - 108InterfacesContains only methods with no body, and maybe constants
Declare using the interface keyword
Classes can declare they implement an interface using the implements keyword - 109Interfaces vs Abstract ClassesSee Below
- 110Interfaces:A class may implement multiple interfaces
An interface does not contain any code (except constants)
An interface does not have any visibility specifiers – it’s all public - 111Abstract classes:A class may only inherit from one class
An abstract class may contain code and attribute declarations
Abstract classes can contain visibility specifiers - 112instanceof operatorinstanceof gives a way to determine whether an object is an instance of a class
- 113Why not use HTML for data interchange?HTML has traditionally been presentation-oriented
This is an unordered list, it gives some structure to the content, but very little meaning:
A list item
A list item - 114XMLXML is the eXtensible Markup Language
- 115How XML differs from HTMLXML doesn't define any elements or attributes
XML therefore allows semantic markup
XML has tighter syntax rules - for example you must close every element you open - 116XML SyntaxXML looks very similar to HTML, and uses the same element/attribute concept
- 117The Document ElementEach document contains exactly one root element.
Like the element in HTML - 118AttributesElements may have attributes in XML
- 119Document Object Model (DOM)What is it for?
A platform- and language-neutral interface for creating and manipulating XML documents programmatically
and HTML documents too - 120NodesThe DOM is mostly about manipulating Node objects.
- 121What can you do with the DOM?Create or load a document
Navigate its structure and query its contents
Add, modify and delete its nodes - 122Create a DOM document$doc = new DOMDocument('1.0');
- 123Add new elements$elem = $doc->createElement('eName');
$doc->appendChild($elem) - 124Converting from DOM to string (and back)$doc->formatOutput = true;
$doc->save('myfilename.xml');
echo $doc->saveXML();
$doc = new DOMDocument();
$doc->loadXML(''); - 125Validating XML// Validate against a DTD
$doc = new DOMDocument();
$doc->load($filename);
$isDTDValid = $doc->validate();
$isXSDValid = $doc->schemaValidate($xsdfile); - 126Converting HTML into DOM$doc = new DOMDocument();
$doc->loadHTML('…'); - 127Using XPathYou can also use a technology called XPath to navigate XML documents
- 128How JSON worksJSON uses only built-in JavaScript primitives and data-types and associated syntax to represent data:
Objects
Arrays
Strings
Numbers
Booleans
null - 129JSON is stricter than JavaScriptNo comments are allowed in JSON
Not all JavaScript types are allowed
Only decimal number types are allowed
Object keys must be double-quoted - 130JSON - Escaping\" - quotation mark
\n - new line
\t - horizontal tab
\r - carriage return
\\ - backslash character
\uXXXX - Unicode characters, for example \u2615 = ☕ - 131Problems with evalUsing eval is generally a bad idea:
Using eval prevents most JavaScript engines from optimizing properly
You must absolutely trust that the JSON you are evaluating does not contain actual JavaScript code
eval doesn't have the same strictness as JSON - 132A better approach - JSON.parseAll current browsers support the built-in JSON object:
var booklist = JSON.parse(bookJson); - 133Decoding to arraysjson_decode
- 134Using json_encodejson_encode is the closest PHP equivalent to JSON.stringify
- 135When to communicateBrowser requests a page at a particular URL
Server responds with HTML
Browser displays the HTML, and requests related resources
Browser continues to make requests and processes responses using JavaScript - 136AJAXThe general label for performing dynamic, JavaScript-driven HTTP requests is called AJAX
Asynchronous JavaScript And XML - 137Using XMLHttpRequest - Simple GETCreate an XMLHttpRequest
var xhr = new XMLHttpRequest();
Initialize a request
xhr.open("GET", "my_page.php", true);
the third argument makes the request asynchronous
Add event handlers
Attach to onload, onerror, onprogress, or onreadystatechange
xhr.onload = function(ev) { … }
Send the request
xhr.send(); - 138APIsAn API, or Application Programming Interface, is a set of functions and protocols by which an application can be manipulated programmatically
- 139XML-RPCXML-RPC is about calling procedures (functions) and getting return values
- 140SOAPSimple Object Access Protocol is the successor to XML-RPC
- 141Representational State Transfer (REST)REST is based on the same constraints as HTTP:
Client-Server
Stateless
Cacheable - 142REST has four "big ideas"Resources
Representations
Self-descriptive messages
"Hypermedia as the engine of application state" - 143REST - ResourcesAny information you can give an identifier can be a resource
Database entries
identified by table name and primary key
Images and media
identified by filename or path
Calculated values
identified by query name
Collections of other resources
identified by table name or directory, for example - 144REST - Resource IdentifiersWhen building a REST API over HTTP, use URIs for resource identifiers
Uniform Resource Identifiers - 145REST - RepresentationsThe representation of a resource is conceptually separate to the resource itself
- 146REST - Custom Media Types ExampleGithub's API (version 3) uses:
application/vnd.github.v3+json - 147REST - Control DataGET - Retrieve a resource representation
POST - Create a new resource, based on the supplied representation
PUT - Create, replace or update a resource using the supplied representation
PATCH - Perform a partial update of an existing resource
DELETE - Remove a resource
OPTIONS - Determine available actions - 148HATEOAS - MotivationReferencing the place in the object
- 149OWASPThe Open Web Application Security Project
- 150InjectionWe've looked at this already with HTML and SQL injection:
Submit HTML (including script elements) which affect the behaviour of the page
Submit SQL fragments which modify the behaviour of database queries - 151Injection - Fixeshtml_special_chars
mysqli_prepare
document.write or the innerHTML property to insert raw HTML. - 152Broken Authentication and Session ManagementFailure to hash passwords
Failure to secure account management
Unsafe use of session IDs
Lack of encrypted transport (https) - 153Failure to hash passwordsAttackers can log in as a user and perform actions on their behalf
Always use a cryptographic hash to protect passwords
In PHP, use crypt() or password_hash() and related functions - 154Unsafe use of Session IDsSession IDs must be kept absolutely secret
Session Hijack - 155Mitigating session fixationsession_regenerate_id(true)
- 156Preventing session ID leakingIn PHP, enable by configuring session.cookie_httponly in php.ini, or calling ini_set('session.cookie_httponly', true);
- 157Cross Site Scripting (XSS)XSS is a catch-all term for any vulnerability that allows JavaScript to be injected into the page
Server-side: JavaScript is injected into generated HTML/JS
Client-side: Untrusted content is added directly to the DOM on the client side (or passed to eval, setTimeout, or setInterval) - 158Preventing XSSEscape everything (carefully!) or use safe methods
Use the Content-Security-Policy HTTP header - 159Insecure Direct Object Referenceshttps://bank.example.com/accounts?id=776
Change the number and you have access to someones account - 160Mitigating Insecure ReferencesDon't use primary keys for resources - use some per-user or per-session value
Always perform access control - 161Security misconfigurationLeaving debugging information on, which can leak valuable information to malicious users
Leaving database configuration details visible
Using weak database passwords, or connecting to the database as root - 162Sensitive Data ExposureIn October 2015, artist funding site Patreon was hacked, exposing 15GB of data, including 2.3 million email addresses, donation records and personal details
- 163Mitigating data exposureHash passwords properly
Don't store stuff you don't need - discard old data, and let somebody else handle credit card transactions
Encrypt sensitive information, such as home addresses, political affiliation, or photos - 164Missing Function Level Access ControlSome web apps show a different set of available functionality, depending on the user's access level
Make sure you test access levels, not just when displaying the user interface, but also when performing the function. Can a user access admin functions by typing in a different URL? - 165Cross-Site Request Forgery (CSRF)CSRF is about convincing a user's browser to send requests that the user didn't intend it to.
Consider a bank website which allows transferring money to an external account through a simple form, submitted using a POST request: - 166CSRFYou are currently logged in to the bank website
A malicious user sends you a link to a site they control, funnycats.com, with a form embedded in it
At this point, you are interacting with funnycats.com but still have an active session on the bank website - 167Preventing CSRFA simple way is to check the Referer header to determine which page submitted the form.
In the bank's case, if the Referer header doesn't start with https://bank.example.com/ then discard the request - 168Preventing CSRFThe best way to prevent CSRF is to generate a unique token per session (separate to the session ID)
Embed this token as a hidden input in every POST, and verify it at the server on every submission. - 169Using components with known vulnerabilitiesThis is mostly a systems-level consideration
However, if you use a web framework such as Laravel, Symfony, CodeIgniter or similar, it is important to keep up with security updates - 170Unvalidated Redirects and ForwardsAttacker links to unvalidated redirect and tricks victims into clicking it.
- 171Mitigating redirectsAvoid using parameterised redirects if you don't really need them
Información
- Descripción
- Fichas sobre ITECH3108 - Dynamic Web Development, creado por Ash Z el 12/06/2020.
- Creado por
- Ash Z
- Visitas
- 0
- Valoración