WEB DEV PDF
Document Details
Uploaded by IdealBiedermeier
Tags
Summary
This document provides lecture notes on internet and WWW topics. It covers topics like internet protocol (IP), transmission control protocol (TCP), and related concepts. It is suitable for an undergraduate-level course.
Full Transcript
Lecture 1 - INTERNET/WWW - Internet - A connection Of Computers Using the Internet Protocol - Internet Protocol (IP) is the method or protocol by which data is sent from one computer to another on the internet - Key Aspects Of The Internet...
Lecture 1 - INTERNET/WWW - Internet - A connection Of Computers Using the Internet Protocol - Internet Protocol (IP) is the method or protocol by which data is sent from one computer to another on the internet - Key Aspects Of The Internet - sub-networks can stand on their own - computers can dynamically join and leave the network - built on open standards; anyone can create a new internet device - lack of centralized control (mostly) - everyone can use it with simple, commonly available software - Internet Layered Architecture - OSI Model Layers - Physical - hardware to send and receive data. e.g. ethernet cables, modems, coaxial cable. - Data Link - handles the moving of data in and out across a physical link in a network - Network - decision is made as to which physical path the information should follow from its source to its destination. - Transport - ensures the reliability of data delivery by detecting and attempting to correct problems that occurred - Session - manages the setting up and taking down of the association between two communicating endpoints that is called a connection - Presentation - transforms data into a form that application layer can accept. e.g. JPEG, MPEG, ASCII, encrypted or non-encrypted, etc - Application - web browser, email, ftp - Internet Protocol (IP) - Specifies the format of packets, also called datagrams, and the addressing Scheme. - Local IP address = In a terminal type ifconfg or ipconfg - Transmission Control Protocol (TCP) - Adds Multiplexing, Guaranteed Message Delivery on top of IP - Multiplexing refers to the ability to send multiple types of data across a single communication channel. - TCP achieves multiplexing using ports. Each application running on a device is assigned a unique port number, and when data is sent over TCP, it is addressed to both the IP address (which identifies the device) and the port number (which identifies the application or service). This allows multiple services (like HTTP, FTP, email, etc.) to run on the same device without interfering with each other. - Multiple Programs can use the Same IP address. - This is done using different ports, which is a number given to each program or service - port 80 - web browser (443 for SSL) - port 25 - email - port 21 - ftp - port 22 - ssh - WWW - Part of the Internet that can be accessed through websites - 1960-1970 = Arpanet - Creation of WWW - Tim Berners-Lee - 1989-1991 - Browser Wars - Netscape Navigator (1994) = Internet Explorer (1995) - Dot-Com Bubble (1997-2000) - Dot-Com Collapse (1999-2001) - Since then the web has become an integral part of our lives - Web Servers - Computers That Deliver (serves up) Web Pages. - Web Server Software - Apache - Nginx - Microsoft Internet Information Server (IIS) - Web Browsers - Software Used to locate, retrieve, and display content on the World Wide Web - Examples - Google Chrome, Microsoft Edge, Safari, Opera, Mozilla Firefox - Domain Name System (DNS) - An internet service that translates domain names into IP Address - Uniform Resource Locator (URL) - Global Address Of Documents and other Resources on the World Wide Web - What a browser do? - The Browser asks the DNS server for IP address for www.mona.uwi.edu - Next, it connects to that IP address on port 80 (default port) - Ask the server to GET /foo/bar.html (and any other resources on that page) - Displays the web page in your browser - Hypertext Transfer Protocol (HTTP) - Protocol that defines how messages are formatted and transmitted and what actions web servers and browsers should take in response to various commands. - Some HTTP Request Methods - GET = often used to read or retrieve a resource - POST = often used to create a new resource - PUT = most often used for Updates - PATCH = used to modify resources but only contains the changes. - DELETE = Deletes the resource - HEAD = Same as GET but returns only HTTP headers and no document body - OPTIONS = Returns the HTTP methods that the server supports - HTTP Response Status Codes - 200 = OK - 301 = Moved Permanently - 304 = Not Modified - 403 = Access Forbidden - 404 = Not Found - 500 = Internal Server Error - MIME Types/Content Types - Multipurpose Internet Mail Extensions (MIME) - Used to specify the type of data - text/html for.html - text/plain for.txt - image/jpeg for.jpg - Other Web Languages/Technology - HTML - HyperText Markup Language (skeleton) - is the basic building block of a webpage and used for creating a webpage. - CSS - Cascading Stylesheets (cloths) - used to style of your webpages. - JavaScript (brain) - a lightweight, interpreted, programming language used to control the behavior of your web pages. - PHP - PHP Hypertext Preprocessor (helper to change things base on person) - server-side language used to dynamically create pages. - AJAX - Asynchronous JavaScript + XML (talks to server without reloading) - the use of the XMLHttpRequest object to communicate with server-side scripts - XML - eXtensible Markup Language (store & organize data so computer understands) - eXtensible Markup Language: for exchanging and representing data - JSON - JavaScript Object Notation(store & share info like XML but faster and simpler) - for exchanging and representing data. - SQL - Structured Query Language (librarian, helps ask questions to database and gets answers) - Structured Query Language: used to interact with a database. N.B - HTML gives the webpage structure. - CSS makes it look good and stylish. - JavaScript lets you do things on the page, like clicking buttons or getting new content without reloading. - PHP helps make things happen on the server before the page shows up in your browser. - AJAX helps JavaScript talk to the server smoothly without refreshing the page. - XML and JSON are ways to store and share data between computers. - SQL helps get or update data from the database. Analogy to make it easier to understand - HTML is like the walls and floors of your house. It's how you make the rooms and put everything in its place. - CSS is like the paint and decorations. You use it to make your house look super cool with different colors, wallpaper, and maybe even some sparkly lights! - JavaScript is like the electricity in your house. It makes things move and do 🎶 stuff, like turning on the lights, making the doors open, and maybe even playing your favorite songs! - PHP is like a magic helper who can change things in your house depending on who's coming over. Maybe they make the house bigger for a party or cozier for just your family. - AJAX is like a special phone that lets you talk to someone far away without having to wait for them to come to your house. - XML and JSON are like different ways of writing secret messages that only your computer can understand. They help your computer keep track of all the important stuff in your house. - SQL is like a librarian who knows where everything is in your house. If you can't find your favorite toy, SQL can help you find it! Lecture 2 - HTML(Hypertext Markup Language (HTML) - Is A markup Language - Used to tell your browser how to structure the web pages you visit. - HTML consists of a series of elements, which you use to enclose, or wrap, different parts of the content to make it appear a certain way, or act a certain way. - paragraph - bold - underline - stronger font (bolder) … (better than using bold) - Attribute - Nesting - Placing an element inside another element - something - Empty Elements (no content to wrap) - Element with no inner content - - … - - - … horizontal ruler (attributes: width, height) - … new line (blind break) - Anatomy - All HTML documents require a structure that includes the following declaration and element - - … wraps entire HTML page … (below doc type) … ROOT ELEMENT - … (16 and 38 might not work on consumer computer) - - Name in Tab - - DOCTYPE - An instruction to the web browser about what version of HTML the page is written in. - HTML Element - The element. This element wraps all the content on the page. It is sometimes known as the root element. - HEAD Element - container for machine-readable information (metadata) about the HTML page. - This includes things like the title, keywords, and a page description that would appear in search results, styles (CSS), scripts (JavaScript), character set declarations, and more. - TITLE Element - This sets the title of the page, which is the title that appears in the browser tab the page is loaded in. - The page title is also used to describe the page when it is bookmarked and used in Search Engines as the title for search engine results. - META Tags - They provide additional information about your page for web browsers, search engines, etc. - BODY Element - This contains all the content that displays on the page, including text, images, videos, games, playable audio tracks, or whatever else. - Images - - Headings - , , , , , - Links - Links are what makes the Web A WEB. They link to other web pages or files. - … archer ( - UWI Mona - Comments - - List - - - Ordered List ( ) - - Unordered List ( ) - - Definition Lists ( ) - Special Characters - … space (new break space) - Because Any consecutive image spaces within your HTML document are seen as one - &trade (iconic trademark character ) - © (iconic copy right character) - < () - Blocks and inline - Elements are usually either block-level or inline elements - Block-level elements begin on new lines, stacking one on top of the other - , , , , , - Inline elements do not begin on a new line. They can start anywhere in a line and only occupies the width of their content. They should not wrap block-level elements and are typically used with text. - = used to define hyperlinks, allowing you to link from one page to another - (The href attribute specifies the destination URL.) - = used to group inline elements or text for styling purposes - = indicate that the enclosed text should be strongly emphasized (bold) - = used to emphasize a part of the text,( italic by default) - Tables - … element is used to create a table on a page. - … creates table heading (Items) - … defines rows in tables - … creates columns ( Textbook $130.02 ) - … adds caption to table - The element denes a set of rows dening the head of the columns of the table - The encapsulates a set of table rows, indicating that they comprise the body of the table. - The element denes a set of rows summarizing the columns of the table - Forms (EXAMPLES ON SLIDES) - Used to collect user input. And the input is often sent to a server to be processed. - … add form element and wraps other elements - … determines where it is sent - … which HTTP method used when submitting data (GET or POST) - - First Name: - - (“text”) … (single line) (“radio”) … (for selecting one of many choices) (“checkbox”) … (Displays a checkbox (selecting 0 or more of choices) (“submit”) … (Displays a submit button … for submitting the form) - The name has to be the same for the same question options - - Method MUST equal post - - - Setting Language - You can (and really should) set the language of your web page. - - Other Semantics - Introduces meaning to the code we write. - Using semantic tags makes it clear to the browser what the meaning of a page and its content is. - Always write HTML code that describes the content rather than how that content should look - … used for quotes - … abbreviations - …container for introductory content. Typically contains one more heading elements, logo or icon, and author information. - … defines a set of navigation links - …species the main content of a document. There - should only be one main element. - … footer for a document or section. Typically for author, copyright etc. … content indirectly related to surrounding/main content (like a sidebar) - … a section in a document. Pages can be split into sections for introduction, content, and contact information - … - can be used for forum posts, blog posts, or news articles. - and Lecture 3 - CSS (Cascading Stylesheet) - code you use to style your webpage - Applies style to tags - CSS lets you apply styles selectively to elements in HTML documents. - External Stylesheet (between head) - - Internal/Embedded stylesheet - … - General Example - p{ color: red;} - p = selector - color = property - red = property value - p,hi,li {color:red;} … multiple selectors - Types of Selector - Element Selector - “p” - selects - ID Selector (#) - Multiple tags with the same ID - #my-id - Selects - Class Selector (.) -.my-class - Selects ) - Attribute Selector ([ ]) - Don't just look at the element itself - img[‘src’] - Selects - BUT NOT - Pseudo Selector (:) … when - Tag:state tag is in - a: hover - Selects - BUT ONLY WHEN THE MOUSE HOVERS OVER THE LINK - Combinators - CSS selectors can contain more than one simple selector. - “,” = do this one or that one - “space” = descendant selector (style based on one applying to another) - matches all elements that are descendants of a specified element. div p { background-color: yellow; } - “ > “ = child selector - The child selector selects all elements that are the children of a specified element. div >p … ( are children of div) - “+” = adjacent sibling selector - Selects all elements that the adjacent siblings of a specified element div + p { background-color: yellow; } … (all elements that are placed immediately after elements.) - “~” = general sibling selector - Selects all elements that are siblings of a specified element. div ~ p { background-color: yellow; } … (selects all elements that are siblings of elements.) - Cascade - The last one is the one that counts - Therefore, styles can be added or overwritten as the stylesheet progresses. - When different types of selectors are used and the specicity of those selectors breaks the cascade. - Specificity - Each selector in CSS has a specificity weight - Along with the placement in the cascade, identify how its styles will be rendered - type/elements selectors = 0-0-1 (lowest) - class/attributes selectors = 0-1-0 (medium) - ID selectors = 1-0-0 (highest priority) - last done - Colors - Represent - Keywords = white - Hexadecimal Notation = #FF6600 - RGB = rgb(128, 0, 0) - HSL (Hue-Saturation-Lightness) = hsl(0, 100%, 25%) - Units - Pixels (px) = better for images - Percentages (%) = better for responsive - Em (em) - REM - VH/VW(Viewpoint Height and width) - Box Model - Every element on a page is a rectangular box and may have width, height, padding, borders, and margins - Margin = Border = Padding = Content - Margin - allows us to set the amount of space that surrounds an element. (ie. outside an element border) - Padding - allows us to set the amount of space inside an element's border (ie. between the border and the content) - Borders fall between the margin and padding. - Borders require 3 properties - width, style, and color. - Examples of the most common styles are solid, double, - dashed, dotted, and none. - N.B Border Radius - Total width = margin-right + borderright + padding-right + width + padding-left + border-left + margin-left - Total height = margin-top + bordertop + padding-top + height + paddingbottom + border-bottom + margin-bottom - Box Sizing “box-sizing” - Allows us to change the way the box model is calculated. - It allows us to include the padding and border in an element's width and height values. - Allowed values are content-box and border-box - context-box is the default - -webkit-box-sizing: border-box; ( works with edge) - -moz-box-sizing: border-box; (works with Mozilla) - Box-sizing: border-box; (works with Chrome by default) - INCLUDE ALL SO IT CAN RUN ON ANY VENDOR-SPECIFIC - Custom Properties (VARIABLES) - Complex websites tend to have very large amounts of CSS and often will have a lot of repeated values. - CSS now has the ability to create variables to store values that you need to reuse throughout your stylesheets. - You can also use the values in JavaScript - “--” and “:root” :root { --main-bg-color: brown; } h1{ color:var(--main-bg-color) - Layouts and Positioning - Normal Flow - Position Elements - Floats - Allows us to take an element, remove it from the normal flow of a page, and position it to the left or right of its parent element. - (only left or right) … best-used responsiveness - STOP: use “clear” instead of “float” (for footer mainly) section { float: left; margin: 0 1.5%; width: 63%;} aside { float: right; margin: 0 1.5%; width: 30%;} - Uniquely Positioning Elements - There are times we need to precisely position an element. - Default: static (normal flow) - Others: relative, absolute, or fixed (can override static) - For fixed the content remains stationary in the background no matter how much you scroll - Work along box offset properties (top, right, bottom, and left) - Relative Positioning - Allows us to move an element, but keep it in the normal flow of a page, thus preventing other elements from flowing around it or taking up the space it once held. - Relative to the element before it (starts commands based on the element/item before it) - Absolute Positioning - Similar to the relative value for the position property, with the exception that the element will not appear in the normal flow of the document and the space it occupies will not be preserved. - Absolute to the nearest Relative - Flexbox (EXAMPLES ON SLIDES) - Layout method for 1-dimensional layout (rows and columns) - Provides tools to allow rapid creation of complex, flexible layouts that can scale better from desktop to mobile. - “display: flex;” - Flex containers (parent) will then contain one or more Flex items (children). - Main Axis (→) - Along the row - Cross Axis (↓) - Runs along the column - Direction “flex-direction” - Values = row, row-reverse, column or column reverse - Horizontal alignment “justify-content” - Values = flex-start, flex-end, center,space-between, or space-around - Vertical alignment “align-items” - Values = flex-start, flex-end, center, baseline, or stretch - Gaps (between flex items ) - “gap”, “column-gap” or “row-gap” - Properties - “align-self” = allows aligning of individual flex items - “flex” = specifies the length of flex item relative to the rest of the flex items inside the same container (combines “flex-grow”, “flex-shrink” and “flex-basis”) - “order” = order of flexible items relative to rest of flexible items inside the same container - Grid “Display: grid;” - Designed as a two-dimensional layout method. Two-dimensional means that you wish to lay your content out in rows and columns. - It allows us to create grid like structures without using tables or needing a CSS framework such as Bootstrap. And our layouts can also be redened using CSS Media Queries to adapt to different contexts (Responsive WebDesign). - Grid Lines - Made of lines (running horizontally and vertically) - Grid Tracks - spaces between 2 grid lines (entire row) - Grid Cell - smallest space on a grid (intersection of a row and column track) - Grid Gap - gutter/alley between tracks - Create Grid - “Grid-template-columns” and “grid-template-rows” - Create Gaps - “Gap:” or “grid-gap:” - With these sets, the direct children of the grid-container (parent) now become grid items and the auto-placement algorithm lays them out, one in each grid cell. Creating extra rows as needed. - Position or Span - “grid-column” - Create Flexible grid Tracks UNIT - “fr” (fraction of available space) - Repeat all or a section of a grid - “repeat()” - Define a size of range = to max - “minmax” Lecture 4 JavaScript - Programming Language (lightweight) that Adds Interactivity to your website - With First Class Functions. (Born out of Java) … NOTHING TO DO WITH JAVA(used as marketing It allows us to create grid-like structures without using tables or needing a CSS framework such as Bootstrap. - Our layouts can also be reddened using CSS Media Queries to adapt to different contexts (Responsive Web Design).ploy) - Introduced 1995 in Netscape Navigator Web Browser - Primarily runs in your browser - ECMAScript is the standard. - While not all browsers currently support all the new features, you can take advantage of them through a transpiler (e.g. BabelJS) - Console “console.log()” - Lets you use standard javascript statements and console-specific commands while a page is live in the browser (helps you debug the page.) - console.log() used over alert() … to help debugging - Adding JavaScript to the webpage - External (Usually put in head tag) - - Internal - // My code here - Basic Types of Values - Numbers - “NaN” - Not a number (aids) - Strings - Use either “ ” or ‘’ - Concatenation “+”… eg. “Hello”+” ”+”World!” - Template Literals (add inserts into a literal string) “$” - eg. My name is ${variablename} - Booleans - true and falses (default for expressions that compare - Allows you to compare 2 strings as well - Objects - Functions - Undefined Values (VERY IMPORTANT) … if someone plays the idiot - A variable that has not been assigned a value - (Null means it doesn't exist at all (NOT THE SAME AS UNDEFINED) - Operators - Unary Operator (e.g. typeof) - Binary Operators (e.g. +, -, *, /, %) - Ternary Operator (e.g ?: (used as shorthand if/else) ) - Logical Operators (e.g. &&(and), || (or)) - Comparison Operators (e.g. ==, !=, ===, !==, , =) - Expression - Combination of values, variables, and operators which computes to a value - E.g “hello world” / 10 / 5-2 - Statement - Instructions to be executed and are usually separated by semicolons - Variables - Declaring “let” - E.g let x = 3; - By using let the computer will know that x is an integer because we stored a integer in it (3) - “let” (new way) or “var” can be used - Keywords/Reserved Words - Cannot be used as variable or function names - break, case, catch, class, const, continue, debugger, default, delete, do, else, enum, export, extends, false, finally, for, function, if, implements, import, in, instanceof, interface, let, new, null, package, private, protected, public, return, static, super, switch, this, throw, true, try, typeof, var, void, while, with, yield - Functions (Processal what it does) - Bread and Butter of Javascript Programming - A function is a block of reusable code that performs a specific task - Tool to Structures larger programs, Reduce repetition, Associate names with subprograms, and to Isolate these subprograms from each other - Example 1 - function squares(x) { Return x*x;} - Example 2 - Let makeNoise = function() { console.log(“Pling!”};}; - Example 3 (for parameters) - let power = function(base, exponent){ let result = 1; for (let count = 0; count < exponent; count++) result *= base; Return result;}; - Example 4 (filtering and mapping in arrays and lists) - (x,y) => { Return x*y;} - Example 5 - let square = (x) => { x * x;} - Control Structures (use console.log instead of alert to reduce pop-ups) - if/else - Example - let num = Number(prompt(“Pick a number”,0)) if (num 6); console.log(result); - Reduce - Similar to a map but it does something to the value - Example - const numbers = [1, 2, 3, 4]; const sum = numbers.reduce((result, item) => result + item, 0); console.log(sum); - Objects ({}) - Allows you to store a list/collection of values too BUT with named keys - Arrays just set out the values while Objects have a key for each value - Example let myCar = { wheels: 4, "brand name": "Toyota", model: "Corolla", features: ["air condition", "radio"] }; - To retrieve myCar.wheels myCar['wheels'] - NB = let variables can be updated but not re-declared const variables can neither be updated nor re-declared - Destructuring “...rest” - Syntax makes it possible to unpack values from arrays, or properties from objects, into distinct variables. - So instead of doing this: const someArray = [10, 20, 30, 40, 50]; let a = someArray; let b = someArray; console.log(a); // 10 console.log(b); // 20 - We shorten and do this: - Arrays: let [a, b,...rest] = [10, 20, 30, 40,50]; console.log(a); // 10 console.log(b); // 20 console.log(rest); // [30, 40, 50] - Objects: let {make, model,...rest} = { make: "Toyota", model: "Corolla", wheels: 4}; console.log(make); // Toyota console.log(model); // Corolla console.log(rest); // { wheels: 4 } - Strict Mode "use strict"; - JavaScript can be made a little more “strict” by enabling strict mode. - To do this you would place "use strict"; at the top of your JS le or the top of a function body. - Strict mode for instance will require you to use “var” - Disallows giving a function multiple parameters with the same name - Loads Page - document.addEventListener('DOMContentLoaded') - The Document Object Model (DOM) - Programming Interface for HTML, XML and SVG Documents. - Provides a Structured representation of the document as a tree - “document” is the global variable that gives us access to all the elements in our HTML document. - The DOM has various properties and methods for traversing the tree. We can use these properties and methods in JavaScript to find elements and manipulate the DOM. - Each node in the tree has a “parentNode” and “childNodes” property - In addition to those you also have “firstChild”, “lastChild”, “previousSibling” and “nextSibling properties” - ONCE YOU GIVE AN ID TO ANY ELEMENT IN HTML, JAVASCRIPT HAS ACCESS TO THAT ELEMENT - getElementsByTagName() - getElementById() … (most used) - getElementsByClassName() - Example 1 let link = document.body.getElementsByTagName("a"); console.log(link.href); - Changing the DOM - someNode.append(newNode); … attract to the end - someNode.prepend(newNode) - someNode.before(newNode); - someNode.after(newNode); - newNode.remove(); - Create Nodes - createTextNode() - createElement() - Attributes - getAttribute() - setAttribute() - Changing CSS - Example - let elem = document.getElementById("myid"); elem.style.fontSize = "12px”; - Accessing elements in HTML (Like CSS) - querySelectorAll() - querySelector() - We could then change the text in a node by using innerHTML or textContent properties. - Example let myDiv = document.getElementById("myDiv"); myDiv.innerHTML = "Hello!"; - Event Handling - Event Handlers Make it Possible to detect and react to events we have no direct control - Event Types - mouse events (e.g. click, mouseover, mousedown,mouseup, mouse move, mouseout) - key events (e.g. keypress, keyup, keydown) - load events (e.g. load, unload, beforeunload, DOMContentLoaded) … everything in the body is loaded to the browser - focus events (e.g. focus, blur) - Attaching Events - You can attach events directly in HTML (inline) as an attribute Link Link - Or using the DOM property with JavaScript document.getElementById("my-id").onclick = myFunction(); - Or using an event listener target.addEventListener("click", function() { some code}); - Mouse events also allow access to properties that tell you the mouse position. - Prevent Default Action - To prevent the default action we can use the “preventDefault()” method - Example Submit const btn = document.querySelector("button"); btn.addEventListener("click", function(event) { event.preventDefault(); console.log("Nope."); }); - Class - Same as in Java (class = constructor () = this. ) - Example 1 class Rectangle { constructor(height, width) { this.height = height; this.width = width; } calcArea() { return this.height * this.width; } } let rect = new Rectangle(20, 40); rect.calcArea(); // 800 - Spread (...name) - allows us to expand an array, string, or object expressions in places where key-value pairs are expected - Example function sum(x, y, z) { return x + y + z; } const numbers = [1, 2, 3]; console.log(sum(...numbers)); - Rest - The rest operator is similar to the spread operator but is used to put the "rest" of some specific user-supplied values into a JavaScript array, object, or function. Lecture 5 PHP (Hypertext Preprocessor) - A server-Side Scripting Language - And Powerful tool for making dynamic and interactive Web Pages - Recursive acronym for PHP (Current Version is PHP8.1) - Just like JavaScript (first-class function) - Executed on the server and returns plain HTML back to your web browser - File extension (“.php”) - Need a web server like Apache or Nginx and install PHP - PHP does have a built-in web server but this should never be used in production. - Generate an HTML - PHP runs on the server (very fast) … not running in the background constantly - Your browser takes the URL and looks up the servers IP address using DNS. Your browser then connects to that IP address and requests the given page. Your web server then nds that page and when found sends back a response with the contents to your browser where it is then displayed. - If the browser requests a.html le, that will usually return static content, so the server just sends that file. However, if a browser requests a.php file, that will execute the code in that file on the server before sending a response back to the browser - Client-side - code runs on your computer (in the web browser) - Examples - HTML - CSS - JavaScript/jQuery - ReactJS/VueJS/Angular - Server-side - runs on the webserver to generate a dynamic web page before it is sent back to the browser to be rendered. - Examples - PHP - Ruby on Rails (Based on Ruby) - Django, Flask (Based on Python) - Node.js (Based on JavaScript but runs on the server-side instead of client-side) - Tag - If a PHP file only contains PHP code then you don't need the closing tag. - (complex) - (short) - Data Types - String - Integer (e.g. 12) - Float (floating point numbers - also called double) (e.g. 3.59) - Boolean (e.g. true or false) - Array - Object - NULL - Operators - Arithmetic Operators ( +, -, *, /, %) - Comparison Operators ( ==, =!, ===, !==, , =) - “===” FOCUSES IT TO CHECK THAT THEY ARE NOT SIMILAR BUT TRULY THE SAME - Logical Operators (and, or, &&, II, !) - Comments - # or // (single line ) - (mutli-line comment) - Variables - Variable Names (starts variables with $ sign) - Must start with a letter and case-sensitive - Cant start with a number and Doesn't need you to define data types - Examples $variableName = "some value”; - Strings - String Concatenation - “.” or “.=” - Example $myString = "Hello ". "World!"; - String Interpolation - Way of embedding variables or expressions inside a string, so that the values are automatically inserted where you want them - This only occurs within a string with double quotes - Examples $message = "Hello my name is $name"; $message = "Hello my name is {$name}. How are you?"; - Common String Function - str_replace - used to replace parts of a string with something else - Example $text = "I like cats."; $newText = str_replace("cats", "dogs", $text); echo $newText; - strip_tags - removes all HTML and PHP tags from a string - Example $htmlString = "This is bold text."; $cleanString = strip_tags($htmlString); echo $cleanString; - strlen - returns the length of a string - Example $text = "Hello, World!"; $length = strlen($text); echo $length; - substr - Extracts a portion (substring) from a string…You can tell it where to start and how many characters to take - Example $text = "Hello, World!"; $subText = substr($text, 7, 5); echo $subText; // Outputs: World - strtoupper - converts all the characters in a string to uppercase - Example $text = "Hello, World!"; $upperText = strtoupper($text); echo $upperText; // Outputs: HELLO, WORLD! - strtolower - converts all the characters in a string to lowercase - Echo/Print - Two ways to output data to the screen: “echo” and “print” - Used to output data to the screen - The only difference between the 2 is that Echo can accept more than one argument and doesn't have a return value - Control Structures (Similar to JavaScript) - If/Else Statements - Can add or compare strings - While Loop $x = 1; while ($x ” $courses = array( "INFO2180" => "Web Dev 1", "COMP1126" => "Intro to Computing", "COMP1161" => "Object Oriented Programming"); - Length of An Array count($course) - Common Array Functions - in_array = checks if a specific value exists in an array. It returns true or false - array_pop = removes the last element from an array and returns that element - array_push = adds one or more elements to the end of an array. - sort = sorts the elements of an array in ascending order (from smallest to largest) - array_reverse = reverses the order of the elements in an array - SuperGlobals - Built-in variables always available in all scopes - $GLOBALS References all variables available in global scope - $_SERVER an array containing information such as headers, paths, and script locations. - $_REQUEST an associative array containing $_POST, $_GET, & $_COOKIE - $_POST an associative array of variables passed to the current script via the HTTP POST method. - $_GET an associative array of variables passed to the current script via the URL parameters. - $_FILES an associative array of items uploaded to the current script via the HTTP POST method. - $_ENV an associative array of variables passed to the current script via the environment method. - $_COOKIE an associative array of variables passed to the current script via HTTP Cookies. - $_SESSION an associative array containing session variables available to the current script. - Includes - Like import from Java - Takes code that exists in a file and copies it into the file that uses the include/require statement - “require” = will produce a fatal error and stop the script if it cannot find the file - “include” = will only produce a warning and the script will continue - You can also use “include_once” / ”require_once” statements. - Example include ‘filename.php’; - OOP (Object Oriented PHP) - PHP has a very complete set of object-oriented programming features like classes, abstract classes, interfaces, inheritance, constructors, cloning, exceptions, and more. - Visibility - There are three (3) types - public - can be accessed everywhere. public $public = 'Public'; - private - only be accessed by the class that defines member. protected $protected = 'Protected - protected - can be accessed only within the class itself and by inherited classes. private $private = 'Private'; - Form Processing Your name: Your age: Hi. You are years old - File Handling - With PHP we are also able to Open/Read and Create/Write files. - Open/Read = “fopen()” and “fread()” functions - Create/Write = “fopen()” and “fwrite()” functions - Good practice to close a file using “fclose()” - Sessions - Way to store info (in variables) to be used across multiple pages - Being remembered by servers (logging in ) … check for cookies to remind itself of who you are (sessions are used in place of cookies) - Despite many different users visiting your site. PHP can generate unique Session ID's for each of those users and store session information on the server - By default when using a website the web server typically does not know who you are or what you do because HTTP does not maintain state. - A good use for Sessions is for a system that requires a user to log in. - You start a session by using the “session_start()” function. - Session variables are then set using the $_SESSION superglobal. $_SESSION['fav_colour'] = 'blue'; - If you need to remove all global session variables and destroy the session, use “session_unset()” and “session_destroy()” - Debugging - When debugging your PHP code it is often good to turn on error_reporting and to set the display_errors option On at the top of your PHP file. (console.log in javascript) - “error_reporting” - “display_errors” - Example