Be ready to study forever - 개발자 꿈나무
[대학교 자료정리]Fundamental PHP 본문
Lecture 1 - An Overview and Introduction to Web Application Development
1. Internet
It is a massive network of networks. Internet is interconnected network of computer and network devices with TCP/IP protocol
TCP – handles the messages
IP – handles the delivery
The Basic Protocols of the internet:
· TCP/IP
· IP Address
· DNS
· URL & URI
· MIME
DNS – Domain Name Systems
DNS look up the IP Address of the website and translate it from URL to IP address of website
HTTP (HyperText Transfer Protocol) – a way of accessing information over the internet
Client (browser) – make HTTP request and TCP/IP deliver it to the web server
Web server – receive HTTP request and make HTTP response and TCP/IP deliver it to the browser (client)
URLs – Uniform Resource Locator
Also commonly referred to as a Web address. URL is a type of URI(Uniform Resource Identifier)
Web server
Apache HTTP server (apache)
Microsoft Internet Information Services (IIS) for windows
2. Web Development
Web Communication Protocols
URL – consist of two part. A protocol(usually HTTP) and either Domain name or a web server’s internet protocol address
Ex) https:// <- protocol, www.google.com<- Domain name
Host - refers to a computer system that is being accessed by a remote computer.
Domain name - is a unique address used for identifying a computer such as a Web server on the Internet
Domain Identifier - identifies the type of institution or organisation (.biz, .com, .edu, .org)
Internet Protocol (IP address) - another way to identify computers or devices connected to the Internet
HTTP – is a component of TCP/IP (Transmission Control Protocol/Internet Protocol)
HTTPS (Hypertext Transfer Protocol Secure) - provides secure Internet connections for transactions that require security and privacy
3. Publishing Website
Web Hosting - The publication of a Web site for public access. Internet access (cable modem, DSL, satellite, dial-up modem, ISP)
Internet Service Provider (ISP) - Provides access to the Internet along with other types of services such as e-mail. America Online, CompuServe, and EarthLink
Domain name - a unique address used for identifying a computer, such as a Web server on the Internet. A popular domain name registrar is Network Solutions. After you register your domain name, notify your ISP of your domain information
File Transfer Protocol (FTP) - a TCP/IP protocolused for transferring files across the Internet. Transfers files between an FTPclient (your computer) and an FTP server(a server capable of running FTP). Allows you to use your browser to log on to an FTP server and upload your files.
Ex) WinSCP
4. Client/Server Architecture
A system consisting of a client and a server is known as a two-tier system
Lecture 2 - Data Types and Operators
1. Data Type and Variables
Variable - Can include letters (A to Z, a to z) and numbers (0 to 9) or an underscore (_) … but cannot start with a number. Case sensitive,
Constant - A constant contains information that does not change during the course of program execution. Constant names do not begin with a dollar sign ($). Can be string, Boolean, number.
Ex) define("CONSTANT_NAME", value);
Type Casting - $newVariable = (new_type) $oldVariable;
Ex)
$speedLimitMiles = “55 mph”;
$speedLimitKilometers = (int) $speedLimitMiles * 1.6;
2. Arrays
Creating Array
$array_name = array(value1, value2…); OR
$array_name[ ] = value1;
$array_name[ ] = value2;
$array_name[ ] = valueN;
Print_r ($array_name) - Use to print or return information about variables. Return index and values together.
Modifying array
$array[0] = “value”;
3. Operators
4. Operator precedence
Operator precedence - refers to the order in which operations in an expression are evaluated.
Associativity - the order in which operators of equal precedence execute.
Lecture 3 – Functions and Control Structure
1.Function – a group of statements as a single unit
Function Syntax
Function name_of_function($parameter1, $parameter1){
Statement;
Return $value;
}
2. Variable Scope
Global variable - one that is declared outside a function and is available to all parts of your program.
Local variable - declared inside a function and is only available within the function in which it is declared.
Static variable - declared inside a function but it is not deleted after the function executes (still local to the function).
Global Keyword
In PHP however, we need to use the global keyword to declare a global variable in a function where you would like to use it.
EX)
functiontestScope() {
global $globalVariable;
echo "<p>$globalVariable</p>";
}
3. If statement
Syntax:
If(condition1){
Statements;
}
Elseif(condiiton2){
Statements;
}
Else{
Statements;
}
4. Loops
While
Syntax:
$count = 1;
while ($count <= 5) {
echo "$count<br>";
$count++;
}
Do While
Syntax:
$count = 2;
do {
echo "<p>The count is equal to $count</p>";
$count++;
} while ($count < 2);
For
Syntax:
for ($count = 0; $count < 5; $count++) {
echo $fastFoods[$count], "<br>";
}
Foreach
Syntax:
$daysOfWeek = array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");
foreach ($daysOfWeek as $day) {
echo "<p>$day</p>";
}
Lecture 4 – Strings
1. Handling Form Submission
$_GET[“”] – Appear in URL
$_POST[“”] – Not Appear in URL
Isset( ) – whether the variables declared Return TURE if yes
Empty( ) - whether the variables is empty TURE if yes
Is_numeric( ) – whether the variable is numeric value TURE if yes
Mail( ) – returns TRUE if a message was delivered or FALSE if failed
Syntax:
mail(recipient(s), subject, message[, additional_headers])
Ex)
$to = “amolnar@swin.edu.au";
$subject = "This is the subject";
$message = "This is the message.";
$headers = "From: Andreea Molnar <amolnar@swin.edu.au>";
mail($to, $subject, $message, $headers);
2. Manipulating Strings
Concatenation operator .
Ex) echo”<p>”.$variable.”</p>”;
Concatenation assignment operator .=
Ex) $name .=”Hi,”;
Complex String Syntax
$variable = “tomato”;
Echo”this is {$veriable}s”;
3. Comparision String
ASCII Code–range of 0 to 255. A(65) to Z(90), a(97) to z(122). So can be compared in if statement
String Comparision Functions
Strcasecmp($string1, $string2) - performs a caseinsensitive comparison of strings. returns TURE or FALSE
Strcmp($string1, $string2) - performs a case-sensitive comparison of strings.returns TURE or FALSE
Similar_text($string1, $string2)- returns the number of characters that two strings have in common.
Levenshtein($string1, $string2)- returns the number of characters you need to change for two strings to be the same.
4.Parse String- extracting characters or substrings from a larger string.
Strlen($string) - returns the total number of characters in a string.
Str_word_count($string)- returns the number of words inside a string.
Strpos($email, “@”) - Performs a case-sensitive search and returns the position of the first occurrence of one string in numeric value.
Strchr($string, “c”)- Parameters are the string and the character for which you want to search. return a substring from the specified characters to the end of the string. starts searching at the beginning of a string(Last Portion)
Strrchr($string, “c”)- Parameters are the string and the character for which you want to search. return a substring from the specified characters to the end of the string.starts searching at the end of a string (Last Portion)
Substr($string, 0, 10)- a text string, the starting position and length of the substring you want to extract.
Ex) substr($string, starting point, end point);
Str_replace()- accept three parameters. (1)String you want to search, (2)replacement string, (3)the main string.
Ex) $newEmail = str_replace("president", "vice.president", $Email);
Str_ireplace()- accept three parameters. (1)String you want to search, (2)replacement string, (3)the main string.
Strtok()-divides a string into tokens using any of the characters that are passed.
Ex)
$presidents = "George W. Bush;William Clinton; George H.W. Bush;RonaldReagan;Jimmy Carter";
$president = strtok($presidents, "; ");
Str_split() - functions split a string into an indexed array.splits each character in a string into an array element using the syntax:
Ex) $array = str_split($string, [length]);
Explode()- function splits a string into an indexed array at a specified separator.
Ex) $array = explode(separators, string);
Implode()-Combines an array’s elements into a single string, separated by specified characters.
Ex) $variable = implode(separators, array);
5.Regular Expression
6. Regular Expression Common Function
preg_match($pattern, $str) – return TRUE if matches
rpreg_replace()
preg_split()
Lecture 5 – Files and Directories
1. Handling String Input
Addslashes($string) - a single argument representing the text string you want to escape and returns a string containing the escaped string.
stripslashes($string)- Removes slashes that were added with the addslashes() function.
2. Manage Files and Directories
Reading Directories
Opendir() - To iterate through the entries in a directory
Readdir() - return the file and directory names from the open directory
Closedir() - to close a directory handle
Ex)
$dir = "C:\\PHP "; // Windows path
$dirOpen = opendir($dir);
while ($curFile = readdir($dirOpen)) {
echo $curFile , "<br />";
}
closedir($dirOpen);
scandir() - Returns an indexed array containing the names of files and directories in the specified directory.
Ex)
$dir = "C:\\PHP"; // Windows path
$dirEntries = scandir($dir);
foreach ($dirEntries as $entry) {
echo $entry , "<br />";
}
Mkdir() - creates a new directory. To create a new directory within the current directory, Pass just the name of the directory you want to create to themkdir() function
Ex)
mkdir("bowlers");// on windows
mkdir("..\\tournament"); // Windows path
Copy() - function to copy a file with PHP. returns a value of true if it is successful or false if it is not
Syntax: copy(source, destination)
Ex) copy("sfweather.txt", "history\\sfweather01-27-2006.txt")
Rename() - rename a file or directory with PHP. returns a value of true if it is successful or false if it is not.
Syntax: rename(old_name, new_name)
Ex) rename(“Abc.txt”, “def.txt”)
Unlink() - function to delete files. functions return a value of trueif successful or false if not.
Rmdir() - function to delete directoriesfunctions return a value of trueif successful or false if not.
3. Working with Files
Fopen() - Open the file stream
Fclose() - Close the file stream
Fwrite() - function incrementally writes data to a text file.function returns the number of bytes that were written to the file. If no data was written to the file, the function returns a value of 0.
Syntax: fwrite($handle, data, [length]);
File_put_contents() - function writes an entire file or appends a text string to a file.
Ex)
$bowlerFirst = $_GET["first_name"];
$bowlerLast = $_GET["last_name"];
$newBowler = $bowlerLast . ", " . "$bowlerFirst" . "\n"; $bowlersFile = "bowlers.txt";
file_put_contents($bowlersFile, $newBowler, FILE_APPEND)
Reading data to txt files
6.Arrays
1. Add & Remove elements from the beginning of an array
array_shift()- function removes the first element from the beginning of an array
ex) array_shift($array)
array_unshift()- unction adds one or more elements to the beginning of an array
ex) array_unshift($topGolfers, "Tiger Woods", "Vijay Singh");
array_pop()- function removes the last element from the end of an array.
Ex) array_pop($hospitalDepts);
array_push() -adds one or more elements to the end of an array. Pass the name of the array whose last element you want to remove
ex)array_push($hospitalDepts, "Psychiatry", "Pulmonary Diseases");
array_splice() -adds or removes array elements. renumbers the indexes in the array.
Syntax: array_splice(array_name, starting element, elements_to_delete, values_to_insert);
Ex)To add an element within an array, include a value of 0as the third argument.
array_splice($hospitalDepts, 3, 0, "Ophthalmology");
ex) To add more than one element within an array, pass the array()construct as the fourth argument, separate the new array() element values by commas
array_splice($hospitalDepts, 3, 0, array("Ophthalmology","Otolaryngology"));
ex) Delete array elements by omitting the fourth argument from the array_splice()function
array_splice($hospitalDepts, 1, 2);
Note: If no 3rd argument, all elements starting from the specified position are deleted
2. Associative Arrays
Associative array - With associative arrays, you specify an element's key by using the array operator (=>)
Syntax:
$array_name = array(key=>value, ...); OR
$array_name[key] = value1;
$array_name[key] = value2;
…
Ex)
$capitals = array("Ontario"=>"Toronto", "Alberta"=>"Edmonton", ...); OR
$capitals["Ontario"] = "Toronto";
$capitals["Alberta"] = "Edmonton";
...
Ex)
3. FINDING AND EXTRACTING ELEMENTS AND VALUES
In_array()- function returns a Boolean value of trueif a given value exists in an array
Ex) in_array("Neurology", $hospitalDepts)
Array_search()- function determines whether a given value exists in an array andReturns the index or key of the first matching element if the value exists, or Returns false if the value does not exist
Array_key_exists()- unction determines whether a given index or key exists. You pass two arguments. The first argument represents the key to search for, The second argument represents the name of the array in which to search.
Ex) array_key_exists("Fat Man", $gamePieces)
Array_slice() - function returns a portion of an array and assigns it to another array.
Syntax: new_array = array_slice(array_name, starting element, elements_to_return);
Ex) $topFiveGolfers = array_slice($topGolfers, 0, 5);
4.OPERATING ON ARRAYS: SORT, COMBINE AND COMPARE
Sort
Sort()- for indexed arrays
Rsort()- for indexed arrays. reversed
Ksort()- for associative arrays by key
Krsort()- for associative arrays by key reversed
Combine
+ and += works best on associative arrays, especially if the arrays involved do not have any common keys.
Ex)
$arr1 = array ("one"=>"apple", "two"=>"banana");
$arr2 = array ("three"=>"cherry", "four"=>"grapes");
$arr3 = $arr1 + $arr2;
print_r($arr3);
Output Array ( [one] => apple [two] => banana [three] => cherry [four] => grapes )
Array_merge()- To merge two or more arrays use the function
Syntax: new_array = array_merge($array1, $array2, $array3, ...);
Note: duplicated associative keys overwrite, elements of numeric keys are appended
Compare
Array_diff()- unction returns an array of elements that exist in one array but not in any other arrays to which it is compared.
Syntax: new_array = array_diff($array1, $array2, $array3, ...);
Array_intersect()- new_array = array_intersect($array1, $array2, $array3, ...);
5.Two dimensional array
Associative array
Indexed array
Lecture 7 - Databases and MySQL & MySQL Databases with PHP
Querys
$connection = mysqli_connect("host", "user ", "password", "database");
$dbSelect = mysqli_select_db($connection, $database)
Terminating Script Execution
die($connection);
exit($connection);
Handling MySQL Errors
$query = "SELECT * FROM postcode WHERE pcode='$pcode'";
$results = mysqli_query($conn, $query);
mysqli_affected_rows($dbConnect)–count of affected rows
Lecture 9 - Managing State Information and Security
1. Understanding state information
Information about individual visits to a Web site is called state information. HTTP was originally designed to be stateless – Web browsers store no persistent data about a visit to a Web site.
The four tools for maintaining state information with PHP are:
· Hidden form fields
· Query strings
· Cookies
· Sessions
2. Hidden form
Hidden form fields temporarily store data that needs to be sent to a server that a user does not need to see.
Syntax: <input type="hidden" value=’values you want’ />
Ex) <input type="hidden" name="diverID" value="<?php echo $diverID ?>" />
3. Query strings
To pass information from one Web page to another using a query string. add a question mark (?) immediately after the URL. followed by the query string containing the information in name=value pairs, and eparate the name=value pairs within the query string by ampersands (&).
Ex)
<a href="page2.php?firstName="<?php echo $fname ?> "&lastName="<?php echo $lname ?> "&occupation="<?php echo $occ ?>">Link Text</a>
Use GET method ($_GET[“lastName”]);
4. Cookies
Query strings do not permanently maintain state information. Cookies are small pieces of information about a user that are stored by a Web server in text files on the user’s computer.
Temporary cookies - remain available only for the current browser session
Persistent cookies- remain available beyond the current browser session and are stored in a text file on a client computer
Setcookie() – Cookies cannot include semicolons or other special characters, such as commas or spaces, that are transmitted between Web browsers and Web servers using HTTP.
Syntax: setcookie(name ,[value ,expires, path, domain, secure]);
Ex) setcookie("firstName", "Don", time()+3600, "/", ".gosselin.com", 1);
$_COOKIE[] - Cookies that are available to the current Web page are automatically assigned to the $_COOKIE autoglobal. Access each cookie by using the cookie name as a key in the associative $_COOKIE[]array
Ex) echo $_COOKIE['firstName'];
Can use multidimensional array syntax to set and read cookie values
Deleting cookies - To delete a persistent cookie before the time assigned to the expiresargument elapses, assign a new expiration value that is sometime in the past. Do this by subtracting any number of seconds from the time() function
Ex) setcookie("firstName", "", time()-3600);
5. Session
Session_start() -function beforeyou send the Web browser any output.
session_destroy() - function to delete the session.
$_SESSION[“”] - autoglobal or retrieves any variables for the current session (based on the session ID) into the $_SESSIONautoglobal
6. UNDERSTANDING PHP SECURITY ISSUES
Web server security issues – firewalls, secure socket layer protocol to encrypt data
Secure coding issues - No magic formula for writing secure code, although there are various secure coding techniques to minimize security threats in programs.
· Disable the register_globals directive in php.ini
· Validate submitted form data
· Use sessions to validate user identities
· Store code in external files
· Access databases through a proxy user
· Handle magic quotes
Lecture 10 – OOP in PHP
Object-oriented programming- refers to the creation of reusable software objects that can be easily incorporated into multiple programs.
Object - refers to programming code and data that can be treated as an individual unit or component
Data - refers to information contained within variables or other types of storage structure
Methods - The functions associated with an object
Properties - The variables that are associated with an object
Encapsulation - Objects are encapsulated, all code and required data are contained within the object itself. Encapsulated objects hide all internal code and data. An interfacerefers to the methodsand properties that are required for a source program to communicate with an object.
Classes- The code, methods, attributes, and other information that make up an object are organized into classes
Instance - object that has been created from an existing class
Instantiating the object- Creating an object from an existing class
Inheritance - An object inheritsits methods and properties from a class — it takes on the characteristics of the class on which it is based
2. USING CLASSES IN PHP SCRIPTS
Create an object using a class: new - A class constructor is a special function with the same name as its class that is called automatically when an object from the class is instantiated.
Syntax: $objectName = new ClassName();
The identifiers for an object name- Must begin with a dollar sign ($), Can include numbers or an underscore (but cannot start with a number). Can pass arguments to many constructor functions.
Ex) $checking = new BankAccount(01234587, 1021, 97.58);
Access the methods and properties contained in the object - symbol (->)
-> - member selection notation
With member selection notation append one or more characters to an object, followed by the name of a method or property.
Like functions, methods can also accept arguments
Ex)
$checking->getBalance();
$checkNumber = 1022;
$checking->getCheckAmount($checkNumber);
3. Working with Database Connections as Objects
To connect to a MySQL database server using procedural syntax:
$dbConnect = mysqli_connect("localhost", "dongosselin", "rosebud", "real_estate");
To connect to a MySQL database server using object-oriented style:
$dbConnect = new mysqli("localhost", "dongosselin", "rosebud", "real_estate");
This statement also uses the mysqli()constructor function to instantiate a mysqliclass object named.
To explicitly close the database connection, use the close()method of the mysqli class
Ex) $dbConnect->close();
Selecting a Database
Ex)
$dbConnect = new mysqli("localhost", "dongosselin", "rosebud"); $dbConnect->select_db("real_estate");
Handling MySQL Errors - With object-oriented style, check whether a value is assigned to the connect_errno or connect_error properties and thencall the die()function to terminate script execution.
Ex)
$dbName = "guitars";
@$dbConnect->select_db($dbName)
or die("<p>Unable to select the database.</p>" . "<p>Error code " . $dbConnect->errno . ": “ . $dbConnect->error . "</p>");
Executing SQL Statements
With object-oriented style, use the query()method of the mysqliclass.
Ex)
$tableName = "inventory";
$sqlString = "SELECT * FROM inventory";
$queryResult = $dbConnect->query($sqlString)
$row = $queryResult->fetch_row();
4.DEFINING CUSTOM PHP CLASSES
Data structure - refers to a system for organizing data
Class members- The functions and variables defined in a class
Properties- Class variables are referred to as data membersor member variables
Methods- Class functions are referred to as memberfunctionsor function members
Defining Custom PHP Classes - Help make complex programs easier to manage. Hide information that users of a class do not need to access or know about. Make it easier to reuse code or distribute your code to others for use in their programs.
Inherited characteristics allow you to build new classes based on existing classes without having to rewrite the code contained in the existing one
Creating a class definition - Class names usually begin with an uppercase letter to distinguish them from other identifiers
Syntax:
classClassName {
data member and member function definitions
}
get_class() - function to return the name of the class of an object
ex) get_class($Checking)
instanceof - operator to determine whether an object is instantiated from a given class. Returns TRUE if it is or FALSE if not
ex) If($checking instanceofBankAccount)
PHP provides the following functions that allow you to use external files in your PHP scripts
· Include()
· Require()
· Include_once()
· Require_once()
Use the include()and include_once() functions for HTML code.
Use the require()or require_once() functions for PHP code.
Collecting Garbage- refers to cleaning up or reclaiming memory that is reserved by a program. PHP knows when your program no longer needs a variable or object and automatically cleans up the memory for you. The one exception is with open database connections.
Access specifiers - control a client’s access to individual data members and member functions
· Protected - access specifier allows access only within the class itself and by inherited and parent classes.
· Public - access specifier allows anyone to call a class’s member function or to modify a data member.
· Private - access specifier prevents clients from calling member functions or accessing data members and is one of the key elements in information hiding
Ex)
Constructor - a special function that is called automatically when an object from a class is instantiated. __construct()function takes precedence over a function with the same name as the class. Constructor functions are commonly used in PHP to handle database connection tasks.
'Programming > PHP' 카테고리의 다른 글
[대학교 자료정리]Laravel Framework features, structure and installation (0) | 2020.07.21 |
---|