O GoConqr está de visual novo! Conte para nós o que você achou.

Flashcards

ITECH3108 - Dynamic Web Development

Ash Z Inglês 171 flashcards

Flashcards do conjunto (171)

  1. 1HTTPThe web is built on this
    Client-server
    1989
  2. 2HTTP ConnectionEstablish a connection
    Tunnel Over SSH
    IF the transport is reliable HTTP doesn't care
  3. 3HTTP RequestGET or POST
    Containing the location
    and protocol version
  4. 4HeadersThes give additional information to the server about the request
    In Key Value format
  5. 5User-AgentBrowser Identifier
  6. 6HostIf the server hosts multiple websites
  7. 7HTTP ProcessHere’s when your server-side code usually runs
  8. 8HTTP ResponseLots of data here
  9. 9HTTP Response Status CodeCode on how the request went
    e.g. 404, 200
  10. 10HTTP Response Connection: Keep-aliveWhether more requests should use this connection
  11. 11HTTP Response Cache-ContolWhether browsers should cache this and how long
  12. 12HTTP Response Content-Encoding Content-Length Content-TypeWhat the server is sending back
  13. 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
  14. 14HTTP Response X-PoweredHeaders starting with X- are not part of HTTP specification
  15. 15HTTP Response ContentFollows after 2 lines
  16. 16Web Servershandles the web request
    Most (not all!) web servers allow some type of code to be run on requests.
  17. 17Server-side codePHP
    Web browsers don't understand PHP but use it to generate HTML, CSS, etc.
  18. 18Client-side codeClient-side code is always some variant of JavaScript.
  19. 19Client-side code capabilitiesadding and removing elements (including elements!)
    changing attributes
    connecting to servers
    reading form contents
    loading new pages
  20. 20Where to write PHP code
  21. 21SyntaxUse Semicolon ;
    Comments start with // or #
    Multi-Line /* */
  22. 22VariablesDon't need to be declared before use
    $name = "Leonardo";
  23. 23Double quotes versus single quotesThe difference is that double-quoted strings do variable interpolation. That is, you can embed variables in double-quoted strings.
  24. 24Variable namesCase Sensitive
  25. 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
  26. 26Function Examplefunction do_something_amazing($x, $y) {
    return $x * $y;
    }
    echo do_something_amazing(2, 5);
  27. 27Argument evaluationArguments are evaluated before being passed to the function
  28. 28Overloadingyou can't declare multiple functions with the same name but different arguments in PHP
  29. 29Passing arguments by referenceYou can declare that a function takes a reference to a variable as an argument using &
    function swap (&$a, &$b)
  30. 30Adding to an array without declaring// Create and populate an array.
    $students[0] = "John";
    $students[1] = "Dorothy";
  31. 31Appending to an array// Create and populate an array
    $students[] = "John";
    $students[] = "Dorothy";
  32. 32Types of PHP arraySequential arrays
    Associative arrays
    Both declared with the same syntax and you can mix and match
  33. 33Sequential arraysSequential arrays are what we've just seen - an in-order list of stuff that you can look up by index
  34. 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'];
  35. 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
  36. 36Comparison Operators=== is the identical comparison operator
    == is the equal comparison operator
  37. 37Switch statementswitch($a) {
    case 0:
    case 1:
    echo '$a is zero or one';
    break;
  38. 38Foreach Loops$students = array("John", "Dorothy", "Sasha", "Deanna");
    foreach($students as $student) {
    echo "" . $student . "
    ";
    }
  39. 39PHP Variable ScopeLocal (function) scope
    Global Scope
    Super-global scope
    Class scope
  40. 40Local and Global ScopeOutside of a function has a global scope
    Inside a function has local scope
  41. 41PHP Variable ScopeGlobal scope is not visible inside a function
    use keyword global
    e.g.
    global $a;
  42. 42GlobalKeyword not needed when its a superglobal
    $a = 1;
    function test() {
    echo $GLOBALS['a'];
  43. 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)
  44. 44Including non-code files
  45. 45JavaScriptOften used for validation on the client-side
    Use this when looping back is going to be slow
  46. 46GET and POSTGET
    Use for queries that don’t change the state or database
    POST
    Use for other queries
    $_POST
    $_GET
    Super Globals
  47. 47Passing data between pagesHidden fields
    Cookies
    Session variables
    Or:
    Do it all client side
  48. 48Hidden FieldsHidden fields similar to text fields, but aren't displayed by the browser.
  49. 49Drawbacks of hidden fields- If there are too many forms and questions
    - Breaks back button
  50. 50CookiesCan be used to remember info between requests
    Cookies are stored locally by the browser on disk
  51. 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)
  52. 52Reading a cookieAll cookie values are available in the $_COOKIE Superglobal array
    $uid = $_COOKIE['uid'];
  53. 53Session Functionssession_start()
    Starts a new session or resumes an existing session
  54. 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.
  55. 55Problems with sessions- Session Hijacking
  56. 56Alternatives to using a database- Cookies
    - LocalStorage
    - WebDB
    - IndexedDB
  57. 57Using filesPHP's file functions are pretty easy to use
    However - they are not thread-safe
  58. 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
  59. 59MySQL extensionsmysqli
    mysql (deprecated)
  60. 60Database AbstractionsLet you connect with different databases using the same API
    PHP Data Objects (PDO)
    dbx
    ODBC
  61. 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
  62. 62Connect to the database$conn = mysqli_connect( 'host', 'username', 'password', 'database_name');
  63. 63Prepare a query$query = "SELECT name FROM goat WHERE id=1";
  64. 64Execute, get the results$results = mysqli_query($conn, $query);
  65. 65Loop through the results$row = mysqli_fetch_assoc($results); echo $row['name'];
  66. 66PDO - PHP Data ObjectsPDO is PHP's abstracted database interface
    The same code can be used for MySQL, PostgreSQL, and others
  67. 67OOPHP// Instantiate an object
    $goat = new Goat();
    // Call a method
    echo $goat->toString();
    // Access a property
    echo $goat->breed;
  68. 68PDO ProcessConnect to the DB
    Prepare a query
    Execute it and get the results
    Loop through them
  69. 69PDO Connect$connection = new PDO(
    'mysql:dbname=db;host=localhost;charset=utf8', // DSN
    'username',
    'password',
    [ /* other options go here */ ]
    );
  70. 70PDO Prepare$query = "SELECT name FROM goat WHERE id=1";
  71. 71PDO Execute$results = $connection->query($query);
  72. 72PDO Use the resultsforeach($results as $row) {
    echo $row['name'];
    }
  73. 73Preventing SQL injectionString Escaping
    Query parameterization
  74. 74String escapingTo perform string escaping in PDO, use the PDO::quote function
  75. 75String escaping drawbacksDoesn't work quite well for anything other than strings
  76. 76Query ParameterizationPDO allows this using PDO::prepare, adding an extra step to the process
    Then BindValues
  77. 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
  78. 78CookiesCan be used to identify session
  79. 79EncryptionPHP mcrypt_encrypt / mcrypt_decrypt
    You do not ever really need to know the plain-text password!
  80. 80How can I possibly tell if a user entered the right password if I don't know what their password is?hashing
  81. 81HashingHashing is a one way conversion of data from one form to another.
  82. 82Hashing AlgorithmsSHA1
    MD5
  83. 83SALTAlgorithms by themselves are not good enough,
    Add some salt to fix this
  84. 84Types of saltGlobal salt:
    Per-user salt:
  85. 85Using cryptcrypt() takes a string to hash and a specially formatted salt.
  86. 86ECMAScriptECMAScript is the standard that JavaScript, JScript and other implementations follow.
  87. 87What is JavaScript?duck-typed
    multi-paradigm
    scripting language
  88. 88JavaScript variablesvar - Function or Global scope
    let - Block scope
    const - Cannot reassign value - Same scope as let
  89. 89Anonymous functionsAnonymous functions do not know their own name.
    function(x, y, width, height) {
    // do something
    }
  90. 90Arrow functionslet sayIt = toSay => { console.log(toSay); }
    Arrow functions are most useful when passing anonymous functions as arguments
  91. 91HoistingThis means all variables declared with var inside a function are available anywhere in the function
  92. 92Block scopeBlock scope limits visibility to the containing block { }
  93. 93UndefinedAll declared variables contain the special value undefined until they are assigned a value
  94. 94JavaScript Objectsex: { key: "value", "quoted key": 3}
    Objects are JavaScript's Dictionary or Map type
    Objects, like arrays, are indexed using [square brackets]
  95. 95JavaScript Objects Lookupvar ninja = {"name": "Leo", "weapon": "Sword"};
    console.log(ninja['name']); // using []
    console.log(ninja.weapon); // using dot
  96. 96Running JS in the browserEmbedded
    console.log('hello');
    External
  97. 97Object-Oriented Programmingdecomposing and modeling problems
    designing software architecture
  98. 98Object-Oriented Programmingencapsulate their own data and behavior into a single package (or capsule!)
    specialize their behavior through inheritance
  99. 99PHP OO Class Examplename . " is " .
    $this->age . " years old";
    }
    }
  100. 100Creating instances of a class$s = new Student();
  101. 101Member visibilityPublic means anyone can access the member
    Protected means accessible by this class, and inherited classes
    Private means only accessible by this class
  102. 102Static membersStatic members belong to the class, not to instances
  103. 103Class scopestatic and constant members
  104. 104Constructors__construct()
  105. 105Destructors__destruct() that takes no parameters
  106. 106Using inheritanceUse the extends keyword
  107. 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
  108. 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
  109. 109Interfaces vs Abstract ClassesSee Below
  110. 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
  111. 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
  112. 112instanceof operatorinstanceof gives a way to determine whether an object is an instance of a class
  113. 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
  114. 114XMLXML is the eXtensible Markup Language
  115. 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
  116. 116XML SyntaxXML looks very similar to HTML, and uses the same element/attribute concept
  117. 117The Document ElementEach document contains exactly one root element.
    Like the element in HTML
  118. 118AttributesElements may have attributes in XML
  119. 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
  120. 120NodesThe DOM is mostly about manipulating Node objects.
  121. 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
  122. 122Create a DOM document$doc = new DOMDocument('1.0');
  123. 123Add new elements$elem = $doc->createElement('eName');
    $doc->appendChild($elem)
  124. 124Converting from DOM to string (and back)$doc->formatOutput = true;
    $doc->save('myfilename.xml');
    echo $doc->saveXML();
    $doc = new DOMDocument();
    $doc->loadXML('');
  125. 125Validating XML// Validate against a DTD
    $doc = new DOMDocument();
    $doc->load($filename);
    $isDTDValid = $doc->validate();
    $isXSDValid = $doc->schemaValidate($xsdfile);
  126. 126Converting HTML into DOM$doc = new DOMDocument();
    $doc->loadHTML('…');
  127. 127Using XPathYou can also use a technology called XPath to navigate XML documents
  128. 128How JSON worksJSON uses only built-in JavaScript primitives and data-types and associated syntax to represent data:
    Objects
    Arrays
    Strings
    Numbers
    Booleans
    null
  129. 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
  130. 130JSON - Escaping\" - quotation mark
    \n - new line
    \t - horizontal tab
    \r - carriage return
    \\ - backslash character
    \uXXXX - Unicode characters, for example \u2615 = ☕
  131. 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
  132. 132A better approach - JSON.parseAll current browsers support the built-in JSON object:
    var booklist = JSON.parse(bookJson);
  133. 133Decoding to arraysjson_decode
  134. 134Using json_encodejson_encode is the closest PHP equivalent to JSON.stringify
  135. 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
  136. 136AJAXThe general label for performing dynamic, JavaScript-driven HTTP requests is called AJAX
    Asynchronous JavaScript And XML
  137. 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();
  138. 138APIsAn API, or Application Programming Interface, is a set of functions and protocols by which an application can be manipulated programmatically
  139. 139XML-RPCXML-RPC is about calling procedures (functions) and getting return values
  140. 140SOAPSimple Object Access Protocol is the successor to XML-RPC
  141. 141Representational State Transfer (REST)REST is based on the same constraints as HTTP:
    Client-Server
    Stateless
    Cacheable
  142. 142REST has four "big ideas"Resources
    Representations
    Self-descriptive messages
    "Hypermedia as the engine of application state"
  143. 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
  144. 144REST - Resource IdentifiersWhen building a REST API over HTTP, use URIs for resource identifiers
    Uniform Resource Identifiers
  145. 145REST - RepresentationsThe representation of a resource is conceptually separate to the resource itself
  146. 146REST - Custom Media Types ExampleGithub's API (version 3) uses:
    application/vnd.github.v3+json
  147. 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
  148. 148HATEOAS - MotivationReferencing the place in the object
  149. 149OWASPThe Open Web Application Security Project
  150. 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
  151. 151Injection - Fixeshtml_special_chars
    mysqli_prepare
    document.write or the innerHTML property to insert raw HTML.
  152. 152Broken Authentication and Session ManagementFailure to hash passwords
    Failure to secure account management
    Unsafe use of session IDs
    Lack of encrypted transport (https)
  153. 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
  154. 154Unsafe use of Session IDsSession IDs must be kept absolutely secret
    Session Hijack
  155. 155Mitigating session fixationsession_regenerate_id(true)
  156. 156Preventing session ID leakingIn PHP, enable by configuring session.cookie_httponly in php.ini, or calling ini_set('session.cookie_httponly', true);
  157. 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)
  158. 158Preventing XSSEscape everything (carefully!) or use safe methods
    Use the Content-Security-Policy HTTP header
  159. 159Insecure Direct Object Referenceshttps://bank.example.com/accounts?id=776
    Change the number and you have access to someones account
  160. 160Mitigating Insecure ReferencesDon't use primary keys for resources - use some per-user or per-session value
    Always perform access control
  161. 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
  162. 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
  163. 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
  164. 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?
  165. 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:
  166. 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
  167. 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
  168. 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.
  169. 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
  170. 170Unvalidated Redirects and ForwardsAttacker links to unvalidated redirect and tricks victims into clicking it.
  171. 171Mitigating redirectsAvoid using parameterised redirects if you don't really need them

Informações

Descrição
FlashCards sobre ITECH3108 - Dynamic Web Development, criado por Ash Z em 12-06-2020.
Criado por
Ash Z
Visualizações
0
Avaliação

Fale Conosco

Sobre o que é sua mensagem?

O que você acha do novo visual?

Você gostou?