Introduction To Server-Side Programming

2y ago
35 Views
4 Downloads
1.36 MB
66 Pages
Last View : 5d ago
Last Download : 2m ago
Upload by : Angela Sonnier
Transcription

Introduction to Server-Side ProgrammingCharles Liu

Overview1.2.3.4.Basics of HTTPPHP syntaxServer-side programmingConnecting to MySQL

Request to a Static SiteServer:1. Homepagelookup2. Send as HTTPResponseHTTP Request: GET www.xkcd.comYou (client)Web serverHTTP Response: web content (HTML file)Client-side code: HTML, CSS, JavaScriptIP: 72.26.203.99

Request to a Dynamic Site!The server must respond dynamically if it needs to providedifferent client-side code depending on the situation! Date and time! Specifics of the user’s request! Database contents – forms and authenticationServer:1. Look up things that go onuser’s profile, such aswall posts and friends "caches, databaselookupsWeb server2. Generate client-sidecode containing theseHTTP Response: web content (HTML file)thingsClient-side code: HTML, CSS, JavaScript3. Send as HTTP responseHTTP Request: GET www.facebook.comYou (client)(dynamically generated by server)

sample http interactions› GET, data passed as query string

sample http interactions› POST, data passed as form data

http ››safe: no side effectsidempotent: doing twice same as oncePUT vs POST: PUT typically names a created objectPUT & DELETE used in APIs but not usually in browsers

response status codescategories of codes› 1xx informational› 2xx success› 3xx redirect› 4xx client error› 5xx server errormost common codes› 200 OK (request succeeded, resource is in message body)› 404 Not Found (resource doesn’t exist)› 303 See Other (resource moved, see location header)› 500 Server Error (web app implementer messed up)

Server-side options!PHP – today! Easyto start, lower learning curve! Potentially messy as your site grows!Javascript frameworks – node.js and Meteor.jsRuby on Rails!Other options – Django, Flask, Sinatra !

PHPIntroduction and Basic SyntaxCharles Liu

What is PHP?!!!PHP PHP: Hypertext PreprocessorServer-side scripting language that may beembedded into HTMLUltimate goal is to get PHP files to generate clientside code! mustend up with HTML, CSS, JavaScript, other clientside code!

Side-by-sidePHP File:Output: resulting HTML html head title PHP Introduction /title /head body This is HTML! br / ?phpecho 'This is PHP! br / ';? /body /html html head title PHP Introduction /title /head body This is HTML! br / This is PHP! br / /body /html

A closer look html head title PHP Introduction /title /head body This is HTML! br / ?phpecho 'This is PHP! br / '; // prints to screen/*Here's a longercommentthat spans multiplelines.*/? ! /body /html !!!PHP tags: ?php and ? The echo commandSingle line comment ( // )Multiple line comment (/* and */)

Viewing PHP files!!PHP files executed on the web serverSave .php files in subdirectory of web server/var/www/ on many Linux configurations! web scripts directory of your user directory on Athena!!Make call to web server via domain name(google.com), IP address (72.26.203.99), or localhostif on your own computer

PHPSyntax: Variables, Operators, and StringsCharles Liu

Variables!Store values for future reference, use variable nameto refer to the value stored in it x echoecho x !42;// x;// x 1;//‘hello!’ //store the value 42 in xprints 42prints 43, value of x is still 42type of x can changePHP is a loosely-typed language! Donot need to declare the type of a variable! Type can change throughout the program

Operators!Arithmetic operators! ,!!!-, *, /, % (modulus – remainder after division)Logical AND (&&), OR ( ), NOT (!)Assignment operators ( )Shorthand for assignment operators: y equivalent to x x y! Also works with subtraction, multiplication, division,modulus, and string concatenation! x

versus !Two “equality” operators! tests for “equality” in value but not necessarily type! tests for “identity” in value AND type! ignores the distinction between:! Integers,floating point numbers, and strings containingthe same numerical value! Nonzero numbers and boolean TRUE! Zero and boolean FALSE! Empty string, the string ‘0’ and boolean FALSE! Any other non-empty string and boolean TRUE

Strings!Concatenation of strings – the . operator a ‘hello’; b ‘world’;echo a . ‘ ‘ . b . ‘!’; // prints ‘hello world!’!String functions! Length:strlen()! Position of substring: strpos()! More on string functions:http://www.w3schools.com/php/php ref string.asp

PHPSyntax: Conditional and Looping StatementsCharles Liu

Conditional Statementsif (condition / boolean expression) {statements}else if (another condition) {statements}// there may be more than one else if blockelse {statements} x 5;if ( x 5) {echo ‘The variable x has value 5!’;}

