Chapter 7:- PHP. Compiled By:- Sanjay Patel Assistant Professor, SVBIT.

Similar documents
PHP with data handling

Agenda. 1. Brief History of PHP. 2. Getting started. 3. Examples

Princess Nourah bint Abdulrahman University. Computer Sciences Department

Web Application Development (WAD) V th Sem BBAITM(Unit-1) By: Binit Patel

Web Engineering (Lecture 08) WAMP

Introduction of PHP Created By: Umar Farooque Khan

PHP Introduction. Some info on MySQL which we will cover in the next workshop...

What is PHP? [1] Figure 1 [1]

PHP by Pearson Education, Inc. All Rights Reserved.

You can also set the expiration time of the cookie in another way. It may be easier than using seconds.

PHP. M hiwa ahamad aziz Raparin univercity. 1 Web Design: Lecturer ( m hiwa ahmad aziz)

PHP 5 Introduction. What You Should Already Know. What is PHP? What is a PHP File? What Can PHP Do? Why PHP?

php Mr. Amit Patel Hypertext Preprocessor Dept. of I.T.

PHP INTERVIEW QUESTION-ANSWERS

Introduction. Server-side Techniques. Introduction. 2 modes in the PHP processor:

PHP. Introduction. PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language, like ASP PHP scripts are executed on the server

B. V. Patel Institute of BMC & IT 2014

Important Points about PHP:

Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Chapter 11 Introduction to PHP

PHP and MySQL for Dynamic Web Sites. Intro Ed Crowley

