Learn PHP Lacture1

573 views

Published on

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
573
On SlideShare
0
From Embeds
0
Number of Embeds
16
Actions
Shares
0
Downloads
9
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Learn PHP Lacture1

  1. 1. PHP & Framework Name:-Adarsh Bhatt Contact:-ambhatt23@yahoo.com 9408374479
  2. 2. Index:- • Overview of Open Source Software. • Widely Used Open Source Software. • Difference between Open Source Software and Close Source Software. • Pros and Cons of OSS. • Background Information of PHP. • Using variables • operators & expressions • Conditional Statements : • if statement • switch statement • Looping Statements: • for loop • while loop • do..while loop • foreach loop • Functions & Arrays in PHP • PHP functions • Creating arrays • Regular Expressions
  3. 3. • PHP and Database • Storage Types • PHP with MySQL. • Deal with Database. • Manipulation with tables using PHP. • Include(),include_once(). • Require(),require_once(). • Working with User Data and Error Handling. • Cookie • Session • Error Handling • Types of error • Object Oriented Programming with PHP. • Class, Constructor, Destructure • Inheritance • Magic Methods. • Overview of PHP Framework. • Popular PHP Framework. • WordPpress, Magento, Opencart, Drupal, Zoomla etc.
  4. 4. Overview of Open Source. Open-source software (OSS) is computer software that is available in source code form: the source code and certain other rights normally reserved for copyright holders are provided under a software license that permits users to study, change, improve and at times also to distribute the software. Open Source is a certification standard issued by the Open Source Initiative (OSI) that indicates that the source code of a computer program is made available free of charge to the general public. For an Open Source Software to be an "OSI Certified" a product must meet the following criteria: ◦ The author or holder of the license of the source code cannot collect royalties on the distribution of the program. ◦ The distributed program must make the source code accessible to the user. ◦ The author must allow modifications and derivations of the work under the program's original name.
  5. 5. Widely used open source products Linux Kernel (Operating System) Apache (Web Server) GNOME, KDE (Desktop Environment) MySQL (Database emphasizing speed) Postgre SQL ( Database emphasizing functionality) PHP(Server-side scripting) Open Office.org ( multi platform and multi lingual office suite ) Filezilla (fast & reliable FTP client) Pant.net(Free image editing software)
  6. 6. Open Source Software vs Close Source Software Term Open Source Closed Source Cost •Open source software may be free. If you have in- house capability for implementation, training then it is the best option. Otherwise you need to pay for it. •Open source software requires a certain level of technical expertise in order to manage content. •Open source software providers are increasingly charging for add-ons, additional services and integration. •The cost of proprietary software will vary from a few thousand to a few hundred thousand dollars, depending on the complexity of the system required. •This cost is made up of a base fee for software, integration and services and annual licensing/support fees.
  7. 7. Term Open Source Closed Source Innovation Open source software enables innovation by providing users with the freedom and flexibility to adapt the software to suit, without restriction. Proprietary software providers do not allow users to view or alter the source code. While this may be viewed as a disadvantage to some, it ensures the security and reliability of the software. Usability It is developer-centric. Requires system administration expertise. No availability of the proper documentation of the system is available. Proprietary software generally employs expert usability testing, and as the software is normally aimed at a more targeted audience
  8. 8. Term Open Source Closed Source Services & Support •Service is one of the key issues regarding open source software. Open source software relies on its online community network to deliver support via forums and blogs. •These communities cannot guarantee the high level of responsive service and support proprietary software can offer. •Proprietary software providers offer ongoing support to users, a key selling point for users without technical expertise. •Service is one of the main reasons users choose proprietary software, many proprietary software providers compete on service , increasing the bargaining power of buyers and thereby increasing customer service levels among providers.
  9. 9. •Term •Open Source •Closed Source Security •Open source software is not developed in a controlled environment. •While development they often have a oconcentrated dev. team, oindividuals all over the world who may not work on the software for the duration of its developing lifetime. This lack of continuity and common direction can lead to barriers to effective communication surrounding the software. •Proprietary software is viewed as more secure because it is developed in a controlled environment by a concentrated team with a common direction.
  10. 10. Pros and Cons of OSS Pros of OSS:- ◦ Helped to produce reliable, high quality software quickly and inexpensively. ◦ thousands of independent programmers testing and fixing bugs of the software. ◦ From a developer’s point of view, open source technologies provide a platform on which to build custom solutions.
  11. 11. • Cons of OSS ◦ In terms of security, open source may allow hackers to know about the weaknesses or loopholes of the software more easily than closed-source software. ◦ open source development process may not be well defined and the stages in the development process, such as system testing and documentation may be ignored. ◦ It is also difficult to design a commercially sound business model around the open source paradigm. ◦ Anyone can develop competing product because its Open Source. ◦ Almost everything in open source is viewable by other developers. If a developer makes a major mistake, it can become public information and
  12. 12. Background Information of PHPPHP stands for “Hypertext Preprocessor”. It is widely used Open source, general purpose scripting language for web development & can be embedded into HTML. Hypertext preprocessor is an interpreter of PHP code created to run successfully on web servers.The interpreter processes PHP code spec invoked by web server & finally dispatches HTML code to a browser. PHP is a server-side scripting language which means that PHP scripts or programs usually run on the web server. PHP Script is processed by PHP Engine each time when it runs. PHP Syntax is based on C. So it is easy for C Programmer to learn & work in PHP. PHP was created by Rasmus Lerdorf in 1994, a developer of PERL/CGI Script. Version 1 : (1994) ◦ PHP started out with the set of simple tools coded in C language to replace Perl script and it was used on his Personal Home Page (so acronym - PHP).
  13. 13. Version 2 : (1995) ◦ First popular version of PHP. Version 3 : (1998) ◦ Developers were able to write their own modules for language, adding functionality to its core. Version 4 : (2000) ◦ Important change made to PHP 4 was switching to Zend Engine, created by Zend company found by Zeev Suraski and Andi Gutmans. ◦ PHP started running on: Apache Web Server Microsoft’s IIS Zeus AOLServer & many more Web Servers. Version 5 (2004) ◦ It focused on language maturity & offered a lots of new functionalities that had been missing in previous versions. Cont…
  14. 14. Cont… PHP 6 :- Currently available as a developer snapshot which can be downloaded and tried out. It is planning to offer the following :- Improved Unicode Support Namespaces, SOAP, XML. Benefits of running PHP As a Server Side Script ◦ PHP Script is always invisible to client browser, as Web Server sends only output of PHP Script to client browser, not script only. ◦ PHP Scripts are browser neutral. Drawbacks in running PHP as a Server – Side Script ◦ PHP consumes lots of web server resources because everything is executed on Web Server. ◦ With many concurrent requests & large complex scripts, the server might not be able to respond smoothly. ◦ PHP 5.5.7 is a latest version release on 12th december,2013. ◦ PHP 5.6.0 alpha1 released on 23rd Jan,2014 but it is in development preview mode.
  15. 15. What is a PHP file?PHP File is an ASCII file created using any editor like Notepad, Dreamviewer, etc. and stored on HDD. The file contains mix of HTML & PHP. PHP files may contain text, HTML tags & scripts. After PHP files is processed, output is returned as plain HTML. PHP files usually have .PHP extension. PHP runs on different OS platforms seamlessly, being interpreted scripting language. PHP is compatible with almost all Web Servers. PHP is free to download from official PHP Resource. PHP is easy to learn & runs efficiently on any compatible Web Server.
  16. 16. Internal Structure of PHP Database Webpage w e b s e r v e r Function Modules InterfaceWeb Server Interface Runtime Compiler Zend Engine Executor Web Server Software Modules php MySQL Oracle ODBC XML PDO ...
  17. 17. Variables are identifiers which point to memory location in which data are stored. Variables in PHP are weakly/loosely typed which means when a variable is being defined their data type is not declared prior to use. Variables can change its type depending on value being assigned as often needed. Variables
  18. 18. Variable name should begin with dollar sign. First character after dollar sign should be letter or an underscore. Remaining characters in a variable name can be letters, characters, or underscore without any fixed limit. Following characters are not allowed in variable name :- *, +, #, @, -,&,£. Variables in PHP are case-sensitive. Naming Rules for variables
  19. 19. As it allows to convert variables data-type automatically depending on the content in the variable. It is beneficial as it makes variable very flexible & same variable can be used at several different situations. It is disadvantageous as , if you pass around data accidentally of wrong type it won’t inform you about it. To know variable datatype use gettype($var) function.e.g PHP is loosely-typed language
  20. 20. DataType: - PHP has several different types of variables. All holds specific class/type of information. PHP has 8 basic data types which are categorized into 3 categories :- 1. Scalar Datatype 2. Compound Datatype 3. Special Datatype
  21. 21. Scalar Data Type:-Scalar data means data that contains only a single value. Data type Description Integer -Stores whole numbers either +ve or – ve. -If value assigned is out of the range it is converted to float. Float - Store floating point numbers as well as higher integers. String - Stores sequence of characters terminated by NULL. Boolean -It holds true or false. -Internally it holds integer value - 0 for false - rest values for true.
  22. 22. Compound Data Type Compound data is data that can contain more than one variable. Data type Description Array -Ordered map -It holds multiple values. Object -They have multiple values within it. -They have their own functions for accessing and/ or manipulating its data.
  23. 23. Special Data typePHP supports two special data types which have a specific meaning. Data types Description Resource Contains a reference to an external resource, such as file or database. It can be used in same manner as we use another variables but only difference is it should be freed up when not required. Null Contains null as a value. Explicitly do not contain any value.
  24. 24. Conditional Statements if statement switch statement goto statement
  25. 25. If statement Simple if if(test-expr) { True part } statement If...else statement if(test-expr) { True part } else { False part } Nested if statement if(test-exp 1) { if(test-exp 2) { true 1 & 2 } else { false 2 } } else { false part all }
  26. 26. else if ladder :- if(test-exp 1) statement -1; else if(test-exp 2) statement – 2; else if(test-exp 3) statement – 3; . . . else false statement switch statement :- switch(ch) { case value1: statement 1;break; case value2: statement 2;break; case value3: statement 3; break; . . . default : statement-false; break; } Case value can be of any data type or even any condition. We can use break and continue interchangeable. Default can be placed anywhere in switch.
  27. 27. goto statement The goto operator can be used to jump to another section in the program. The target point is specified by a label followed by a colon, and the instruction is given as goto followed by the desired target label. The target label must be within the same file and context, meaning that you cannot jump out of a function or method, nor can you jump into one. You also cannot jump into any sort of loop or switch structure.
  28. 28. goto statement Forward Jump :- <?php goto label; statement -1 label: statement -2 ?> Example : <?php goto a; echo 'Foo‘; a: echo 'Bar'; ?> Backward Jump :- <?php label: statement -2 goto label; statement -1 ?> Example : <?php a: echo 'Bar'; goto a; echo 'Foo'; ?>
  29. 29. Loo p while loop while (expr) statement; while (expr): statement ... endwhile; do..while loop :- do{ statements; }while(expr); for loop :- for(intialization; condition; incr/decr) { statement; } do..while loop is executed at least once whereas while and for loop executes only when condition is satisfied.
  30. 30. Foreach Loop The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects. foreach will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. Syntax : 1 foreach (array_expression as $value) statement // indexed array Syntax : 2 foreach (array_expression as $key => $value) statement // associative array When foreach first starts executing, the internal array pointer is automatically reset to the first element of the array.Indexed Array : <?php $array = array(1,2,3,4); foreach($array as $val) { print $val; } ?> Associative Array : <?php $arr = array(1=>’ABC’,2=>’PQR’); foreach ($arr as $key => $val) { print "$key = $valn"; } ?>
  31. 31. PHP Super Globals Super Globals are variables that are automatically available throughout all program code in all scopes. These variables do not require declaration and then too they can be accessed. Super global variables provide :- ◦ Useful information about the environment. ◦ Allow access to HTML form variables or parameters. ◦ Access to cookies stored on a client. ◦ Keeping track of sessions and file uploads.
  32. 32. Name Functionality $GLOBALS Contains all global variables in your script, including other super globals. This is not generally recommended for use, unless you are, for some reason, not sure where a variable will be stored. $_GET Contains all variables sent via a HTTP GET request. That is, sent by way of the URL. $_POST Contains all variables sent via a HTTP POST request. $_FILES Contains all variables sent via a HTTP POST file upload. $_COOKIE Contains all variables sent via HTTP cookies. $_SESSION Contains all variables stored in a user's session. $_SERVER Contains all variables set by the web server you are using, or other sources that directly relate to the execution of your script.
  33. 33. Name Functionality $_REQUEST Contains all variables sent via HTTP GET, HTTP POST, and HTTP cookies. This is basically the equivalent of combining $_GET, $_POST, and $_COOKIE, and is less dangerous than using $GLOBALS. However, as it does contain all variables from untrusted sources (that is, your visitors), you should still try to steer clear unless you have very good reason to use it. $_ENV Contains all environment variables set by your system or shell for the script.
  34. 34. Array An array in PHP is actually an ordered map. A map is a type that associates values to keys. Syntax to specify array with array() :- array( key => value , ... ) key may only be an integer or string value may be any value of any type An array can hold all your variable values under a single name. And you can access the values by referring to the array name and index of element. Each element in the array has its own index so that it can be easily accessed.
  35. 35. Types of Array There are two kind of arrays: 1. Indexed array - An array with a numeric index beginning with 0. Indexed arrays are used when you identify things by their position. 2. Associative array - An array where each ID key is associated with a value. Associative arrays have strings as keys and behave more like two-column tables. The first column is the key, which is used to access the value. • PHP internally stores array as associative array. Assigning elements to array using array(): $arrname = array(“val1”,”val2”,”val3”,..); $cars=array("Saab","Volvo","BMW","Toyota"); Manual assignment to initialize array : $cars[0]="Saab"; $cars[1]="Volvo"; $cars[2]="BMW"; $cars[3]="Toyota"; Adding elements to array at the end: $cars[]="Saab"; $cars[]="Volvo"; $cars[]="BMW"; $cars[]="Toyota";
  36. 36. Associative Array If the initial index is a non-numeric string, subsequent indexes are integers beginning at 0. ◦ $whoops = array('Friday' => 'Black', 'Brown', 'Green'); ◦ // same as $whoops = array('Friday' => 'Black', 0 => 'Brown', 1 => 'Green');
  37. 37. Getting size of an Array The count( ) and sizeof( ) functions return the number of elements in the array. They are identical in use and effect. ◦ $family = array('Fred', 'Wilma', 'Pebbles'); ◦ $size = count($family); // $size is 3 ◦ $family = array('Fred', 'Wilma', 'Pebbles'); $size = sizeof($family); // $size is 3
  38. 38. Iterator FunctionsEvery PHP array keeps track of the current element you're working with; the pointer to the current element is known as the iterator. PHP has functions to set, move, and reset this iterator. The iterator functions are: current( ) ◦ Returns the element currently pointed at by the iterator reset( ) ◦ Moves the iterator to the first element in the array and returns it next( ) ◦ Moves the iterator to the next element in the array and returns it prev( ) ◦ Moves the iterator to the previous element in the array and returns it end( ) ◦ Moves the iterator to the last element in the array and returns it each( ) ◦ Returns the key and value of the current element as an array and moves the iterator to the next element in the array key( ) ◦ Returns the key of the current element The each( ) function is used to loop over the elements of an array. It processes elements according to their internal order:
  39. 39. To extract only a subset of the array, use the array_slice( ) function: $subset = array_slice(array, offset, length); The array_slice( ) function returns a new array consisting of a consecutive series of values from the original array. The offset parameter identifies the initial element to copy (0 represents the first element in the array), and the length parameter identifies the number of values to copy. The new array has consecutive numeric keys starting at 0. Example $people = array('Tom', 'Dick', 'Harriet', 'Brenda', 'Jo'); $middle = array_slice($people, 2, 2); // $middle is array('Harriet', 'Brenda') Example:- $person = array('name' => 'Fred', 'age' => 35, 'wife' => 'Betty'); $subset = array_slice($person, 1, 2); // $subset is array(0 => 35, 1 => 'Betty') Slicing an array
  40. 40. Creating variables from arrayThe extract( ) function automatically creates local variables from an array. The indexes of the array elements are the variable names $person = array('name' => 'Fred', 'age' => 35, 'wife' => 'Betty'); extract($person); // $name, $age, and $wife are now set print $name; If a variable created by the extraction has the same name as an existing one, the extracted variable overwrites the existing variable. $shape = "round"; $array = array("cover" => "bird", "shape" => "rectangular"); extract($array, EXTR_PREFIX_SAME, "book"); echo "Cover: $book_cover, Book Shape: $book_shape, Shape: $shape";
  41. 41. Sorting one array Effect Ascending Descending User-defined order Sort array by values, then reassign indexes starting with 0 sort( ) rsort( ) usort( ) Sort array by values asort( ) arsort( ) uasort( ) Sort array by keys ksort( ) krsort( ) uksort( )
  42. 42. print_r() ◦ print_r() displays information about a variable in a way that's readable by humans. var_dump() ◦ This function displays structured information about one or more expressions that includes its type and value. ◦ Example :- <?php $a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z')); print_r ($a); ?> Array ( [a] => apple [b] => banana [c] => Array ( [0] => x [1] => y [2] => z ) )
  43. 43. explode() takes a string and splits it into separate elements of an array using the argument provided as a delimiter. ◦ explode(separator,string,limit) ◦ <?php $str = "Hello world. It's a beautiful day."; print_r (explode(" ",$str)); ?> explode() Parameter Description separator Required.Delimitor using which you can break string. string Required. The string to split limit Optional. Specifies the maximum number of array elements to return.
  44. 44. implode() traverses through the elements of an array and re-creates a single string. implode(separator,array) <?php $arr = array('Hello','World!','Beautiful','Day!'); echo implode(" ",$arr); ?> Output :- Hello World! Beautiful Day! Implode() Parameter Description separator Optional. Specifies what to put between the array elements. Default is "" (an empty string) array Required. The array to join to a string
  45. 45. Functions A function is a block of code that has a name and it has a property that it is reusable. Function groups a number of script statements into a unit and gives it a name. To keep the script from being executed when the page loads, you can put it into a function. A function will be executed by a call to the function. You may call a function from anywhere within a page.
  46. 46. Syntax for function function functionName($param1, $param2,…) { code to be executed; return $value; } Example :- <?php function writeName() { echo “ABC"; } echo "My name is "; writeName(); ?> Example : with parameter <?php function writeName($fname) { echo $fname . “Paul.<br />"; } echo "My name is "; writeName("Jim"); echo "My sister's name is "; writeName(“Agnes"); echo "My brother's name is "; writeName("Steve"); ?>
  47. 47. Date Time functions int time ( ) ◦ It returns you the current time int strtotime ( string time [, int now]) ◦ It converts string to timestamp. The string time to convert, and a second optional parameter that can be a relative timestamp. string date ( string format [, int timestamp]) ◦ Parameter one is a special string containing formatting codes for how you want the timestamp converted. Parameter two is the timestamp you want to convert - if you do not supply it, PHP assumes you want to use the current time.
  48. 48. Mathematical FunctionsPHP provides you wide set of mathematical functions. float ceil ( float value) – rounds to nearest int above current value. float floor ( float value) - rounds to the nearest int below current value. float round ( float value [, int precision]) – rounds up the specified value as first parameter to the specified precision as second parameter. Trigeonometric functions as: float sin ( float value) float cos ( float value) float tan ( float value) float asin ( float value) float acos ( float value) float atan ( float value) float deg2rad ( float value) float rad2deg ( float value)
  49. 49. Mathematical Constants Constant Meaning M_PI PI (Value : 3.14159265358979323846 ) M_SQRTP I Sqrt(M_PI) (Value :1.77245385090551602729 ) M_SQRT2 Sqrt(2) Value : 1.414213562373095 M_SQRT3 Sqrt(3) Value : 1.732050807568877
  50. 50. String unctions• substr() :-This function returns the part of the string as an output. Syntax : - string substr(<string s>,<int start>,[<int length>]); Examples :- <?php echo substr("Hello world",6); ?> //Returns world <?php echo substr("Hello world",6,4); ?> // Returns worl <?php echo substr("Hello world", -1); ?> // Returns d <?php echo substr("Hello world", -3, -1); ?> // Returns rl • strlen() :-This function returns the length of the string. Syntax :- int strlen(<string s>); string s: It is mandatory field. The string whose length is to be found out is mentioned here. Example :- <?php echo strlen("Hello world"); ?> // Returns 11 •trim() :-This function removes the whitespaces from both start and the end of the string. Syntax :- string trim(<string s>); Example :- <?php echo trim( " Hello World "); ?>//Hello World
  51. 51. ltrim() :- This function removes the whitespaces from the left part of the string. ◦ Syntax:- string ltrim(<string s>); ◦ Example :- <?php echo ltrim( " Hello World "); ?> // returns Hello World rtrim() :- This function removes the whitespaces from the right part of the string. Syntax :- string rtrim(<string s>); ◦ Example :- <?php echo rtrim( " Hello World "); ?>// Hello World strtolower() :-This function converts the string to lower case ◦ Syntax : string strtolower(<string s>); ◦ Example :- <?php echo strtolower("HELLO WORLD"); ?> // Returns hello world
  52. 52. strtoupper():-This function converts the string to upper case ◦ Syntax :strtoupper(<string s>); ◦ Example :- ◦ <?php echo strtoupper("hello world"); ?> // Returns HELLO WORLD strcmp():-The strcmp() function compares two strings. ◦ This function returns: ◦ 0 – if the two strings are equal ◦ <0 – if string1 is less than string2 ◦ >0 – if string1 is greater than string2 ◦ Syntax : strcmp(<string1>,<string2>); ◦ Example :- ◦ <?php echo strcmp("Hello world!","Hello world!"); ?> // 0
  53. 53. Regular Expression Usually referred as regex. Regular expression is a specially formatted pattern that can be used to find instances of one string within another. Regular expressions in PHP are similar to find/replace tools in text editors. Regex engine is s/w that can process regex such as trying to match a pattern within given string.
  54. 54. Common Uses of Regular ExpressionsIn Web application, regular expression would be helpful as under: ◦ Input Validation ◦ Verifying input format ◦ Parsing data from pre-defined variables ◦ Searching for and replacing data in a file or database.
  55. 55. Regular Expression Functions Function Description preg_filter() Performs a regex search and replace. preg_grep() Returns array entries that match the pattern. preg_last_error () Returns error code of the last PCRE regex execution. preg_match() Performs regular expression match. preg_match_all () Performs a global regular expression match. preg_quote() Quote regular expression characters. preg_replace() Performs a regex search and replace. preg_split() Split string by a regular expression.

×