Loops x 2;while ( x 1000) {echo x . “\n”; // \n is newline character x x * x;}do {echo x . “\n”; x x * x;} while ( x 1000);// note the semicolonfor ( i 1; i 10; i ) {echo i . “:” . ( i * i) . “\n”;}

PHPSyntax: Functions and Global VariablesCharles Liu

Defining your own functionsfunction function name ( arg1, arg2) {function parametersfunction codereturn var // optional}Example: a simple multiply functionfunction multiply( x, y) {echo x * y;echo “\n”;}multiply(5, 1.2); " prints 6 a 5; b 1.2;multiply( a, b); " prints 6 a array(1,2,3);multiply( a, b); " error a “string”multiply( a, b); " prints 0 (?!)

Return values!A function can return a value after it is done! Usethis value in future computation, use like a variable,assign value to a variablefunction multiply( x, y) {return x * y;}multiply(2,3); " prints nothing! returns value, but we don’t store anywhereecho multiply(2,3); " prints 6 a multiply(2,3); " assigns the value 6 to the variable a b multiply(multiply(2,3), multiply(3,4)); " assigns thevalue72 to the variable b

Variable scope!Variables declared within a function have local scope!Can only be accessed from within the function ?phpfunction function1() { // some code local var 5;echo local var 3;// this variable is LOCAL to// function1()// prints 8} // some codefunction1();echo local var;? // does nothing, since local var is// out of scope

Global variable scope!Variables declared outside a function have globalscope!Use global keyword to gain access within functions ?phpfunction function1() {echo a;// does nothing, a is out of scopeglobal a;// gain access to a within functionecho a;// prints 4} // some code a 4;// a is a global variablefunction1();?

PHPSyntax: ArraysCharles Liu

Arrays as a list of elements!Use arrays to keep track of a list of elements usingthe same variable name, identifying each element byits index, starting with 0 colors array(‘red’, ‘blue’, ‘green’, ‘black’, ‘yellow’);!To add an element to the array: colors[] ‘purple’;!To remove an element from the array:unset( colors[2]); colors array values( colors);

Arrays as key-value mappings!Use arrays to keep track of a set of unique keys and thevalues that they map to – called an associative array favorite colors array(‘Joe’ ‘blue’, ‘Elena’ ‘green’,‘Mark’ ‘brown’, ‘Adrian’ ‘black’, ‘Charles’ ‘red’);! To add an element to the array: favorite colors[‘Bob’] ‘purple’;!To remove an element from the array:unset( favorite colors[‘Charles’]);!Keys must be unique: favorite colors[‘Joe’] ‘purple’ overwrites ‘blue’

The for-each loop!The for-each loops allow for easy iteration over allelements of an array.foreach ( colors as color) {echo color; // simply prints each color}foreach ( colors as number color) {echo “ number color”; // prints color with index// to change an element:// colors[ number] new color;

PHPHTTP Requests and FormsCharles Liu

Superglobals!!A few special associative arrays that can beaccessed from anywhere in a PHP fileThe SERVER superglobal gives information aboutserver and client" server IP! SERVER[‘REMOTE ADDR’] " client IP! SERVER[‘HTTP USER AGENT’] " client OS andbrowser! SERVER[‘SERVER ADDR’]

Passing information to the server!Sometimes, we require additional values be passedfrom client to server! Login:username and password! Form information to be stored on server!GET request: pass information via the URL! http://www.yourdomain.com/yourpage.php?firstparam firstvalue&secondparam secondvalue! Access values server-side using GET superglobal# GET[‘firstparam’] ‘firstvalue’# GET[‘secondparam’] ‘secondvalue’

When to use GET vs. POST!!!!GET requests are sent via the URL, and can thus becached, bookmarked, shared, etcGET requests are limited by the length of the URLPOST requests are not exposed in the URL andshould be used for sensitive dataThere is no limit to the amount of information passedvia POST

Dealing with forms!!Forms are generally used to collect data, whetherthe data needs to be stored on the server(registration) or checked against the server (login)2 components to a form:! TheHTML generating the form itself! The server-side script that the form data is sent to (viaGET or POST), taking care of the processing involved# Servershould respond appropriately, redirecting the user tothe appropriate destination or generating the appropriatepage

Forms: client-side html head title A Form Example /title /head body form action "welcome.php" method "post" Name: br / input type "text" name "name" / br / Phone Number: br / input type "text" name "phone" / br / input type "submit" value "Submit" /form /body /html !!!form action – where to send the form datamethod – how to send the data (GET or POST)Name attributes become the keys used to access thecorresponding fields in the GET or POST arrays

Forms: server-side html head title This is welcome.php /title /head body The name that was submitted was:   ?php echo POST['name']; ? br / The phone number that was submitted was:   ?php echo POST['phone']; ? br / /body /html !A simple PHP file that displays what was enteredinto the form! Cando many other things server-side depending on thesituation

PHPCookies and SessionsCharles Liu

Cookies and sessions!!HTTP is stateless – it does not keep track of theclient between requestsBut sometimes we need to keep track of thisinformation! Shoppingcart! “Remember me” on login sites!2 solutions to this issue! Cookies– small file stored client-side! Sessions – relevant data stored on the server

cookies in httpcookie is› name-value pair› expiration, path & domainserver sends› using set-cookie headerbrowser sends back› all unexpired cookies› with matching pathexpiration› session cookies: on quit› persistent cookies: on expirea funny cookie talenytimes.com used cookiesto count #articles read, soviewers just deletedcookies.

Cookies!!Cookies are stored on the user’s browser, and aresent to the server on every relevant requestThe COOKIE superglobal makes a cookie a keyvalue pairing! Storeuser information as a value with a known key! Never assume a cookie has been set. Always check withisset( COOKIE[ cookie name]) before trying to usethe cookie’s value

The setcookie() function!To set a cookie in PHP:!setcookie(name, value, expire, path, domain);Name and value correspond to COOKIE[ name] value!Expiration – cookie will no longer be read after theexpiration!Useful to use time in seconds relative to the present:#!Path and domain refer to where on the site the cookie isvalid!!time() time in seconds until expirationUsually ‘/’ for path and the top-level domain (yoursitename.com)To delete a cookie, set a new cookie with same argumentsbut expiration in the past

Setting cookies!Cookies are set via the HTTP header! Mustbe sent before the body – before any HTML, CSS,JS, etc.!This code will not work:if(isset( COOKIE["6470"])) { value COOKIE['6470'];echo "Cookie is set to value";}else { value 0;}// after echo statement: will not work!setcookie("6470", value 1, time() 60*60);?

Sessions!Two main disadvantages of cookiesLimited in size by browser! Stored client-side " users / malicious people can change!!Sessions store user data on the serverLimited only by server space! Cannot be modified by users!!!A potential downside to sessions is that they expirewhen the browser is closedSessions are identified by a session id: often a smallcookie! But the rest of the data is still stored on theserver

Using sessions!Call session start() at top of every page to start session!!Sets a cookie on the client: must follow same rules as cookies(before any HTML, CSS, JS, echo or print statements)Access data using the SESSION superglobal ?phpsession start();if (isset( SESSION["count"])) { SESSION["count"] 1;echo "You\'ve visited here { SESSION['count']}times";}else { SESSION["count"] 1;echo "You\'ve visited once";}?

Removing sessions!Remove an individual element of the SESSIONsuperglobal! unset( SESSION[‘key name’]);!Destroy the entire session, remove all data! Usethe function session destroy()! SESSION no longer valid! Will need to call session start() to start a new session

Recap: a comparisonCOOKIESSESSIONSWhere is data stored?Locally on clientRemotely on serverExpiration?Variable – determinedwhen cookie is setSession is destroyedwhen the browser isclosedSize limit?Depends on browserDepends only on server(practically no sizelimit)Accessing information? COOKIE SESSIONGeneral use?Remember small thingsabout the user, such aslogin name. Rememberthings after re-openingbrowserRemembering varyingamount of data aboutthe user in onebrowsing “session”.More sensitive info.

PHPMySQLCharles Liu

Databases and MySQL!!Databases give us an easy way to issue“commands” to insert, select, organize, and removedataMySQL: open-source database, relatively easy toset up, easy to use with PHP! OtherSQL databases, as well as non-SQL options suchas MongoDB

Connecting to MySQL!!MySQL database server can contain manydatabases, each of which can contain many tablesConnecting to the server via PHP: db mysql connect(server, username, password);if (! db) {// terminate and give error messagedie(mysql error());}mysql select db(database name, db);! db is a database resource type. We use thisvariable to refer to the connection created

Making SQL queries!PHP function for making queries:mysql query(query string, db resource);!Queries that return information, such as SELECT:returns a resource result mysql query(query string, db);! In!!this case, this resource is stored in the variable resultOther queries, returns TRUE upon success.All queries return FALSE on failure. Best practice isto handle the error (e.g. die(mysql error()))

Retrieving information from a query!Loop over the returned result resource, row by row result mysql query(query, db);while ( row mysql fetch assoc( result)) { col1 row['column 1 name']; col2 row['column 2 name'];// and so forth.}

A shared database resource!!Don’t repeat code - put database connection, selectdatabase code into the same fileReference the connection resource ( db) in otherfiles (using include( file path))

SQL queries!!!INSERT INTO table name (col1, col2 ) VALUES(val1, val2 )SELECT col1, col2 FROM table name WHEREconditionsCREATE TABLE table name (column namedata type(size), column name data type(size) )

The relational model!!Indicate relations between objects (rows) with an id" a pointer to a row in a different tableThe INNER JOIN

what is a relational database?a relation is a set of tuples› tuple is ordered, set isn’ta relational database is› a set of named relations› with named Alertaa@mitaaClosure cc@mitblahBitdiddle ben@mit contentyummy!neatrating54about21

query operatorsrelational algebra operators› select: filter rows by a predicate› project: filter by columns› product: combine two tablesin SQL, all parts of select statement-- show content and ratings of reviews about Cloverselect content, rating from subjects, reviewswhere subjects.id reviews.about and name "Clover"

deconstructing a -- product operator (implicit in list of tables)select * from subjects, reviewsexamples from RazorSQL: available at http://www.razorsql.com/

deconstructing a -- selection operator (where)select * from subjects, reviewswhere subjects.id reviews.about and name "Clover"

deconstructing a -- projection operator (implicit in list of columns)select content, rating from subjects, reviewswhere subjects.id reviews.about and name "Clover"

your turnwhat does this query say?select distinct name from subjects, reviewswhere rating 5reviewscategssubjects users-- lists all subject names: oops!

special operators› order by: sort the results by some column› sum, avg, count, max, min› group by: group rows before applying functions-- show subjects and their average ratingsselect name, avg(rating) from subjects, reviewswhere reviews.about subjects.id group by subjects.id-- show reviews ordered by ratingselect name, content, rating from subjects, reviewswhere reviews.about subjects.id order by rating

PHPConclusionCharles Liu

What we’ve talked about !!!!Purpose of server-side programmingBasic PHP syntax, arrays, functionsSpecifics to websites: cookies, sessions, HTTPrequests and forms, MySQLOther server-side solutions:! ASP.NET! Python!PHP’s extensive documentation:http://www.php.net/manual/en

PHP workshop and tomorrow!!Mostly to get you set up with a PHP server, writesome simple codeTomorrow: more server-side frameworks! Node.js! Meteor.js!35-225, 11AM

Introduction and Basic Syntax Charles Liu . What is PHP? ! PHP PHP: Hypertext Preprocessor ! Server-side scripting language that may be embedded into HTML ! Ultimate goal is to get PHP files to generate client-side code ! must end up with HTML, CSS, JavaScript, other client-side code! Side-by-side PHP File: .

Related Documents:

Server Side Scripting merupakan sebuah teknologi scripting atau pemrograman web dimana script (program) dikompilasi atau diterjemahkan di server. Dengan server side scripting, memungkinkan untuk menghasilkan halaman web yang dinamis. Beberapa contoh Server Side Scripting (Programming) : 1. ASP (Active Server Page) dan ASP.NET 2.

When provisioning a Windows Server for a specific role there are additional items to consider for further securing the server. When planning and provisioning your server layout, designate one primary purpose per server. Whenever possible, designate one server as the database server, one server as the web server, and one server as the file server.

Server 2005 , SQL Server 2008 , SQL Server 2008 R2 , SQL Server 2012 , SQL Server 2014 , SQL Server 2005 Express Edition , SQL Server 2008 Express SQL Server 2008 R2 Express , SQL Server 2012 Express , SQL Server 2014 Express .NET Framework 4.0, .NET Framework 2.0,

Introduction 1-2 Oracle Forms Server and Reports Server Installation Guide Introduction Oracle Forms Server and Reports Server is an integrated set of database tools i Oracle Forms i. Oracle Forms Server Server and Reports Server Server. UNIX. Installation Guide Compaq Tru64 .

Pemrograman Web dengan PHP dan MySQL Achmad Solichin (achmatim@gmail.com) 7 Bab 1 Pengenalan Web Server dan Server Side Scripting Pengenalan Web Server Instalasi dan Konfigurasi Web Server Instalasi dan Konfigurasi PHP Testing Web Server dan PHP Web Server Web Server merupakan sebuah perangk

Administrasi Server Sementara itu peta konsep mata pelajaran menjelaskan struktur urutan kegiatan belajar dan topik materi pelajaran. Gambar 2 dibawah ini menjelaskan peta konsep mata pelajaran Administrasi Server kelas XI semester 2. Administrasi Server 2 1. Server FTP 2. Server e-Mail 3. Server WebMail 4. Server Remote 5. Server NTP 6. Server .

System x3650 Type 7979 Turn off the server and install options. Did the server start correctly? Yes No Go to the Server Support flow chart on the reverse side of this page. Start the server. Did the server start correctly? Yes No Install the server in the rack cabinet and cable the server and options; then, restart the server. Was the server .

programming, pengertian server side programming dan client side programming, serta alasan mengapa memilih PHP. Tak lupa pula akan dijelaskan tool apa saja yang diperlukan untuk belajar PHP. Tentang Client Side dan Server Side Programming PHP atau merupakan singkatan rekursif dari PHP : Hypert