Course Syllabus. Course Title. Who should attend? Course Description. PHP ( Level 1 (

PHP Personal Home Page PHP: Hypertext Preprocessor (Lecture 35-37)

CS6501 IP Unit IV Page 1

Hello everyone! Page 1. Your folder should look like this. To start with Run your XAMPP app and start your Apache and MySQL.

PHP Development - Introduction

Database Systems Fundamentals

Lecture 7: Dates/Times & Sessions. CS 383 Web Development II Wednesday, February 14, 2018

Server side basics CS380

By the end of this section of the practical, the students should be able to:

The PHP language. Teaching you everything about PHP? Not exactly Goal: teach you how to interact with a database via web

PHP Hypertext Preprocessor

Chapter 9. Managing State Information. Understanding State Information (continued) Understanding State Information 10/29/2011.

Lecture 7 PHP Basics. Web Engineering CC 552

Open Source Web Application Development - CS310

CERTIFICATE IN WEB PROGRAMMING

HTML 5 Form Processing

CS 377 Database Systems. Li Xiong Department of Mathematics and Computer Science Emory University

CSC Web Programming. Introduction to JavaScript

PHP State Maintenance (Cookies, Sessions, Hidden Inputs)

CSCB20 Week 8. Introduction to Database and Web Application Programming. Anna Bretscher* Winter 2017

Lecture 12. PHP. cp476 PHP

DATABASE SYSTEMS. Introduction to web programming. Database Systems Course, 2016

INTERNET PROGRAMMING. Software Engineering Branch / 4 th Class Computer Engineering Department University of Technology

URLs and web servers. Server side basics. URLs and web servers (cont.) URLs and web servers (cont.) Usually when you type a URL in your browser:

CITS1231 Web Technologies. PHP s, Cookies and Session Control

User Guide. Version 8.0

PHP: Cookies, Sessions, Databases. CS174. Chris Pollett. Sep 24, 2008.

Fachgebiet Technische Informatik, Joachim Zumbrägel

Some things to watch out for when using PHP and Javascript when building websites

PHP: Hypertext Preprocessor. A tutorial Introduction

Languages in WEB. E-Business Technologies. Summer Semester Submitted to. Prof. Dr. Eduard Heindl. Prepared by

Web Scripting using PHP

Alpha College of Engineering and Technology. Question Bank

CSE 154 LECTURE 13: SESSIONS

Let's Look Back. We talked about how to create a form in HTML. Forms are one way to interact with users

AN INTRODUCTION TO PHP

Introductory workshop on PHP-MySQL

PhpT Point, Simply Easy Learning

PHP 5 if...else...elseif Statements

Tutorial 10: Programming with JavaScript

Multimedia im Netz Online Multimedia Winter semester 2015/16. Tutorial 03 Minor Subject

BEGINNER PHP Table of Contents

Programming for the Web with PHP

PHP. MIT 6.470, IAP 2010 Yafim Landa

Excerpts of Web Application Security focusing on Data Validation. adapted for F.I.S.T. 2004, Frankfurt

3. WWW and HTTP. Fig.3.1 Architecture of WWW

Web Scripting using PHP

WINTER. Web Development. Template. PHP Variables and Constants. Lecture

WEB APPLICATION ENGINEERING II

Course Wiki. Today s Topics. Web Resources. Amazon EC2. Linux. Apache PHP. Workflow and Tools. Extensible Networking Platform 1

COMS 469: Interactive Media II

How browsers talk to servers. What does this do?

Creating HTML files using Notepad

Basic PHP. Lecture 19. Robb T. Koether. Hampden-Sydney College. Mon, Feb 26, 2108

CSE 154 LECTURE 21: COOKIES

CSE 154 LECTURE 21: COOKIES

Part 3: Online Social Networks

exam. Number: Passing Score: 800 Time Limit: 120 min File Version: Zend Certified Engineer

COMP519 Web Programming Lecture 28: PHP (Part 4) Handouts

Hands-On Perl Scripting and CGI Programming

Figure 1 Forms category in the Insert panel. You set up a form by inserting it and configuring options through the Properties panel.

ISSN: [Kumar * et al., 7(3): March, 2018] Impact Factor: 5.164

Setting Up a Development Server What Is a WAMP, MAMP, or LAMP? Installing a WAMP on Windows Testing the InstallationAlternative WAMPs Installing a

Shankersinh Vaghela Bapu Institue of Technology

Introduction to HTML5

COMP284 Scripting Languages Lecture 11: PHP (Part 3) Handouts

CNIT 129S: Securing Web Applications. Ch 10: Attacking Back-End Components

zend. Number: Passing Score: 800 Time Limit: 120 min.

Govt. of Karnataka, Department of Technical Education Diploma in Computer Science & Engineering. Fifth Semester. Subject: Web Programming

Web Programming TL 9. Tutorial. Exercise 1: String Manipulation

ITS331 IT Laboratory I: (Laboratory #11) Session Handling

Distributed Databases and Remote Access to a Database

Sample Copy. Not For Distribution

INSTITUTE OF AERONAUTICAL ENGINEERING (Autonomous) Dundigal, Hyderabad

Perch Documentation. U of M - Department of Computer Science. Written as a COMP 3040 Assignment by Cameron McKay, Marko Kalic, Riley Draward

A Web-Based Introduction

A JavaBean is a class file that stores Java code for a JSP

PHP. Interactive Web Systems

PHP & My SQL Duration-4-6 Months

Chapter 1 INTRODUCTION

Transcription:

Chapter 7:- PHP Compiled By:- Assistant Professor, SVBIT.

Outline Starting to script on server side, Arrays, Function and forms, Advance PHP Databases:-Basic command with PHP examples, Connection to server, creating database, selecting a database, listing database, listing table names creating a table, inserting data, altering tables, queries, deleting database, deleting data and tables, PHP my admin and database bugs.

What is PHP? PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language, like ASP PHP scripts are executed on the server PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.) PHP is an open source software (OSS) PHP is free to download and use

Getting Start How to escape from HTML and enter PHP mode PHP parses a file by looking for one of the special tags that tells it to start interpreting the text as PHP code. The parser then executes all of the code it finds until it runs into a PHP closing tag. Starting tag <?php echo Hello World ;?> Ending tag Notes <?php?> Preferred method as it allows the use of PHP with XHTML <??> Not recommended. Easier to type, but has to be enabled and may conflict with XML <script language="php">?> Always available, best if used when FrontPage is the HTML editor <% %> Not recommended. ASP tags support was added in 3.0.4

What is a PHP File? PHP files may contain text, HTML tags and scripts PHP files are returned to the browser as plain HTML (View source would not work here!) PHP files have a file extension of ".php", ".php3", or ".phtml"

Why PHP? PHP runs on different platforms (Windows, Linux, Unix, etc.) PHP is compatible with almost all servers used today PHP is FREE to download from the official PHP resource: www.php.net PHP is easy to learn and runs efficiently on the server side

Why is PHP used? Easy to Use:- Code is embedded into HTML. The PHP code is enclosed in special start and end tags that allow you to jump into and out of "PHP mode". Cross Platform:- Runs on almost any Web server on several operating systems. One of the strongest features is the wide range of supported databases. Cost Benefits:- PHP is FREE to download

What Can PHP Do? PHP can generate dynamic page content PHP can create, open, read, write, and close files on the server PHP can collect form data PHP can send and receive cookies PHP can add, delete, modify data in your database

Hello world example PHP code can be placed anywhere in the document. Starts and ends with <?php?> Each code line in PHP must end with a semicolon <html> <body> <?php?> </body> echo "Hello World"; </html>

Simple HTML Page with PHP The following is a basic example to output text using PHP. <html><head> <title>my First PHP Page</title> </head> <body> <?php echo "Hello World!";?> </body></html> Copy the code onto your web server and save it as test.php. You should see Hello World! displayed.

My First Program

Comments in PHP

Variables in PHP All variables in PHP start with a $ sign symbol. Variables may contain strings, numbers, or arrays. To concatenate two or more variables together, use the dot (.) operator. Variables are used for storing values, like text strings, numbers or arrays. All variables in PHP are denoted with a leading dollar sign($) The value of a variable is the value of its most recent assignment

Variable Syntax Syntax $name_of_variable=value; Variables are assigned with the = operator, with the variable on the left-hand side and the expression to be evaluated on the right.

Rules for declaration Variable A variable name must start with a letter or an underscore "_. A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and _ ). A variable name should not contain spaces. If a variable name is more than one word, it should be separated with an underscore ($my_string), or with capitalization ($mystring).

Variable Example

Another Example <html> <body> <?php $x=5; $y=6; $z=$x+$y; echo $z;?> </body> </html> The result would be: 11

Local Scope Variable Example <?php $x=5; // global scope The result would be: Blank function mytest() { echo $x; // local scope } mytest();?>

Global ScopeVariable Example <html> <body> <?php $x=5; $y=10; function mytest() { global $x, $y; $y=$x+$y;} // global scope // global scope The result would be: 15 mytest(); echo $y;?> </body> </html> // run function // output the new value for variable $y

Data types in PHP PHP s type is simple, streamlined and flexible, and it insulates the programmer from low-level details. PHP makes it easy not to worry too much about typing of variables and values, both because does not require variables to be typed and because it handles a lot of type conversion for you.

Data Types Example Integers Ex, 1,3,5,5,44,3,3334 Doubles Ex, 3.14,5.33.4.55 Booleans Ex. TRUE and FALSE String Ex, hello Array Objects

Example

String Variables in PHP A string variable is used to store and manipulate text. String variables are used for values that contain characters. After we have created a string variable we can manipulate it. A string can be used directly in a function or it can be stored in a variable.

Example <?php $txt="hello world!"; echo $txt;?> <?php $txt1="hello world!"; $txt2="what a nice day!"; echo $txt1. " ". $txt2;?> <?php echo strpos("hello world!","world");?> The result would be: Hello world!"; The result would be: Hello world! What a nice day! The result would be: 6

PHP operator

Cont d..

Cont d..

Array -An array can store one or more values in a single variable name. -Each element in the array is assigned its own ID so that it can be easily accessed. $array[key] = value;

Three Kind of array When working with PHP, sooner or later, you might want to create many similar variables. Instead of having many similar variables, you can store the data as elements in an array. There are three different kind of arrays: Numeric array - An array with a numeric ID key Associative array - An array where each ID key is associated with a value Multidimensional array - An array containing one or more arrays

Numeric Arrays A numeric array stores each element with a numeric ID key. There are different ways to create a numeric array. 1. In this example the ID key is automatically assigned. 2. In this example we assign the ID key manually:

Cont d.. 3. The ID keys can be used in a script:

Associative array An associative array, each ID key is associated with a value. When storing data about specific named values, a numerical array is not always the best way to do it. With associative arrays we can use the values as keys and assign values to them.

Example

Example

Multidimensional array In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on.

Example

PHP Looping Looping statements in PHP are used to execute the same block of code a specified number of times. Very often when you write code, you want the same block of code to run a number of times. You can use looping statements in your code to perform this.

While,Do..while, For loop..

PHP Function The real power of PHP comes from its functions. In PHP, there are more than 700 built-in functions. we will create our own functions. A function will be executed by a call to the function. You may call a function from anywhere within a page. Syntax:- function functionname() { code to be executed; }

Example <?php function writename() { echo "Kai Jim Refsnes"; The result would be: My name is Kai Jim Refsnes } echo "My name is "; writename();?>

PHP function

PHP Functions - Adding parameters <?php function writename($fname) { echo $fname. " Refsnes.<br>"; } The result would be: My name is Kai Jim Refsnes. My sister's name is Hege Refsnes. My brother's name is Stale Refsnes. echo "My name is "; writename("kai Jim"); echo "My sister's name is "; writename("hege"); echo "My brother's name is "; writename("stale");?>

PHP Functions - Two parameters <?php function writename($fname,$punctuation) { echo $fname. " Refsnes". $punctuation. "<br>"; } The result would be: My name is Kai Jim Refsnes. My sister's name is Hege Refsnes! My brother's name is Ståle Refsnes? echo "My name is "; writename("kai Jim","."); echo "My sister's name is "; writename("hege","!"); echo "My brother's name is "; writename("ståle","?");?>

PHP function- Return Value

PHP date() The PHP date() function is used to format a time or a date.

PHP date() The first parameter in the date() function specifies how to format the date/time. It uses letters torepresent date and time formats. Here are some of the letters that can be used: d - The day of the month (01-31) m - The current month, as a number (01-12) Y - The current year in four digits

Example

SSI(server side includes) Server Side Includes (SSI) are used to create functions, headers, footers, elements that will be reused on multiple pages.

SSI ( include(), require() function) You can insert the content of a file into a PHP file before the server executes it, with the include() or require() function. The two functions are identical in every way, except how they handle errors: include() generates a warning, but the script will continue execution require() generates a fatal error, and the script will stop

Advantages This can save the developer a considerable amount of time. This means that you can create a standard header or menu file that you want all your web pages to include. When the header needs to be updated, you can only update this one include file, or when you add a new page to your site, you can simply change the menu file (instead of updating the links on all web pages).

PHP include() function The include() function takes all the text in a specified file and copies it into the file that uses the include function. If an error occurs, the include() function generates a warning, but the script will continue execution

Example

Output

PHP require() function The require() function is identical to include(), they only handle errors differently. The include() function generates a warning (but the script will continue execution) while the require() function generates a fatal error (and the script execution will stop after the error).

Example ( use include() function ) Notice that the echo statement is still executed! This is because a Warning does not stop the script execution.

Example ( use require() function ) The echo statement was not executed because the script execution stopped after the fatal error.

Another Example

Recommendation It is recommended to use the require() function instead of include(), because scripts should not continue executing if files are missing or misnamed.

PHP File Handling The fopen() function is used to open files in PHP. File Handling Data Storage Though slower than a database Manipulating uploaded files From forms Creating Files for download

Open/Close a File A file is opened with fopen() as a stream, and PHP returns a handle to the file that can be used to reference the open file in other functions. Each file is opened in a particular mode. A file is closed with fclose() or when your script ends.

Opening a File ( fopen() ) The first parameter of this function contains the name of the file to be opened The second parameter specifies in which mode the file should be opened.

File Open Modes

Note If the fopen() function is unable to open the specified file, it returns 0 (false).

Example

Fclose()

Check end of file ( feof() ) We need to be aware of the End Of File (EOF) point.. feof($file) The feof() function checks if the "end-of-file" (EOF) has been reached. The feof() function is useful for looping through data of unknown length.

fgets() (Reading a File Line by Line) The fgets() function is used to read a single line from a file. Note: After a call to this function the file pointer has moved to the next line.

Example

fgetc() (Reading a File Character by Character) The fgetc() function is used to read a single character from a file. Note: After a call to this function the file pointer moves to the next character.

PHP Forms and User Input The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input. PHP Form Handling:-The most important thing to notice when dealing with HTML forms and PHP is that any form element in an HTML page will automatically be available to your PHP scripts.

Example Sample Output:- The example HTML page above contains two input fields and a submit button. When the user fills in this form and click on the submit button, the form data is sent to the "welcome.php" file.

PHP $_GET The $_GET variable is used to collect values from a form with method="get. The $_GET variable is an array of variable names and values sent by the HTTP GET method. Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address bar) it has limits on the amount of information to send (max. 100 characters).

Example

Why use $_GET? When using the $_GET variable all variable names and values are displayed in the URL. So this method should not be used when sending passwords or other sensitive information! However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.

PHP $_POST The $_POST variable is used to collect values from a form with method="post". The $_POST variable is an array of variable names and values sent by the HTTP POST method. Information sent from a form with the POST method is invisible to others It has no limits on the amount of information to send.

Example

Why use $_POST? Variables sent with HTTP POST are not shown in the URL Variables have no length limit However, because the variables are not displayed in the URL, it is not possible to bookmark the page.

PHP Cookies A cookie is often used to identify a user. What is a Cookie? A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.

What is a Cookie? A cookie is a small text file that is stored on a user s computer. Each cookie on the user s computer is connected to a particular domain. Each cookie be used to store up to 4kB of data. A maximum of 20 cookies can be stored on a user s PC per domain.

How to Create a Cookie? The setcookie() function is used to set a cookie. Note: The setcookie() function must appear BEFORE the <html> tag. Syntax:-

Syntax (set cookie) setcookie(name [,value [,expire [,path [,domain [,secure]]]]]) name value expire path domain secure cookie name data to store (string) UNIX timestamp when the cookie expires. Default is that cookie expires when browser is closed. Path on the server within and below which the cookie is available on. Domain at which the cookie is available for. If cookie should be sent over HTTPS connection only. Default false.

Example In the example below, we will create a cookie named "user" and assign the value "Alex Porter" to it. We also specify that the cookie should expire after one hour:

How to Retrieve a Cookie Value? The PHP $_COOKIE variable is used to retrieve a cookie value. In the example below, we retrieve the value of the cookie named "user" and display it on a page:

Cont d.. In the following example we use the isset() function to find out if a cookie has been set.

How to Delete a Cookie? When deleting a cookie you should assure that the expiration date is in the past.

PHP Session When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application.

PHP Session Variables When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn't maintain state.

Solution A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database. Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.

Syntax (Starting a PHP Session) Before you can store user information in your PHP session, you must first start up the session. Note: The session_start() function must appear BEFORE the <html> tag. The code above will register the user's session with the server, allow you to start saving user information, and assign a UID for that user's session.

Storing a Session Variable The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:

Example

Destroying a Session If you wish to delete some session data, you can use the unset() or the session_destroy() function. The unset() function is used to free the specified session variable. You can also completely destroy the session by calling the Session_destroy() function: Note: session_destroy() will reset your session and you will lose all your stored session data.