PHP & MYSQL Fundamentals 2024 PDF
Document Details
Uploaded by WonderfulTrumpet
George Brown College
2024
Tiny Content
Tags
Summary
This document is a guide to learning PHP and MySQL fundamentals focusing on web development. It covers topics such as client-server interactions, HTTP, and web server setup. The document contains exercises, quizzes, and solutions to help in learning the material.
Full Transcript
PHP Building Blocks: Web Development Foundations © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) © 2024 NAISIT Authored by: Tiny Content ISBN: 978-1-927041-25-3 2|Page © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (...
PHP Building Blocks: Web Development Foundations © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) © 2024 NAISIT Authored by: Tiny Content ISBN: 978-1-927041-25-3 2|Page © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) Table of Contents Chapter 1..................................................................................................................................12 © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) Review Client-Server.............................................................................................................12 Why use Client-Server...........................................................................................................13 HTTP.....................................................................................................................................13 Web Servers..........................................................................................................................14 Setup Tools...........................................................................................................................15 Port Number......................................................................................................................15 htdocs Folder.....................................................................................................................16 Documentation......................................................................................................................17 Hello World............................................................................................................................19 Mini Exercise 1......................................................................................................................20 php.ini....................................................................................................................................22 Mini Exercise 2......................................................................................................................23 Mini Exercise 2 Solution........................................................................................................23 Maxi Exercise 1.....................................................................................................................25 Ch.1 Maxi Exercise 1 Solution...............................................................................................25 Ch.1 Test Your Knowledge....................................................................................................26 Ch.1 Test Your Knowledge Solution......................................................................................26 Ch.1 Quiz..............................................................................................................................27 Ch.1 Quiz Solution.................................................................................................................27 Terms....................................................................................................................................28 Chapter 2..................................................................................................................................29 RAM vs Drive........................................................................................................................29 Variables...............................................................................................................................29 Identifiers/Naming Convention...............................................................................................31 Naming Variables...............................................................................................................31 Naming Functions..............................................................................................................31 Naming Classes.................................................................................................................31 Constants..............................................................................................................................31 Mini Exercise 1......................................................................................................................32 Mini Exercise 1 Solution........................................................................................................32 3|Page Data types.............................................................................................................................32 Strings...............................................................................................................................32 Integers..............................................................................................................................33 © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) Floats/Doubles...................................................................................................................33 Booleans............................................................................................................................34 Mini Exercise 2......................................................................................................................36 Mini Exercise 2 Solution........................................................................................................36 PHP variable scope...............................................................................................................36 Numeric Arrays......................................................................................................................41 Indexing.............................................................................................................................41 Printing Arrays...................................................................................................................42 Assoc. arrays.........................................................................................................................42 Array Types...........................................................................................................................43 Multi-D Arrays........................................................................................................................44 Operators..............................................................................................................................46 Modulus.............................................................................................................................46 Exponent............................................................................................................................47 Equality..............................................................................................................................48 Logical Operators...............................................................................................................49 String Operators....................................................................................................................50 Mini Exercise 4......................................................................................................................51 Mini Exercise 4 Solution........................................................................................................51 HTML form review.................................................................................................................52 Sending Data with GET and POST....................................................................................52 Accessing Form Data.........................................................................................................53 Superglobals......................................................................................................................54 The MVC Pattern - Short Introduction................................................................................55 Built-ins.................................................................................................................................55 Mini Exercise 5......................................................................................................................56 Mini Exercise 5 Solution........................................................................................................57 Array functions......................................................................................................................58 Queue vs Stack.....................................................................................................................58 Maxi Exercise 1.....................................................................................................................59 4|Page Maxi Exercise 1 Solution.......................................................................................................60 Test Your Knowledge............................................................................................................64 Test Your Knowledge Solutions.............................................................................................64 © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) Quiz.......................................................................................................................................65 Quiz Solutions.......................................................................................................................66 Chapter 3..................................................................................................................................67 Conditionals..........................................................................................................................67 If statement........................................................................................................................67 Switch statement................................................................................................................67 Equality.................................................................................................................................69 Logical Operators..................................................................................................................70 Mini Exercise 1......................................................................................................................73 Mini Exercise 1 Solution........................................................................................................73 Loops....................................................................................................................................74 for......................................................................................................................................74 foreach...............................................................................................................................75 while..................................................................................................................................76 do … while.........................................................................................................................77 Break.................................................................................................................................78 end syntax.............................................................................................................................79 Test Your Knowledge............................................................................................................80 Test Your Knowledge Solution..............................................................................................80 Quiz.......................................................................................................................................81 Quiz Solution.........................................................................................................................82 Maxi Exercise 1.....................................................................................................................83 Case 1: Only 1 Item Checked out......................................................................................84 Case 2: More than 1 Item Checked out..............................................................................84 Maxi Exercise 1 Solution.......................................................................................................85 Terms....................................................................................................................................87 Chapter 4..................................................................................................................................88 More Built-ins........................................................................................................................88 String Functions.................................................................................................................88 Date Functions...................................................................................................................89 5|Page Writing Functions...................................................................................................................92 Return Values....................................................................................................................94 Mini Exercise 1......................................................................................................................95 © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) Mini Exercise 1 Solution........................................................................................................95 Anonymous Functions...........................................................................................................96 Pass-by-Value or Pass-by-Reference..................................................................................100 Strict Data Typing................................................................................................................102 Variable-Length Argument Functions..................................................................................104 Functions func_get_args() and func_num_arg()...........................................................104 Splat (…) operator...........................................................................................................105 Terms..................................................................................................................................108 Test your Knowledge...........................................................................................................109 Test your Knowledge Solutions...........................................................................................109 Quiz.....................................................................................................................................110 Quiz Solutions.....................................................................................................................111 Maxi Exercise 1...................................................................................................................112 Maxi Exercise 1 Solution.....................................................................................................113 Chapter 5................................................................................................................................116 An Organized App...............................................................................................................116 Web Page Burger................................................................................................................117 Burger Patty.....................................................................................................................117 Burger buns.....................................................................................................................118 The Chef..........................................................................................................................119 Chapter 5 Mini Exercise 1....................................................................................................121 Chapter 5 Mini Exercise 1 Solution......................................................................................122 What is MVC?.....................................................................................................................124 MVC framework...................................................................................................................125 Chapter 5 Maxi Exercise 1...................................................................................................126 Chapter 5 Maxi Exercise 1 Solution.....................................................................................127 Chapter 6................................................................................................................................131 File I/O.................................................................................................................................131 Where am I?........................................................................................................................131 File Pointer.......................................................................................................................133 6|Page TXT/CSV/True CSV.............................................................................................................133 File Permissions..................................................................................................................134 File Functions......................................................................................................................134 © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) Open and Close...............................................................................................................134 Read................................................................................................................................135 Write................................................................................................................................139 Mini Exercise 1....................................................................................................................140 Mini Exercise 1 Solution......................................................................................................140 Manage Files.......................................................................................................................141 Output Buffer.......................................................................................................................145 Flush................................................................................................................................145 Hashing...............................................................................................................................146 Race Conditions..................................................................................................................147 Chapter 6 Quiz....................................................................................................................150 Chapter 6 Quiz Solutions.....................................................................................................150 Chapter 6 Test Your Knowledge..........................................................................................151 Chapter 6 Test Your Knowledge Solutions..........................................................................151 Chapter 6 Maxi Exercise.....................................................................................................152 Chapter 6 Maxi Exercise Solution........................................................................................157 Terms..................................................................................................................................164 Chapter 7................................................................................................................................165 Cookies...............................................................................................................................165 Mini Exercise 1....................................................................................................................166 Mini Exercise 1 Solution......................................................................................................167 Session...............................................................................................................................168 Authentication with a Session..........................................................................................168 Chapter 7 Quiz....................................................................................................................170 Chapter 7 Quiz Solutions.....................................................................................................171 Chapter 7 Test Your Knowledge..........................................................................................171 Chapter 7 Test Your Knowledge Solutions..........................................................................171 Chapter 7 Maxi Exercise.....................................................................................................173 Chapter 7 Maxi Exercise Solution........................................................................................174 Terms..................................................................................................................................182 7|Page Chapter 8................................................................................................................................183 Object-Oriented Programming.............................................................................................183 Objects VS Classes.........................................................................................................183 © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) Properties and Methods...................................................................................................183 Access Modifiers.................................................................................................................184 Method Return Type............................................................................................................185 Define & Use Classes..........................................................................................................185 Mini Exercise 1....................................................................................................................187 Mini Exercise 1 Solution......................................................................................................187 Setters and getters..............................................................................................................188 Constructors........................................................................................................................189 Static Properties..................................................................................................................192 Constant Properties.............................................................................................................194 Magic methods....................................................................................................................195 __construct():...................................................................................................................195 __destruct():.....................................................................................................................196 __toString():.....................................................................................................................197 __clone():.........................................................................................................................198 __serialize() and __unserialize():.....................................................................................200 Inheritance..........................................................................................................................201 Chapter 8 Quiz....................................................................................................................205 Chapter 8 Quiz Solutions.....................................................................................................206 Chapter 8 Test Your Knowledge..........................................................................................207 Chapter 8 Test Your Knowledge Solutions..........................................................................207 Chapter 8 Maxi Exercise.....................................................................................................208 Chapter 8 Maxi Exercise Solution........................................................................................210 Chapter 8 Terms.................................................................................................................216 Chapter 9................................................................................................................................217 SQL Intro.............................................................................................................................217 Run SQL Server..................................................................................................................218 Table Setup.........................................................................................................................218 Limited Privileges................................................................................................................222 Test Web Server.................................................................................................................223 8|Page PDO Setup..........................................................................................................................225 PDO Fetch Options..........................................................................................................227 Output all Results.............................................................................................................228 © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) INSERT Example.............................................................................................................229 Mini Exercise 1....................................................................................................................232 Mini Exercise 1 Solution......................................................................................................232 MySQLi Setup.....................................................................................................................234 Chapter 9 Quiz....................................................................................................................236 Chapter 9 Quiz Solutions.....................................................................................................238 Chapter 9 Test Your Knowledge..........................................................................................238 Chapter 9 Test Your Knowledge Solutions..........................................................................239 Chapter 9 Maxi 1 Exercise...................................................................................................239 Chapter 9 Maxi 1 Exercise Solution.....................................................................................240 Chapter 9 Terms.................................................................................................................243 Chapter 10..............................................................................................................................244 Override Methods................................................................................................................244 Mini Exercise 1....................................................................................................................246 Mini Exercise 1 Solution......................................................................................................246 Final methods......................................................................................................................247 Final Classes.......................................................................................................................247 Interfaces............................................................................................................................249 Has-the............................................................................................................................250 Unrelated Classes............................................................................................................252 Mini Exercise 2....................................................................................................................253 Mini Exercise 2 Solution......................................................................................................253 Abstract...............................................................................................................................255 Quiz.....................................................................................................................................259 Quiz Solution.......................................................................................................................260 Test Your Knowledge..........................................................................................................260 Test Your Knowledge Solution............................................................................................260 Maxi 1 Exercise...................................................................................................................261 Maxi 1 Exercise Solution.....................................................................................................264 Terms..................................................................................................................................267 9|Page Chapter 11..............................................................................................................................268 Errors and Exceptions.........................................................................................................268 Errors vs. Exceptions...........................................................................................................269 © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) Properties........................................................................................................................270 Types of Errors....................................................................................................................270 Warning and Notice Errors...............................................................................................270 Parse (Syntax) Errors.......................................................................................................272 Fatal Error........................................................................................................................274 Bounds Checking................................................................................................................276 Range Checking..............................................................................................................276 Index Checking................................................................................................................276 Types of Exceptions............................................................................................................276 Display All Errors.................................................................................................................277 Uncaught Errors/Exceptions................................................................................................277 More Execution Jumps........................................................................................................281 Caught Errors and Exceptions (try-catch)............................................................................283 Throw Errors and Exceptions..............................................................................................285 Throw Error......................................................................................................................285 Throw Exception..............................................................................................................286 Custom Exceptions..............................................................................................................287 Regular Expressions...........................................................................................................289 Meta Characters..............................................................................................................291 Anchors..........................................................................................................................291 Replace...........................................................................................................................295 Mini Exercise 3....................................................................................................................295 Mini Exercise 3 Solution......................................................................................................295 Web Security.......................................................................................................................297 SSL Protocol....................................................................................................................297 Hashing Encryption..........................................................................................................299 Quiz.....................................................................................................................................302 Quiz Solution.......................................................................................................................304 Test Your Knowledge..........................................................................................................306 Test Your Knowledge Solution............................................................................................308 10 | P a g e Maxi 1 Exercise...................................................................................................................310 Maxi 1 Exercise Solution.....................................................................................................312 Terms..................................................................................................................................316 © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) 11 | P a g e Chapter 1 Review Client-Server © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) Let’s envision the process: You need a computer to visit a website. Let’s call it Computer A. This website’s code is stored on another computer, which we’ll call Computer B. Your computer sends a request to Computer B, asking for the website data (such as text, images, videos, etc). This request follows certain rules so that computer B can understand them. Then computer B sends a response back to you so you can view the website data on your computer. If someone spills water on computer B and destroys it, its website will also be inaccessible. Computer B will be running all day to make the website available. It is fast and has a large amount of storage space so that if 20 computers at once wanted to access its website, it could handle them all at once. In contrast, you can turn off your computer anytime and simply return to the website when you want. Your computer is likely slower and has less space - just enough to handle the response. In this example, Computer B acts as a server, and your computer acts as a client. Sends Request Client accessing website Web Server (Computer A) (Computer B) Sends back a Response Client Server Model The Client-Server model is the model described in the example above. The client sends requests to the server containing the website code, and then the server sends responses back so the client can view the website. 12 | P a g e Why use Client-Server The Client-Server model communicates between a browser and a website it visits. This is the primary reason for its existence, but it has some limitations, such as: © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) Traffic congestion on the web: There is a limit to the number of clients served at once by a single server computer. Traffic congestion can cause the web page to load slowly, or crash. Constant Maintenance: Once a website goes live, the server computer must constantly run to keep it live. Otherwise, users will not be able to access the website. Because of this, there needs to be someone maintaining the server at all times. Because the client and server portions of code are separate, one must decide: “Should this new piece of code be executed on the client or server?” For example, some programmers are hired to make software more efficient by reducing the amount of computation or memory required. A programmer can specifically store variables or perform calculations on the client computer (i.e., The client-side) instead of the server computer. Here are the things to consider when deciding where to put each piece of code: The server computer is often more powerful than the client computer. For example, if you want to run a website that runs a game with graphic content, the computations for the graphics should generally be running on the server side. The server computer often has more space than the client computer. Suppose you host a social media platform that will need to store many high-resolution photos. In that case, the photos will ultimately be stored on an external storage device connected to the server computer. The client's computer often has a lot of free cookie space for keys and other small pieces of information. Cookies use browser storage to save temporary, non-private data. The client's computer can access a resource more quickly if it is already on the client's computer. Therefore, if the content displayed on the website is rapidly changing, it might be helpful to save it temporarily on the client side. HTTP HTTP defines the rules and regulations for using the web. It stands for Hypertext Transfer Protocol. You’ll often see this acronym in the web development world. Even Client-Server Requests and Responses are called HTTP Requests and Responses. Both the Request and Response follow the rules and regulations set by HTTP. Let’s break this term down: 13 | P a g e Hypertext refers to the HTML code used on the web. Note: HTML is seen as text by the PHP interpreter but with more capabilities than regular text, which is why it is called hypertext. Transfer refers to the movement of code between the Client and the Server as © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) Requests and Responses are passed back and forth. Protocol refers to the rules and regulations surrounding the transfer of HTML between the Client and the Server. HTTP is most directly seen in the URL of any website. For example, if you visit Google on the browser, you would use the following URL: http://www.google.com/ The URL's first four letters indicate that the HTTP rules were used to visit this website. The connection between the Client and the Server could have also been secure. In this case, the URL would start with https instead. Web Servers Recall that you need a web server to interpret PHP code. We will set up both a local and a remote web server. We’ll use The local server, XAMPP, and the remote server, GBLearn, for different purposes. The local server allows you to test your code quickly but is not publicly accessible. In contrast, the remote server takes longer to connect to, but the web page is publicly accessible. See the table below for more differences between the local and remote servers. XAMPP (Local Web Server) GBLearn (Remote Web Server) Locally hosts your website Remotely hosts your website Is accessible only on your computer Is accessible publicly Use your computer's regular file browser (Finder Use FileZilla to move files to GBLearn under on Mac, File Explorer on Windows) to move files public_html/comp1230/ to the XAMPP/htdocs/dashboard folder 14 | P a g e XAMPP (Local Web Server) GBLearn (Remote Web Server) To start the server, go to your XAMPP controller To start the server, do nothing. GBLearn keeps (manager-osx in Mac, Control Panel in Windows) them always running. © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) To view, go to the browser and type in localhost To view, go to the browser and type in f1231231.gblearn.com, replacing f1231231 with your actual GBLearn username Local hosting is usually used for testing Remote hosting is usually used for deployment (getting a real client to buy or use the site) Setup Tools The applications you need to follow along with the exercises in this booklet are: 1. Download the Firefox browser (you cannot use any other browser because they are less developer friendly, and will show you unnecessary errors) 2. Download PHPStorm (or any other IDE or text editor) 3. Download FileZilla (or any other FTP client) 4. Download XAMPP 5. Create an account online at GBLearn.com Port Number If starting Apache on Windows XAMPP, you may need to add the port number on the browser’s URL: localhost:portnumber For example, if the port that is running Apache is port 80, add the following to the URL of the browser: localhost:80 You can find the port number on your XAMPP Control Panel/XAMPP Manager under the “Port(s)” heading. 15 | P a g e © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) htdocs Folder To run PHP code on the local web server, you must place the code within the xampp/htdocs/dashboard folder. Sometimes, the xampp folder is named differently on different operating systems. It may be called XAMPP in capital letters or another word variation. One way to find the folder is to look in the directory where you first downloaded XAMPP. You may need to restart the installation process to check the location where you installed xampp. You could also search for the htdocs folder on your computer in multiple ways: Search using your file browser search box Search using the Windows taskbar Search using the Mac Spotlight search One of these methods will likely reveal the location of htdocs. 16 | P a g e Documentation © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) Documentation is where you can find explanations and examples of how to use different PHP functionality. There are many aspects of PHP syntax (or any language syntax) that programmers are not meant to memorize. With the internet available at our fingertips, the smarter approach to programming is to remember and understand the concepts and be able to search for specific syntax when needed. If you visit https://www.php.net/manual/en/index.php, you will see the following web page: You can browse many different topics here. The expectation for a programmer is to be able to quickly search for the answer by using the documentation, so we will train you in this text to do the same. Take a moment now and read through the following section: Language Reference / Basic Syntax / PHP tags 17 | P a g e 18 | P a g e © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) Hello World As usual, we will start learning PHP by writing a simple “Hello World” application. However, to run this (relatively short) code, we will use our development software tools, which can be © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) difficult. Unlike HTML and JavaScript, the browser cannot interpret PHP code. It needs the web server. In the next chapters, we will explain tools such as PHP Storm, XAMPP, and GBLearn. Create a new file called ch1mini1.php and use the following code, replacing First-name Last- name with your actual first and last name. Most of the HTML tags should be familiar to you. We’ve introduced a new tag here: the PHP scope tag. Within this HTML tag, you can write PHP code that the server will interpret and execute. Example ch1mini1.php: Starting out with PHP Notice that you can embed the PHP scope tag within another HTML tag. What other tag(s) contain the PHP scope tag? The paragraph tag directly contains it. Indirectly, the html and body tags also contain the PHP scope tag. We are also introducing the PHP echo command here, which prints some words to the screen. In this case, the words “Hello World” will be shown on the screen on your webpage. Notice that the statement also contains a semicolon (;), which indicates the end of the statement. In the next chapters, we can use this code and a web server to make the website come to life. 19 | P a g e Mini Exercise 1 First, we’ll run the code on our local web server, XAMPP. To do this, complete the following steps: © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) 1. Move your ch1mini1.php into the xampp/htdocs/dashboard folder. 2. Next, open your XAMPP Control Panel / XAMPP Manager, and start the Apache server by clicking Start beside the Apache Server. You do not need to start any of the other servers. (ie. MySQL, ProFTP, Filezilla, Mercury, and Tomcat should be left as Stopped.) Next, open your XAMPP control panel or XAMPP manager to start the Apache Server. XAMPP Control Panel on Windows 20 | P a g e 3. Next, open the Firefox browser and type in localhost in the browser’s URL. It should look like this: © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) 4. Finally, click ch1maxi1.php to run our PHP file to see the following. Output: 21 | P a g e php.ini © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) This file, php.ini, is an initialization file, as the keyword “ini” indicates, for interpreting PHP on your web server. It contains some initial configurations. You can change different values for the configurations to change how errors will be displayed. Changing this file is not a simple task and will not be discussed in much detail here. However, let's briefly look at the file to understand it further: At the top of the file, we see the title and description of the file: If we scroll down past the explanations, we can find values that can be changed This is in what we call the key: value format, where the keys are keywords on the left, for example, “log_errors_max_len”, and values are on the right, for example, “1024”. You can generally read these configurations from top-down and left to right. But usually, we need to translate the sentence into something more human-readable. For our example, the translation would be: “For logging errors, the maximum length is 1024 bits based on this php.ini file.” 22 | P a g e Mini Exercise 2 1. First, locate your php.ini file. It should be within the XAMPP folder in the original installation location. You can simply search for the file within this folder. If you’re having © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) trouble searching for the file, try these locations: Windows: C:\xampp\php\php.ini Mac: Applications/XAMPP/etc/php.ini If you still cannot find it, search online using the following keywords: a. php.ini b. location And these extra keywords to indicate your: c. Operating system (Windows, Mac, Linux) d. XAMPP version If you put it all together, your keyword search may look something like: “php.ini location Windows 10 XAMPP”. Look through the first few results and try to find your answer. 2. Open up php.ini and locate a different key and value (different than the example shown in this text). Write the answer in this format when submitting your work. Key: ____________ Value: ____________ 3. Take a screenshot of this Key and Value in php.ini 4. Write the translation of the configuration Key and Value you chose. Mini Exercise 2 Solution 1. The answer varies based on the operating system. 2. Various answers are accepted here. This is one example: 3. Key: ignore_repeated_errors Value: Off 23 | P a g e 4. Show repeated errors (i.e. Ignoring repeated errors is turned off) © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) 24 | P a g e Maxi Exercise 1 1. Show “Hello universe” to the screen using PHP. You can use HTML skeleton code to do this. © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) 2. Take a screenshot of your code running live in XAMPP, and make sure the URL is visible in the screenshot. The URL should contain something like “localhost”. 3. Next, take a screenshot of your code running live on GBLearn, and make sure the URL is visible again in the screenshot. The URL should contain something like https://123123123.gblearn.com/ where 123123123 is an example of a GBLearn user ID. Ch.1 Maxi Exercise 1 Solution 1. The code solution is to use the template from Mini Exercise 1, and change the line: echo "Hello Universe"; 2. Output: 3. Output: 25 | P a g e Ch.1 Test Your Knowledge 1. Which one of our web servers can make your web page publicly viewable? (ie. So that your friend in Korea can also view your web page) © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) 2. What is PHP documentation? a. Give a situation in which you would look at the PHP documentation. 3. What is the difference between a Request vs a Response? How are they related to HTTP? Ch.1 Test Your Knowledge Solution 1. Apache on GBLearn 2. The PHP documentation describes the concepts and syntax of PHP code a. Situation: Imagine you have forgotten the PHP command for printing to a screen (echo command), so you could look it up in the documentation. 3. A Request is sent by the client, asking to view (or interact with) a web page. The server sends back a response to provide the resources that the client wants. Both the Request and Response follow the rules and regulations set by HTTP. 26 | P a g e Ch.1 Quiz 1. What is php.ini? a. A configuration file to solely view some different values for how to run XAMPP © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) and interpret PHP code b. An HTML file that should be used as a default landing page c. A configuration file to set some default values for how to run XAMPP and interpret PHP code d. An HTML file that should be used only if we have errors in the rest of our web page code 2. Which one of our web servers is only viewable on your private computers? a. Apache on XAMPP b. Apache on GBLearn 3. How do you open (and close) a PHP scope in the middle of an HTML file? a. b. c. d. 4. T/F. You should memorize all of the PHP documentation. 5. What is Apache? a. A database server b. A web server c. A program that can launch and integrate both a web server and a database server Ch.1 Quiz Solution 1. c. 2. a. 3. d. 4. F 5. b. 27 | P a g e Terms Resource - A computer, software, hardware, or device can provide many different resources. However, the two primary computer resources are memory space and processing power. © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) HTTP - The rules and regulations of the web and how to send requests and responses between clients and servers. PHP Initialization - The preparations of some starting values for PHP Documentation - Pages of information (physically in a textbook or digitally online) describing the concepts and syntax of a programming language Client - The computer that sends a request to the server computer to access resources on the web Server - The computer that returns a response to the client's computer, providing resources that the client requested 28 | P a g e Chapter 2 RAM vs Drive © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) The RAM, which stands for Random Access Memory, is the computer's short-term memoy. In contrast, the Drive is a memory space on the computer used as long-term memory. The computer uses the RAM space to run a program in real-time and temporarily holds the values being inputted, outputted, or used for calculations. The computer uses the Drive to save the programming code used to run the program in the first place. For example, suppose that the Google Chrome browser is closed on your computer and you are not currently using it. As long as the application is installed, the code for the application is stored on the Drive. Once you open a browser tab, a default web page will open. Suppose that the default web page is Google Search, and you type something into the search bar. This is a very specific instance of you using the application (it has a specific time stamp, this specific web page, and your specific search), and the information is only needed temporarily. This specific information is stored in the RAM. Drive RAM Stored for a Stored for a long period of short period of time. time, specific to this use. Eg. Stores the programming Eg. Stores code to run the timestamp, Google Chrome. the web page, and the search Drive VS. RAM Variables Variables are containers in programming that can hold different (and changing) values. The word "variable" itself means changeable. To create a variable in PHP, you must start it with a 29 | P a g e dollar sign ($), and you can assign it a value using the equal (=) sign. Below, you’ll see examples of four different variables. Example variables.php: © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) $name = "Julien"; $age = 25; $weight = 160.48; $alive = true; Each variable will be assigned a location in the RAM. If you change the value of a variable, the space in RAM will not change; only the value will. Let’s see this in diagram form: RAM Address 0x04 0x08 0x0C 0x10 Variabl $name $age $weight $active e Value “Julien” 25 160.47 true New “Jules” Value Variables being saved and updated in the RAM 30 | P a g e Identifiers/Naming Convention Identifiers are names given to variables, functions, constants, and classes. © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) Naming Variables Variable names are required to start with the dollar sign, $, and should be descriptive. For example, a variable named $cost is easier to use than a variable called $c. Variable names are also case-sensitive. For example, the variables $name and $Name are considered different with separate memory spaces. A number cannot be used as the first character following the dollar sign, $, but can be used afterward. For example, $2user is not a valid variable name, but $user2 is. Naming Functions Functions names should have underscores between words. Function names are not case- sensitive but should be descriptive. Naming Classes Class names can be in either camelCase or PascalCase. Class names are not case-sensitive but should be descriptive. Constants Constants define values that cannot be changed and logically should not be changeable, such as PI or other mathematical constants. Constants can be defined in two different ways. However, it is more convenient to use the const keyword because it can be used inside and outside of a class definition. const TAX = 0.1; Or 31 | P a g e define("TAX", "0.1"); © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) Mini Exercise 1 Are the following two lines of code legal? Explain what is happening in the memory space (in the RAM). Draw the new diagram, continuing on the diagram given in the example. $weight = 160.48; $weight = 174.12; Mini Exercise 1 Solution Yes, they are legal. A memory address is created for the first line of code. On the second line of code, the old value will be crossed out (160.48), and the new value will be added below (174.12). RAM Address 0x04 0x08 0x0C 0x10 Variabl $name $age $weight $active e Value “Julien” 25 160.47 true New “Jules” 174.12 Value Variables being saved and updated in the RAM Data types Strings A string can hold a character, word, or sentence. Because a space is considered a character, sentences are also considered strings. You can also have numbers and special characters within a string. Let’s see some examples of strings: Example strings.php $first_name = "Julien"; 32 | P a g e $first_name = "Jules"; $last_name = "Bagra"; $email = "[email protected]"; $password = "#nk4(..sñs"; © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) How many different memory addresses are used for the code above? Only four. Why? Because $first_name is used twice. The computer simply changes the value at the same address. Integers An integer is a counting number, such as 0, 1, 2, 3, etc. Integers can also be negative or positive numbers. Let’s see some examples of integers: Example integers.php: $card_number = 9947305288; $phone_number = 18002652002; $num_items = 16; Floats/Doubles Unlike some other programming languages, there is no difference between a float and a double in PHP, so from here on, we will refer to them as floats. A float contains a decimal number (i.e. a fraction value). When you create a float, the computer will allocate a large amount of memory space to allow for high-precision calculations. Let’s see some examples of floats: Example floatDouble.php: $cost = 188.99; $tax = 0.13; $discount = 0.05; Precision Loss Precision loss happens when you need more decimal places than you can store. Because modern computers can store many decimal places, problems will not arise for most applications. However, if a large number of decimal places are used, problems can arise when checking if two doubles are equal since the two doubles may be stored with slightly different values. 33 | P a g e To test if two doubles are equal, use an epsilon. An epsilon is a very small amount used to compare with the difference of the two doubles. The epsilon is used to determine how small the difference between the two doubles should be, so that as long as the two doubles are close enough to each other, they will be considered equal. In this example, use the following value for © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) epsilon: $epsilon = 0.0000001; The value for epsilon will change based on your program and how much precision you need. In the code below, we will check if it has enough precision for 7 decimal places. Example precisionLoss.php: $firstDouble = 1.12121121; $secondDouble = 1.12121120; $epsilon = 0.0000001; if(abs($firstDouble - $secondDouble) < $epsilon) { echo "The doubles are equal (within 7 decimal places)"; } else { echo "The doubles are not equal (within 7 decimal places)"; } // Output: "The doubles are equal (within 7 decimal places)" Notice that the code above uses the function abs() to get the absolute value (positive value) of the difference of the doubles. This is because the first double may be larger or smaller than the second, resulting in a negative or positive number. The function abs() will always return a positive number, which can be compared to epsilon (Since epsilon is positive). The point is that it is larger or smaller by such a small amount that they can be considered equal. Booleans Boolean variables can only contain true and false values. To experience the need for this type of variable yourself, ask your friend this question: "Does PHP have different data types?" 34 | P a g e The answer is either YES or NO. This can be mapped as YES -> true and NO -> false. We use this variable type when we want to force the answer to be one or the other, with no options in between. We can use booleans as conditions by asking a YES/NO question and checking the boolean’s value. © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) Example booleans.php: $active = true; $high_cholesterol = false; $diabetic = true; 35 | P a g e Mini Exercise 2 Define the following variables, giving them appropriate variable names. Beside each variable definition, add a comment stating its data type. © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) A variable representing whether the user has health insurance. Initialize to true. A variable representing the user’s current eye color. Initialize to green. A variable representing the user’s age. Initialize to 27. A variable representing the user’s glasses prescription. Initialise to: 0.5. Mini Exercise 2 Solution $insurance = true; // Boolean $eye_color = "green"; // String $age = 27; // Integer $prescription = 0.5 // Float/Double PHP variable scope There are two main locations (i.e. scopes) where a variable can be defined: In the main execution or within a function. Although we will go over functions more in detail in future chapters, we will only briefly introduce them here for context. Each function, i.e. a block of code between a pair of curly brackets ({}), has its own separate scope. If a variable is defined in one scope, it is not available in another scope. The main execution is the main code area, (ie. the first level of tabbing) (ie. the scope outside of any function). See the code example below for the difference between the main execution and the function scope: Example scope.php: // Main execution $cost = 5.66; function greet(){ // Function scope $cost = 8.66; return $cost; } echo "In the main execution scope, the cost is $cost"; echo "From the function scope, the cost is ". greet(); 36 | P a g e See the diagram below to see what is happening in the RAM: RA © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) M Scope Main Exe. Function Address 0x04 0x08 Variable $cost $cost Value 5.66 8.66 New Value Memory addresses for $cost are different in the Main Execution vs the Function. As the table above shows, If you create variable $cost in the main execution and then again in the function, these are considered two different scopes and, therefore, two different addresses in memory as well. Confusing the scope of a variable can cause problems. For example, an error can occur if you define a variable in the main execution and then try to access it in the function scope. Example scope2.php: // Main execution $cost = 5.66; function greet(){ // Function scope echo $cost; // Causes an error because $cost is not defined in this scope $cost = 8.66; echo $cost; } 37 | P a g e RAM © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) Scope Main Exe. Function Address 0x04 Variable $cost Value 5.66 New Value If there is no $cost variable in the function scope, it cannot be accessed from there. We have seen that variables can be defined in different scopes. Now, a variable’s scope can additionally be defined as: Local: If a variable is defined only in scope A, it cannot be accessed in scope B. For example, if a variable is defined in a function, it is not accessible from the main execution. This is what we have seen in the code above. Global: The variable can be accessed everywhere. No matter where the variable is defined, the variable is available in the main execution and in all functions. Example global.php: $num_stars = 2; $num_coins = 8; function print_coins() { global $num_coins; echo $num_coins; // Works without error } print_coins(); // Output: 8 38 | P a g e RAM Scope Main Main Exe. AND © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) Execution Func. Address 0x04 0x08 Variable $num_stars $num_coins Value 2 8 New Value Global variables in the RAM Static: The variable is defined in scope A. It cannot be accessed in scope B. However, it is not deleted from RAM after scope A closes. For example, if there is a static variable defined in a function and you call the function twice in a row, the variable is not deleted from memory between the two function calls. Take a look at the code below. The first function uses the static keyword for its $counter variable so that it can perform its task of increasing the counter every time the function is called. The second function, however, repeats the same operation of setting $counter to 1 and resets from the beginning. Example static.php: // Increases the counter by one, every time the function is called function incCount() { // Inside a function, static means: // The variable will keep its value each time the function is called during the life of the page load static $counter = 1; echo "You have called this function $counter times"; $counter++; } function BuggyResetCount() { echo "Count is reset to 1 "; $counter = 1; } BuggyResetCount(); // Prints 1 incCount(); // Prints 1 incCount(); // Prints 2 BuggyResetCount(); // Prints 1 // But it does not change the existing value 39 | P a g e of static $counter variable; incCount(); // Prints 3 incCount(); // Prints 4 © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) incCount(); // Prints 5 RAM Scope inc_counter rep_counter Func. Func. Address 0x04 0x08 Variable $counter $counter Value 1 1 New Value 2 New Value 2 1 New Value 2 New Value 3 1 New Value 2 Static variables in the RAM Although we favor code that uses functions designed to reset their operations each time they are called, there are valid cases (like the one above) where you should use the static keyword. In other words, favor code without the static keyword, but use it when needed. 40 | P a g e Numeric Arrays An array is a data type containing multiple items rather than just one. An array can contain any data type within it. In contrast, remember that strings, integers, floats/doubles, and booleans can © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) contain only one value at a time. If you change the value, it will overwrite the old value. Arrays, however, can have multiple values added to them at a time. Let’s see some examples of arrays: Example numericArrays.php: $friends_list = ["Katie", "Casey", "Damon", "Melanie"]; $connect_score = [9.77, 8.5, 8.4, 2]; $age = [25, 26, 25, 22]; $best_friends = [true, true, false, false]; We will see how to insert, delete from, and generally manipulate arrays in future chapters. Indexing To get a value from an array, you need to index into it. In most programming languages, the syntax for indexing uses square brackets ([ ]). Next, you need to use an index to indicate which array value to access, as in most programming languages, array indexing starts at zero. For example, to access the first name in the friends_list, ie. "Katie", you can do the following: Example indexing.php: $friends_list = ["Katie", "Casey", "Damon", "Melanie"]; $best_friends = [true, true, false, false]; $first_friend = $friends_list; // Output: "Katie" echo $first_friend; Which index must I use to check whether or not "Damon" is considered a best friend? Example indexing.php: $best_friends = [true, true, false, false]; $damon_is_bf = $best_friends; echo $damon_is_bf; // Output: false but results in blank output 41 | P a g e Printing Arrays To print the elements of an array, you cannot use echo and can print_r() instead. © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) For example, with the following PHP code, we are using echo incorrectly: $friends_list = ["Katie", "Casey", "Damon", "Melanie"]; echo $friends_list; And so you would see the following Warning: Warning: Array to string conversion Whereas with the PHP code below: $friends_list = ["Katie", "Casey", "Damon", "Melanie"]; print_r($friends_list); You will see the following output: Array ( => Katie => Casey => Damon => Melanie ) Assoc. arrays Associative arrays are indexed using keys (usually keys with a string data type) instead of indexing with increasing counting numbers 0, 1, 2, 3, etc. Keys can also be integers or floats, but most commonly, they are strings so that they can easily be used to identify each element in the associative array. For example: Example assocArray.php: $pot_luck = [ "ricky" => "salmon", "xi lao" => "pizza", "maryam" => "salad" ]; $num_friends = [ "ricky" => 2, "xi lao" => 1, "maryam" => 1 42 | P a g e ]; $pot_luck["xi lao"] = "sushi"; echo $num_friends["maryam"]; © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) To access these values, we use the keys to index into the array. For example, to change Xi Lao’s potluck contribution from "pizza" to "sushi", use the following code: $pot_luck["xi lao"] = "sushi"; To print out the number of friends that Maryam is bringing to the dinner party, use the following code: echo $num_friends["maryam"]; Array Types When should you use a numeric vs an associative array? Use associative arrays to store information that could be stored in a table or on a graph with two dimensions. In contrast, use numeric arrays when you only want to store a row of information. For example, let’s save the employee information into a numeric array. See the disadvantages: $emp_100999885 = ["Sarah Ahmet", true, 4, 7, 65.78]; Is it clear what the second element in the array above, the value true, stands for? Is what the 4 and 7 stand for obvious? Let’s see this same data stored in an associative array. Example arrayTypes.php: $emp_100999885 = [ "Name" => "Sarah Ahmet", "Manager" => true, "Rank" => 7, "Hourly" => 65.78 ]; It is now very clear what this data represents. However, it also takes up more space to save both the keys and the values in memory instead of just using numeric indexing. Depending on the situation, the trade-off may be worth it. 43 | P a g e Multi-D Arrays A numerical or an associative array can be 2-dimensional by containing another array within it. A numerical array can contain an associative array and vice versa. You can use more than two © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) dimensions to make a multi-dimensional array. See the code below for an example of a 2- dimensional associative array. Notice that you must use an extra set of square brackets for every dimension to index into the array. See the code below for the file multiArray.php. Example multiArray.php: $emp_100999885 = [ "Name" => "Sarah Ahmet", "Manager" => [ "Senior" => "Hoichi Chan", "Junior" => "Ingrid Xu" ], "Rank" => 7, "Hourly" => 65.78 ]; $senior = $emp_100999885["Manager"]["Senior"]; $junior = $emp_100999885["Manager"]["Junior"]; $emp_name = $emp_100999885["Name"]; echo "$emp_name associates senior associate: $senior junior associate: $junior."; Output: The next code example has a multidimensional array called $accessories. Based on the keys "headphones" or "chargers", each element contains a numerical array. This numerical array represents the 2nd dimension of the greater array. The zeroth index contains an associative array representing the first headphone brand. This 3rd dimension of the greater array has the brand "Anker", and the price is 15.99. See the code below for multiArray2.php. Example multiArray2.php: 44 | P a g e $headphone_brands = [ [ © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) "brand" => "Anker", "price" => 15.99 ], [ "brand" => "Logitech", "price" => 129.99 ], [ "brand" => "Jabra", "price" => 189.99 ] ]; $charger_brands = [ [ "brand" => "Aukey", "price" => 40.00 ], [ "brand" => "Google", "price" => 34.99 ], [ "brand" => "Apple", "price" => 169.00 ] ]; $accessories = [ "headphones" => $headphone_brands, "chargers" => $charger_brands ]; // Assume that the user chose Aukey Headphones and you need to display the price $brand_chosen = $accessories["headphones"]["brand"]; $price_chosen = $accessories["headphones"]["price"]; echo "$brand_chosen is $$price_chosen"; 45 | P a g e Output: © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) Operators There are different kinds of operators, but most of them remind us of mathematics. These operators are the only maths required for this course, however. We’re not going to review the four basic operators, +, - *, /, with an expectation that you are familiar with them. Let’s evaluate the last two symbols. Operator Name + Addition - Subtraction * Multiplication / Division % Modulus ** Exponent Modulus The modulus (%) symbol represents the remainder after a division operation. Example modulus.php: echo 8 % 5; // Prints 3. This is because 8 divided by 5 is 1 with a remainder of 3. echo 5 % 8; // Prints 8. This is because 5 divided by 8 is 0 with a remainder of 5. echo 5 % 5; // Prints 0. This is because 5 divided by 5 is 0 with a remainder of 0. echo 11 % 2; // Prints 1. This is because 11 divided by 2 is 5 with a remainder of 1. 46 | P a g e Exponent The exponent (**) symbol represents taking a number to the power of another. © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) Example exponent.php: echo 1 ** 2; // Prints 1. This is because 1 to the power of 2 is equal to 1 multiplied by 1 which is equal to 1. echo 2 ** 3; // Prints 8. This is because 2 to the power of 3 is equal to 2 multiplied by itself 3 times, which is equal to 8. Mini Exercise 3 How can you use modulus to find an even number? Mini Exercise 3 Solution You can use modulus 2 to check if the remainder is 0 or 1. If the remainder is 0, the number was even. Otherwise, it was odd. 47 | P a g e Equality The assignment operator (=) is another basic and important tool in the PHP syntax. It is used to set the variable's value on the left side to the result of the calculation on the right side. © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) See the following compound assignments below for more ways to use the assignment operator (=): Compound Assignment Expanded Assignment x=y Not Applicable x += y x=x+y x -= y x=x-y x *= y x=x*y x /= y x=x/y x %= y x=x%y 48 | P a g e Logical Operators We will use the following table with an example code to clarify it. Let us assume that it is sunny © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) today and that it is a weekend. Now, we will check some conditions, each with an output statement that will print only if the condition is true. For example, let’s go through the conditions in the code example below, noticing that we are assuming it is a sunny weekend below. Remember, 1 represents true, and 0 represents false. Example logicalOperators.php: $sunny_today = true; $weekday = false; echo $sunny_today or $weekday. ""; // Outputs 1 because only one of the variables needs to be true, but both can be true echo $sunny_today and $weekday. ""; // Outputs nothing, because both need to be true echo $sunny_today xor $weekday. ""; // Outputs 1, because only one of the variables can be true echo !$weekday; // Outputs 1, because the opposite of false is true Operator Name Example Result and And $sunny_today True if both $x and $y are && and $weekday true $sunny_today && $weekday or Or $sunny_today or True if either $x or $y is true || $weekday or if both are true $sunny_today || $weekday xor Xor $sunny_today True if either $sunny_today xor $weekday or $weekday is true, but not both 49 | P a g e ! Not !$sunny_today True if $x is not true (i.e. false) © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) String Operators Although we usually perform maths on numbers, we can use operators to manipulate strings. The concatenation operator, For example, we can use the concatenation operator to attach a first name and a last name with a space between them: Example concat.php: $first_name = "Jane"; $last_name = "Hinkle"; $full_name = $first_name. " ". $last_name; We could also add a qualification to the $full_name variable using the concat compound assignment operator (.=). $full_name.= " PhD"; 50 | P a g e Mini Exercise 4 What would be the expanded version of the code? Check the documentation online for what this © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) compound operator does. $full_name.= " PhD"; a) $full_name = $full_name. " PhD"; b) $full_name = "PhD ". $full_name; Mini Exercise 4 Solution a. The concat compound operator (.=) appends the value on the left to its existing value. This means that it strings the string at the end of its value. Array Operators Here, we have listed some important ones, but always see the documentation for the full list. Operator Example Result + $arr_1 + $arr_2 It will create a single array that contains the values $arr_1 and afterward the values of $arr_2 == $arr_1 == $arr_2 Returns true if $arr_1 and $arr_2 contain the same keys and values 51 | P a g e HTML form review HTML forms are virtual forms where users can fill out their information online. For example, we can use a form to register a user on a website. In this case, the website may ask for the user’s © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) email, desired username, and desired password. The HTML code for the page "registration.php" may look something like this. Example formReview.html: E-mail: Username: Password: Sending Data with GET and POST Recall that whatever values are entered into the form are available to the next script ("home.php"). This behavior is how we can access the user’s email, username, and password and store them in the system’s database for validation. Notice that we can specify the form’s action attribute, determining where the browser sends the form data once the user presses the submit button. We can also specify whether the form should use the GET or the POST method. The POST and GET methods temporarily store the values into global variables accessible by the next script, but the GET method also displays values in the URL. For this reason, the POST method is considered more secure. If you don’t remember the differences between GET and POST, pause now and review it on your own. There are many different forms possible on a given website. A registration form is just one example. We must not use the GET method because we used a registration form and received a password as user input. In contrast, if we used the form to set search filters on an online store, we would want the filters displayed in the URL. This is because the search filters would display 52 | P a g e a different set of items on the web page based on these choices. We can use the GET or POST method based on the situation. © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) Accessing Form Data Imagine that the user lands on the Login page, login.php. Once the form is submitted, the action attribute of the form directs the user to home.php, passing on the values of all input elements to the new page. login.php: Username: Output: To access the values that were entered into the form, use superglobals such as $_GET and $_POST, using the name of the original input element as the key: profile.php: Welcome to your profile: Output: 53 | P a g e © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) Superglobals The superglobals are associative arrays where the keys match the name attributes of the corresponding inputs. The three names we had in "registration.php" were "email", "username", and "pass", and we can access all three of these. See the script "home.php" below for the code: Example superglobals.php: Welcome Your email address is: Your password is: This page is where we can find the user-provided values. The $_POST superglobal variable and its counterpart $_GET are called superglobals because they are accessible in any scope. If we had used the GET method in "registration.php", we would have used the $_GET superglobal variable in "home.php". However, recall that the GET method displays its values in the URL. Would you want a password displayed in the URL? Definitely not. 54 | P a g e There are many other superglobal variables in PHP. However, we will introduce only one more here: $_REQUEST. $_REQUEST contains both parameters sent via the GET or POST methods. © 2024 - All Rights Reserved. Custom Copy for Fidan Zeynalli (GBC) The MVC Pattern - Short Introduction A widely used alternative to using the action attribute to pass form data between files is to use the MVC pattern. In this pattern, use the GET method to include the desired web page by using an include statement in the code in the currently running script. This way, the user will view and interact with multiple pages, such as the home page, the login page, the products page, etc, without having the problem of controlling the web page flow with the action