230 questions

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

Q1-1 How do web browsers help prevent XSS attacks

Modern browsers have the XSS Filter to help prevent XSS attacks . This filter is turned on by default .If a cross-site scripting attack is detected(vulnerabilities are found), the browser will disable the harmful scripts

Q1-1 Do you believe that separation is actually achievable given current web standards? Please provide a concrete example, together with reasons for your answer.

No. It's not achievable. Separation is the way lead to good web application structure. can also lead to better performance, since imported file can be cached. But some time it is not hard to see many embedded js and css in the HTML file. not all the developer like to follow the same rule. e.g. we can still say inline style css which apply to a certain single element for some reason : <p style="color:green">This is a paragraph.</p> which is bad for seperation and future maintainance.

Q2-1 How would you check, using PHP, if browser cookies are enabled?

The following example creates a small script that checks whether cookies are enabled. First, try to create a test cookie with the setcookie() function, then count the $_COOKIE array variable: <?php setcookie("test_cookie", "test", time() + 3600, '/'); ?> <?php if(count($_COOKIE) > 0) { echo "Cookies are enabled."; } else { echo "Cookies are disabled."; } ?>

Q3-1 Demonstrate how you could use AJAX to update DIV element in a web document with the contents of a JSON file located on some server.

Using js to create ajax connect with the server to request json file, which contains the arttribute of the div. And then use javascript document to set to arttribute value to the elements on the page Json: {"divs":[ {"backgound":"red", "height":"10px"} ]} Js: $.ajax({ url: "xx.json", dataType: "json", data:data, success: function(response){ Var json_obj = JQuery.parseJSON(response); $("mydiv").css("background", json_obj[0].background); $("mydiv").css("height", json_obj[0].val); } } });

Q3-2 When using XML, it is common to use attributes to represent metadata, rather than creating additional child elements. How would you represent XML attributes using JSON? Use a specific example, and provide both JSON and XML code in your answer.

XML with attributes convert to Json : consider the attribute as the child element of the current level. From the example below we can see, the "id" and "order" attribute of the "entry" element , are considered as child elements of the "entry" elemet in json. <entries> <entry id ="1" order ="2"> <date>20040202</date> <todo>buy apple</todo> </entry> </entries> Json: { "entry": [ { "id": "1", "order":"2", "date": "20040202", "todo": "buy apple" } ] }

Q1-1 Describe "Cross Site Scripting (XSS)"

XSS enables attackers to inject scripts into web pages viewed by other users. which bring system security problems to the web application.

Q1-1 Describe the difference between HTTP GET and POST requests.

difference : GET POST GET: 1.Can be bookmarked 2. GET is less secure compared to POST because data sent is part of the URL 3. the GET method adds the data to the URL; and the length of a URL is limited POST: 1.Cannot be bookmarked 2. POST is a little safer than GET because the parameters are not stored in browser 3. parameter No Restrictions

Q3-2 Give an example of a JSON and XML representation of a calendar "todo" entry.

{ "entries": [ { "date": "20040202", "todo": "buy apple" }, { "date": "20040203", "todo": "go to bank" }, { "date": "20040206", "todo": "finish assignment" } ] } Xml: <?xml version="1.0" encoding="UTF-8" ?> <entries> <entry> <date>20040202</date> <todo>buy apple</todo> </entry> <entry> <date>20040203</date> <todo>go to bank</todo> </entry> <entry> <date>20040206</date> <todo>finish assignment</todo> </entry> </entries>

Q1-1 xss attack example:

welcome .php: Welcome <?php echo $_GET["name"]; ?> Request url: welcome.php?name= <script>alert('attacked')</script>

Q3-1 Demonstrate how you could use jQuery to create a simple modal dialog that overlays an entire page with a black tint, disabling all links and bringing into focus anything above it.

$(function() { var docHeight = $(document).height(); $("body").append("<div id='overlay'></div>"); $("#overlay") .height(docHeight) .css({ 'opacity' : 0.4, 'position': 'absolute', 'top': 0, 'left': 0, 'background-color': 'black', 'width': '100%', 'z-index': 5000 }); $('a').bind("click.myDisable", function() { return false; }); });

Q3-2 What are the advantages and disadvantages of using JSON over XML for data structure and transport?

Advantages of JSON: 1. JSON is Faster: JSON syntax is very easy to use. Since its syntax is very small and light weighted. so it executes the response in faster way. 2. Browser Support: It has wide range of supported browser compatibility with the operating systems . 3. Server Parsing: the server side parsing is fast, so client get fast response . Disadvantages of JSON: 1. First and foremost, in JSON has no error handling for JSON calls. 2. can be quite dangerous if used with untrusted services or untrusted browsers.

Q2-3 Sample Question: Explain the differences between MySQLi and PDO, with reference to database connectivity using PHP.

Both MySQLi and PDO have their advantages: 1.PDO will work on 12 different database systems, where as MySQLi will only work with MySQL databases. So, if you have to switch your project to use another database, PDO makes the process easy. You only have to change the connection string and a few queries. With MySQLi, you will need to rewrite the entire code - queries included. 2.Both are object-oriented, but MySQLi also offers a procedural API. Both support Prepared Statements. Prepared Statements protect from SQL injection, and are very important for web application security.

Q4-1 . Using appropriate code examples, show how it is possible to implement an MVC-based application using AngularJS for development.

Code example (AngularJS): View: index.html <html> <head lang="en"> <meta charset="UTF-8"> <title>AngularJS Tutorial</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular.min.js"></script> </head> <body ng-app="app" ng-controller="MainController as main"> <div class="container"> <h1>{{main.title}}</h1> </div> </body> </html> App.js: angular.module('app', []); Main.ctrl.js angular.module('app').controller("MainController", function(){ var vm = this; // ViewModel vm.title = 'AngularJS Tutorial Example'; });

Q3-2 Describe briefly, using relevant code fragments, how to use PHP to issue a RESTful POST request to a web service.

PHP issue a RESTful POST $curl = curl_init('http://example.com'); $data = array( 'a' => 'b', 'c' => 'd'); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); $response = curl_exec($curl); curl_close($curl);

Describe the features of a Single-page Application (SPA) implementing an MVVM design pattern.

MVVM is based on MVC , which attempts to separate more clearly the development of User Interfaces (UIs/frontend) from that of the business logic and behavior in an application. Model view vew-model: MVVM, the state of the view is continuously connected to the ViewModel(has some features similar to the controller) MVVM is used to two-way bind data within views. This is usually a client-side implementation(Angular.js) in MVVM, controllers will typically contain all processing logic and decide what data to display in which views using which view models. • Model: This represents domain-specific data or information that our application will be working with. Models hold information, but typically don't handle behavior. They don't format information or influence how data appears in the browser as this isn't their responsibility. • View: This is the only part of the application that the users actually interact with. It contains the data bindings and events and behaviors, it is an interactive UI that represents the state of a ViewModel. View isn't responsible for handling state—it keeps this in sync with ViewModel. • ViewModel: This can be considered as a specialized Controller that acts as a data converter. It changes Model information into View information, passingcommands from View to Model. Views and ViewModels communicate using data-bindings and events. The following is the pictorial representation of how MVVM works: In MVC, the View sits on top of our architecture with the Controller below it.Models sit below the controller, and so our Views know about our Controllers, and Controllers know about Models. Here, our Views have direct access to Models. However, exposing the complete Model to the View might have security and performance costs, depending on the complexity of our application. MVVM attempts to avoid these issues.

Q3-1 Demonstrate how you could use AJAX to update DIV element in a web document with the contents of an XML file located on some server.

Using js to create ajax connect with the server to request xml file, which contains the arttribute of the div. And then use javascript document to set to arttribute value to the elements on the page Xml: <divElement> <background>red</background> <height>10px</height> </divElement> Js: $.ajax({ type: "GET", url: "xx.xml", dataType: "xml", success: function(xml){ $(xml).find('divElement').each(function(){ var background = $(this).find('background').text(); var height = $(this).find('height').text(); }); }, complete: function() { $("mydiv").css("height", height); $("mydiv").css("background", background); } }); }

Q3-2 Sample Question: What are "Web Services"? Outline the similarities and differences between REST and SOAP services?

Web services Web Services work on client-server model where client applications can access web services over the network. Web services provide endpoint URLs and expose methods that can be accessed over network through client programs Web services are the serivers runing on the server side, that can interpret the request and response the requested content. Most common web services are REST and SOAP. similarities between REST and SOAP They are the ways to access Web services. SOAP and REST share similarities over the HTTP protocol. Diffrerence between REST and SOAP SOAP Web Services: Runs on SOAP protocol and uses XML technology for sending data. Restful Web Services: It's an architectural style and runs on HTTP/HTTPS protocol almost all the time. REST is a stateless client-server architecture where web services are resources and can be identified by their URIs. Client applications can use HTTP GET/POST methods to invoke Restful web services.

Q1-1 Show the typical HTTP dialogue between a client and web server, where the client issues a POST request with three name/value pairs.

curl -X POST --data "name1=value1&name2=value2&name3=value3" http://localhost/xx.php webserver receive the request and find the request file "xx.php" and then response by sending notice html file content to client browser. Client sent request to server: Accept-Language : en Connection: keep-alive Host : localhost:1234 Referer: http://localhost/post.php User-Agent: curl name1=value1&name2=value2&name3=value3 Server response with refered file: Connection: Keep-Alive Content-Length: 6 Content-Type: text/html Date : Wed, 27 Apr 2016 16:24:15 GMT Server: Apache(Unix)

Give an example of using a prepared statement within PHP to save multiple records to a database.

an example of using a prepared statement <?php $conn = new mysqli("localhost", "root", "123456", "mydb"); $stmt = $conn->prepare("INSERT INTO users (username, password) VALUES (?, ?)"); $stmt->bind_param("ss", $username, $password); // set parameters and execute $username = "Marry"; $password = "11111111"; $stmt->execute(); $username = "Tom"; $password = "12345678"; $stmt->execute(); echo "New records created successfully"; $stmt->close(); $conn->close(); ?>

Q4-1 Is it possible to develop scalable and maintainable full-stack applications using JavaScript? Give reasons for your answer

https://www.smashingmagazine.com/2013/11/introduction-to-full-stack-javascript/ MEAN is a JavaScript software stack for building dynamic web sites and web applications .It makes use of collection of JavaScript-based technologies: MongoDB, Express.js, AngularJS, and Node.js. MEAN applications can be written in one language for both server-side and client-side execution environments. NODE.JS Node.js is a platform for building fast and scalable network applications. It's the hottest JavaScript runtime environment around right now, used by a ton of applications and libraries — even browser libraries are now running on Node.js. More importantly, this fast server-side execution allows developers to focus on more complex problems, such as Natural for natural language processing. MONGODB MongoDB is a NoSQL document-based database that uses JavaScript as its query language (but is not written in JavaScript), thus completing our end-to-end JavaScript platform. MongoDB is schema-less, enabling you to persist objects in a flexible way and, thus, adapt quickly to changes in requirements. Plus, it's highly scalable and based on map-reduce, making it suitable for big data applications. MongoDB is so flexible that it can be used as a schema-less document database, a relational data store (although it lacks transactions, which can only be emulated) and even as a key-value store for caching responses, like Memcached and Redis. Angular Express.js is a Node.js web application server framework, designed for building single-page, multi-page, and hybrid web applications. Express.js is a Node.js web application server framework, designed for building single-page, multi-page, and hybrid web applications.Server Componentization is easier With Express With JavaScript, you can create scalable, maintainable applications, unified under a single language.

Q1-1 Outline how XSS prevention might be incorporated into your web application design:

when we developing web application we should use htmlspecialchars() , it converts special characters to HTML entities " Welcome <?php echo htmlspecialchars($_GET["name"]); ?> " this function would convert content in the name variable it into HTML entities, so that content written in script pattern wont be recognize by javascipt engine and executed. Therefore the injection stopped.

Q3-2 Describe briefly, using relevant code fragments, how to implement two CRUD functions using Javascript. Assume you are consuming a RESTful web service.

two CRUD functions using Javascript Create, Read, Update, and Delete operations are also known as CRUD POST, GET, PUT, and DELETE Creat: $.ajax({ url: '/echo/html/', type: 'PUT', data: "name=John&location=Boston", success: function(data) { alert('Load was performed.'); } }); Read: $.ajax({ url: "http://rest-service.guides.spring.io/greeting" , dataType: 'json', Type:"GET", success: function (response) { var json_obj = $.parseJSON(response); $('.greeting-id').append(json_obj[0].id); $('.greeting-content').append(json_obj[0].content); } }); Delete: $.ajax({ url: this.createProductUrl('DELETE'), dataType: 'json', type: 'DELETE', success: function (result) { if (result.errors) alert(result.errors[0].message); } });

Q1-3 Write a suite of javascript functions, which are automatically executed after a page loads, that informs the user (using an in-page dialog) that site-usage requires acceptance of terms of service (ToS). The dialog should contain a message and two buttons which may be used to agree or disagree to the ToS, together with a link to the ToS page. The dialog should continue to be presented until the either button has been pressed by the user. Clicking the ToS link should open the ToS page in a new window or tab. The dialog should be a CSS-styled DIV element which is located in the centre of the window and, while visible, disables access to page content. Accepting the ToS should ensure the modal dialog disappears is never re-presented on subsequent visits. Unaccepting the ToS should ensure redirection to another site, and continued re-presentation of the dialog on subsequent visits. You may assume that writeCookie() and readCookie() functions exist; you do not have to develop the internal content of these functions.

#note { background:grey; color: red; font-size: 10px; border: 2px solid black; position: fixed; top: 50%; left: 50%; } <div id='note'> <p> Please notice that site-usage requires acceptance of terms of service (ToS)</p> <button type='button' onclick='disagree()'>unaccept</button> <button type='button' onclick='agree()' >accept</button> <a href="http://www.google.ie" target="_blank">TOS details</a> </div> loadNotice =function(){ if(readCookie("notice")=="agree"){ document.getElementById('note').style.visibility = 'hidden'; }else{ document.getElementById('note').style.visibility = 'show'; } } loadNotice(); agree = function(){ writeCookie("notice","agree"); document.getElementById('note').style.visibility = 'hidden'; } disagree = function(){ window.location.replace("http://stackoverflow.com"); }

Q1-3 Sample Question: Write a suite of javascript functions, which are automatically executed after a page loads, that informs the user (using an in-page dialog) about new website site features. The dialog should contain a message, links and brief description of two "top new features", and single button which is used to receive acknowledgement from the user that they no longer wish to be informed about new site features (i.e. hide message). The dialog should continue to be presented until the acknowledgement (hide) button has been pressed by the user. The dialog should be a CSS-styled DIV element which is located at the top of the page and, while visible, is displayed inline within page content. You may assume that writeCookie() and readCookie() functions exist; you do not have to develop the internal content of these functions.

#note { background:grey; color: red; font-size: 10px; border: 2px solid black; width:100%; top: 0px; float: left; //inline style } <div id='note'> <p> New Features</p> <a href="http://www.google.ie" target="_blank">Feature1</a> <a href="http://www.stackoverflow.com" target="_blank">Feature2</a> <button type='button' onclick='dontshow()' >don't show me again</button> </div> loadNotice =function(){ if(readCookie("notice")=="dontshow"){ document.getElementById('note').style.visibility = 'hidden'; document.getElementById('note').style.clear = "left"; }else{ document.getElementById('note').style.visibility = 'show'; } } loadNotice(); dontshow = function(){ writeCookie("notice","dontshow"); document.getElementById('note').style.visibility = 'hidden'; document.getElementById('note').style.clear = "left"; }

Q4-3 Sample Question: Demonstrate, using skeleton code fragments where appropriate, how Node.js, Express.js and mongodb may be used to create a basic RESTful API for use by a Single Page Application (SPA). You are not required to provide detailed code examples Sample Question: Demonstrate, using skeleton code fragments where appropriate, how a Single Page Application (SPA) developed using the Anjular.js framework, communicates with Node.js, Express.js and mongodb using a RESTful interface. You are not required to provide detailed code examples.

// server.js var express = require('express'); var app = express(); // create our app w/ express var mongoose = require('mongoose'); // mongoose for mongodb var morgan = require('morgan'); // log requests to the console (express4) var bodyParser = require('body-parser'); // pull information from HTML POST (express4) var methodOverride = require('method-override'); // simulate DELETE and PUT (express4) mongoose.connect('mongodb://localhost:27017/todo'); // connect to mongoDB database todo app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users app.use(morgan('dev')); // log every request to the console app.use(bodyParser.urlencoded({'extended':'true'})); // parse application/x-www-form-urlencoded app.use(bodyParser.json()); // parse application/json app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json app.use(methodOverride()); app.listen(8080); console.log("App listening on port 8080"); var Todo = mongoose.model('Todo', { text : String }); // routes ====================================================================== app.get('/api/todos', function(req, res) { Todo.find(function(err, todos) { if (err){ res.send(err) } res.json(todos); }); }); app.post('/api/todos', function(req, res) { Todo.create({ text : req.body.text, done : false }, function(err, todo) { if (err){ res.send(err); } Todo.find(function(err, todos) { if (err){ res.send(err) } res.json(todos); }); }); }); // public/core.js var scotchTodo = angular.module('scotchTodo', []); function mainController($scope, $http) { $scope.formData = {}; // when landing on the page, get all todos and show them $http.get('/api/todos') .success(function(data) { $scope.todos = data; console.log(data); }) .error(function(data) { console.log('Error: ' + data); }); // when submitting the add form, send the text to the node API $scope.createTodo = function() { $http.post('/api/todos', $scope.formData) .success(function(data) { $scope.formData = {}; // clear the form so our user is ready to enter another $scope.todos = data; console.log(data); }) .error(function(data) { console.log('Error: ' + data); }); }; } <!-- index.html --> <!doctype html> <html ng-app="scotchTodo"> <head> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script> <script src="core.js"></script> </head> <body ng-controller="mainController"> <!-- TODO LIST --> <div id="todo-list" > <div class="checkbox" ng-repeat="todo in todos"> <p>{{ todo.text }}</p> </div> </div> <!--FORM --> <div> <form> <input type="text" ng-model="formData.text"> <button type="submit" ng-click="createTodo()">Add</button> </form> </div> </body> </html>

Q1-1 Describe, using a specific example, how web developers achieve separation of web application structure, presentation and behavior using JavaScript, HTML and CSS.

1. HTML to define the content of web pages 2. CSS to specify the layout of web pages 3. JavaScript to program the behavior of web pages The separation of the three part achive by the following syntax, put the HTML, CSS, Js in three different type of files and then put the reference in the html file's header. <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="mystyle.css"> <script src="myScript.js"></script> </head> <body> <h1>This is a Heading</h1> <p>This is a paragraph.</p> </body> </html>

Q2-2 Sample Question: Write a PHP script that includes a single CSS styled form, together with its processor, that allows a user to register (create) a username and password. You should validate the password using two input boxes, checking that the same text has been entered in both input boxes, and that the password is at least 8 characters in length. Your script should returns a CSS styled message confirming the submission by showing the username, for example, "Congratulations John; you are now registered!" if the username has not been previously used by another user. Otherwise you need to represent the from, recommending that the user choose another username. For this script you only need to compare the input with an PHP array of usernames; you do not need to configure a database.

<!DOCTYPE html> <html> <head> <style> p { color: grey; font-size: 30px; } </style> <script> doSubmit =function(){ var alreadyUsed = ["Mary", "Tom", "Jack"]; var username = document.getElementById("username").value; var password1 = document.getElementById("password1").value; var password2 = document.getElementById("password2").value; for (i = 0; i < alreadyUsed.length; i++) { if(alreadyUsed[i]==username){ document.getElementById('warning').innerHTML ="Please chose another username."; return false; } } if(password1!=password2){ return false; } if(password1.length<8){ return false; } return true; } </script> </head> <body> <?php if (isset($_POST["submit"])){ echo "Congratulations ".$_POST["username"]."; you are now registered !"; } ?> <div id="warning"></div> <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post" onsubmit="return doSubmit();"> <p>username:</p><input type="text" name="username" id="username"><br> <p>password:</p><input type="password" name="password1" id ="password1"><br> <p>retype password:</p><input type="password" name="password2" id ="password2"><br> <input type="submit" name="submit" value="submit"> </form> </body> </html>

Q2-2 Write a PHP script that includes a single CSS styled form, together with its processor, that allows a user to register (create) a username and password. You should validate the password using two input boxes, checking that the same text has been entered in both input boxes, and that the password is at least 8 characters in length. Your script should returns a CSS styled message confirming the submission by showing the username and password with only the first and last characters of the password visible; with all other letters are replaced with the "*"character, for example, "Congratulations John; you are now registered with password P******D!".

<!DOCTYPE html> <html> <head> <style> p { color: grey; font-size: 30px; } </style> <script> doSubmit =function(){ var password1 = document.getElementById("password1").value; var password2 = document.getElementById("password2").value; if((password1==password2)&&(password1.length>=8)){ return true; }else{ return false; } } </script> </head> <body> <?php if (isset($_POST["submit"])){ $password = $_POST["password1"]; echo "Congratulations ".$_POST["username"]." you are now registered with password " .substr( $password, 0, 1 )."******".$password{strlen($password)-1}. "!"; } ?> <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post" onsubmit="return doSubmit();"> <p>username:</p><input type="text" name="username" id="username"><br> <p>password:</p><input type="password" name="password1" id ="password1"><br> <p>password again:</p><input type="password" name="password2" id ="password2"><br> <input type="submit" name="submit" value="submit"> </form> </body> </html>

Q2-2 Write a PHP script that includes a single CSS styled form, together with its processor, that accepts as input a user's name and email address, and returns a CSS styled message confirming the valid input. You should validate the form data using Javascript prior to submission to the processor, ensuring that the email address is valid. You must also ensure that the processor is not susceptible to any form of injection attack.

<!DOCTYPE html> <html> <head> <style> p { color: grey; font-size: 30px; } </style> <script> doSubmit =function(){ var email = document.getElementById("email").value; if(email.indexOf("@") > 0){ return true; }else{ return false; } } </script> </head> <body> <?php if (isset($_POST["submit"])){ echo "your input is valid"; } ?> <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post" onsubmit="return doSubmit();"> <p>username:</p><input type="text" name="username" id="username"><br> <p>email:</p><input type="text" name="email" id ="email"><br> <input type="submit" name="submit" value="submit"> </form> </body> </html>

Q2-1 How could you, using PHP, determine the IP address from where the user is viewing the current page

<?php Echo getenv('REMOTE_ADDR'); Echo $_SERVER['REMOTE_ADDR']; Echo $_SERVER['REMOTE_HOST']; ?>

Q2-1 Write PHP code that manages a counter within a PHP session. The counter should be incremented each time a page is visited within a session. Indicate, using code examples, how you may destroy all, and specific, PHP sessions.

<?php session_start(); //start session if(isset($_SESSION["counter"])){ $_SESSION["counter"] = $_SESSION["counter"]+1; }else{ $_SESSION["counter"]=0; } how you may destroy all, and specific, PHP sessions. // remove all session variables session_unset(); // destroy the session session_destroy(); //remove specific seesion unset($_SESSION['session_var']);

Q1-2Write Javascript (JS) functions showDiv() andhideDiv(), that show and hide a DIV element, respectively. Create appropriate CSS to style links (<a>...</a>) so that they appear in red with a "hand" type cursor, and without underlining. Create an HTML page with sample links that, whenever the mouse hovers over the link, a DIV element containing a single line of text appears to the right of the mouse pointer. Provide the complete HTML, CSS and JS for this example, including the DIV element, button and their respective CSS styles.

<a onmouseenter="showDivRight(event,'d2')" onmouseleave="hideDivRight(event,'d2')">link</a><div id = 'd2' style='position: fixed;display:none;'>text right to the cusor</div> a{ text-decoration: none ; color:red; cursor:pointer; } showDivRight = function(e,divid){ var left = e.clientX + "px"; var top = e.clientY + "px"; var div = document.getElementById(divid); div.style.left = left; div.style.top = top; document.getElementById("d2").style.display = "block"; } hideDivRight = function(e,divid){ document.getElementById("d2").style.display = "none"; }

Q1-2 Write Javascript (JS) functions showDiv() andhideDiv(), that show and hide a DIV element, respectively. Create an HTML button that may be used to toggle the visibility of a specified DIV element when clicked. Provide the complete HTML, CSS and JS for this example, including additional JS (toggle) functions, the DIV element, button and their respective CSS styles.

<div id = 'd1' style="display:block;">This is the div</div> <button onclick="toggleDiv()">show/hide</button> showDiv = function(){ document.getElementById("d1").style.display = "block"; } hideDiv = function(){ document.getElementById("d1").style.display = "none"; } toggleDiv = function() { var current = document.getElementById("d1").style.display; if(current == 'none'){ showDiv(); } if(current == 'block'){ hideDiv(); } }

Q1-2 Write a Javascript (JS) function changeAll() that restyles all numbers in a specified DIV element containing some text when a button is clicked by the user. The restyling should underline all numbers, for example, "There are 7 words in this sentence!" would be changed to "There are 7_ words in this sentence!". Please provide the HTML code for the button that is used to invoke changeAll().

<div id ='text1'>There are 7 words in this sentence!</div> <button onclick="changeAll()">Click me</button> changeAll = function() { var str1 = document.getElementById('text1').innerHTML.trim(); var result = ''"; for(var i = 0; i<str1.length; i++){ var charater = str1[i]; if(!isNaN(charater)&&charater!=' '){ //get the number result+= '<u>'+charater+'</u>'; }else{ result +=charater; } } document.getElementById('text1').innerHTML = result; }

Q1-3 Sample Question: Write a suite of javascript functions, which are automatically executed after a page loads, that informs the user (using an in-page modal dialog) that site-usage requires the user's acceptance of cookie usage before progressing. The dialog should contain a message and two buttons which may be used to agree or disagree to cookie usage. The dialog should continue to be presented until the either button has been pressed by the user. The dialog should be a javascript-styled dialog which is located in the centre of the window and, while visible, prevents access to page content. Accepting cookie usage should ensure the modal dialog disappears is never re-presented on subsequent visits. Unaccepting cookie usage should ensure redirection to another site, and continued re-presentation of the dialog on subsequent visits. You may assume thatwriteCookie() and readCookie() functions exist; you do not have to develop the internal content of these functions.

<div id='note'> <p> Please notice that site-usage requires acknowledgement of cookie usage</p> <button type='button'>NO!</button> <button type='button' onclick='agree()' >OK!</button> </div> #note { background:grey; color: red; font-size: 10px; border: 2px solid black; position: fixed; top: 50%; left: 50%; } loadNotice =function(){ if(readCookie("notice")=="agree"){ document.getElementById('note').style.visibility = 'hidden'; }else{ document.getElementById('note').style.visibility = 'show'; } } loadNotice(); agree = function(){ writeCookie("notice","agree"); document.getElementById('note').style.visibility = 'hidden'; }

Q2-1 Describe, using appropriate PHP code examples, the following PHP super globals: $_REQUEST, $_POST and $_GET.

<form action="script.php" method="get"> User: <input type="text" name="user" /><br /> <input type="submit" value="Send" /> </form> $user = $_GET['user']; Set the form method to "post": $user = $_POST['user']; The PHP $_REQUEST variable is a superglobal Array that contains the contents of both $_GET, $_POST: <form action="script.php?id=789" method="post"> $id = $_REQUEST['id']; $user = $_REQUEST['user'];

Q1-2 Using a suitable diagram, together with sample HTTP headers, demonstrate the flow of data between a web client and a web server, where the client issues a GET request via an HTML form.

<form action="xx.php" method="get"> name1: <input type="text" name="name1"> name2: <input type="text" name="name2"> <input type="submit" value="Submit"> </form> Click submit then the url change to http:///localhost/xx.php?name1=value1&name2=value2 HEADER: Accept-Language : en-US Connection: keep-alive Host : localhost Referer: http://localhost/get.php User-Agent : Firefox ( Ubuntu) Server response with refered file: Connection: Keep-Alive Content-Length: 6 Content-Type: text/html Date : Wed, 27 Apr 2016 16:24:15 GMT Server: Apache(Unix) FLOW: After the request url change to -> http:///localhost/xx.php?name1=value1&name2=value2 sent to the webserver. Webserver will transfer the value to the requested file , in this case "xx.php" the php file will make of the value , and calculate a result. Webserver send "xx.php" back to client with calculated result.

Q2-3 With reference to database use within a LAMP setup, explain the terms "Prepared Statement" and"Bound Parameters" and indicate their advantages over executes statements in a PHP web application.

A prepared statement is a feature used to execute the same (or similar) SQL statements repeatedly with high efficiency. Prepared statements basically work like this: 1. Prepare: An SQL statement template is created and sent to the database. Certain values are left unspecified, called parameters (labeled "?"). Example: INSERT INTO MyGuests VALUES(?, ?, ?) 2. The database parses, compiles, and performs query optimization on the SQL statement template, and stores the result without executing it 3. Execute: At a later time, the application binds the values to the parameters, and the database executes the statement. The application may execute the statement as many times as it wants with different values Two main advantages: 1.Prepared statements reduces parsing time as the preparation on the query is done only once (although the statement is executed multiple times) 2.Bound parameters minimize bandwidth to the server as you need send only the parameters each time, and not the whole query 3.Prepared statements are against SQL injections, because parameter values, which are transmitted later using a different protocol. SQL injection cannot occur.

Q4-1 Describe the features of a Single-page Application (SPA) implementing an MVC design pattern

A single-page application is a web application or web site that fits on a single web page with the goal of providing a more fluid user experience akin to a desktop application. The main aim of the SPA is to make the web application work seamlessly. All the necessary code is retrieved with a single page load and changing only elements on the page, depending on the actions taken by the user. The page does not automatically reload during user interaction with the application, nor does control transfer to another page. MVC is a software architecture pattern, and it separates the visual representation of information from the user's interaction. we are talking about the MVC pattern on the client side, Describe the features of Single-page-Application(MVC): • Almost no page reloads, UI built by JavaScript • Most of the logic is executed on the client-side • Richer Interaction between UI Components, which makes the web application work seamlessly • No URL Change other than # • Back Button works as expected • Bookmark-able Links • Ability to go Offline After first time load HTML at client side, there will be no more loading of the views. Most interaction is client request JSON data, and serve response JSON data back. Most logic is excuted on the client-side..

Q3-1 Sample Question: Outline, using concrete examples, the advantages and disadvantages of using AJAX for dynamic web page generation.

Advantages 1.Better interactivity This is pretty much the most striking benefit behind why several developers and webmasters are switching to AJAX for their websites. AJAX allows easier and quicker interaction between user and website as pages are not reloaded for content to be displayed. 2.Easier navigation AJAX applications on websites can be built to allow easier navigation to users in comparison to using the traditional back and forward button on a browser. 3.Compact With AJAX, several multi purpose applications and features can be handled using a single web page, avoiding the need for clutter with several web pages. For our use of AJAX on goedkope-zomervakantie.com, it took just a few lines of code! Disadvantages 1.The back and refresh button are rendered useless With AJAX, as all functions are loaded on a dynamic page without the page being reloaded or more importantly a URL being changed, clicking the back or refresh button would take you to an entirely different web page or to the beginning of what your dynamic web page was processing. This is the main drawback behind AJAX but fortunately with good programming skills this issue can be fixed. 2.It is built on javascript While javascript is secure and has been heavily used by websites for a long period of time, a percentage of website surfers prefer to turn javascript functionality off on their browser rendering the AJAX application useless, a work around to this con is present as well, where the developer will need to code a parallel non-javascript version of the dynamic web page to cater to these users.

Q3-1 Sample Question: Outline, using suitable coding examples, the advantages and disadvantages of using a JavaScript framework, such as jQuery. Demonstrate how you could use jQuery to replace an image on a web page, by fading out the current image and fading in a replacement image, when the mouse hovers over the image.

Advantages of using jquery: Advantages 1.Ease of use it is a lot more easy to use compared to standard javascript and other javascript libraries. It also requires much less lines of code to achieve the same feature in comparison. // hide the element with id is "test"; Jquery: $("#test").hide(); Js: document.getElementById(text).style.visibility='hidden'; 2.JQuery seperates the script from html. <form id="myform" onsubmit=return validate();" > $("#myform").submit(function() { }); Disadvantages 1.Functionality maybe limited, using raw javascript maybe inevitable in some cases. 2.JQuery javascript file required,which need to load at the client side. <script src="jquery-1.12.0.min.js"></script> Fadeout current img and fade in a replacement img, when the mouse hover: $("#myimg").hover( function() { $(this).fadeOut(3000) }, function(){ $(this).attr("src", "anotherpic.jpg"); $(this).fadeIn(1000); });

Q4-1Using appropriate code examples, show how it is possible to implement MVC-based LAMP applications using PHP as the development language.

Code example (LAMP): <?php class Model { public $string; public function __construct(){ $this->string = "MVC + PHP = Awesome!"; } } ?> <?php class View { private $model; private $controller; public function __construct($controller,$model) { $this->controller = $controller; $this->model = $model; } public function output(){ return "<p>" . $this->model->string . "</p>"; } } ?> <?php class Controller { private $model; public function __construct($model) { $this->model = $model; } } ?> <?php $model = new Model(); $controller = new Controller($model); $view = new View($controller, $model); echo $view->output(); ?>

Q2-1 Describe, using appropriate PHP code examples, how to use the PHP super global $_COOKIE, together with the setcookie()function to create, retrieve, delete and update a cookie within a PHP application

Create setcookie(name, value, expire, path, domain, secure, httponly); <?php $cookie_name = "user"; $cookie_value = "John Doe"; setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day ?> Retrieve: user global $_COOKIE <?php if(isset($_COOKIE["user"])) { echo " Cookie Value is: " . $_COOKIE["user"]; } ?> Modify a Cookie Value To modify a cookie, just set (again) the cookie using the setcookie() function: <?php $cookie_name = "user"; $cookie_value = "Alex Porter"; setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); ?> Delete a Cookie To delete a cookie, use the setcookie() function with an expiration date in the past: <?php setcookie("user", "", time() - 3600);// set the expiration date to one hour ago ?>

Q2-1 Using suitable code examples, demonstrate how session management (create, modify and destroy) may be achieved using the PHP super global $_SESSION, together with the PHP session management functions.

Create session: A session is started with the session_start() function. Session variables are set with the PHP global variable: $_SESSION. <?php session_start(); $_SESSION["favcolor"] = "green"; $_SESSION["favanimal"] = "cat"; ?> Retrive all sesission: <?php session_start(); print_r($_SESSION); ?> Modify a PHP Session To change a session variable, just overwrite it: <?php session_start(); $_SESSION["favcolor"] = "yellow"; ?> Destroy a PHP Session // destroy the session session_destroy();

Q2-3 Sample Question: Write a PHP script to create a table suitable for hosting the submitted form data from part (ii) above. Extend your script in part (ii) above to save the validated, submitted data to a MySQL database, having first checked that the username is not already contained in the database. If the user exists, re-present the form with an appropriate CSS-styled error message.

Create table <?php $conn = new mysqli("localhost", "root", "123123", "mydb"); $sql = "CREATE TABLE users ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, username VARCHAR(30) , password VARCHAR(30) )"; if ($conn->query($sql) === TRUE) { echo "Table users created successfully"; } else { echo "Error creating table: " . $conn->error; } $conn->close(); ?> check username from database <?php if (isset($_POST["submit"])){ $conn = newmysqli("localhost", "root", "password", "mydb"); $name =htmlspecialchars( $_POST["username"]); $stmt = $conn->prepare("SELECT * FROM users WHERE username=?"); $stmt->bind_param("s", $name); $stmt->execute(); $result = $stmt->get_result(); if($result->num_rows ==0){ // username not taken $stmt2 = $conn->prepare("INSERT INTO users (username, password) VALUES (?, ?)"); $username = $_POST["username"]; $password = $_POST["password1"]; $stmt2->bind_param("ss", $username, $password); $stmt2->execute(); $stmt2->close(); echo "Congratulations ".$_POST["username"]."; you are now registered"; }else{ echo "<p style='color:red;'>Sorry, username already taken.</p>"; } $stmt->close(); $onn->close(); } ?>

Q4-1 Describe the Model View Controller (MVC) design pattern in relation to web development.

Describe MVC: The pattern's title is a collation of its three core parts: Model, View, and Controller. The Model is the name given to the permanent storage of the data used in the overall design. It must allow access for the data to be viewed, or collected and written to, and is the bridge between the View component and the Controller component in the overall pattern. The View is where data, requested from the Model, is viewed and its final output is determined. Traditionally in web apps built using MVC, the View is the part of the system where the HTML is generated and displayed. The View also ignites reactions from the user, who then goes on to interact with the Controller. The basic example of this is a button generated by a View, which a user clicks and triggers an action in the Controller. The final component of the triad is the Controller. Its job is to handle data that the user inputs or submits, and update the Model accordingly. The Controller's life blood is the user; without user interactions, the Controller has no purpose. It is the only part of the pattern the user should be interacting with.

Q4-1 Describe the Model View Controller (MVVM) design pattern in relation to web development.

Describe MVVM: Model-view-viewmodel -Controler is a software architectural pattern. Model Model refers either to a domain model, which represents real state content (an object-oriented approach), or to the data access layer, which represents content (a data-centric approach) View As in the MVC and MVP patterns, the view is the user interface (UI) View model The view model is an abstraction of the view exposing public properties and commands. Instead of the controller of the MVC pattern, MVVM has a binder. In the view model, the binder mediates communication between the view and the data binder.The view model has been described as a state of the data in the model. View modle: The view model of MVVM is a value converter; meaning the view model is responsible for exposing (converting) the data objects from the model in such a way objects are easily managed and consumed. In this respect, the view model is more model than view, and handles most if not all of the view's display logic. The view model may implement a mediator pattern, organizing access to the back-end logic around the set of use cases supported by the view.

Q3-2 Describe briefly, using relevant code fragments, how to use PHP to issue a SOAP request to a web service.

How to use php to issue a SOAP request $data = array( 'a' => 'b', 'c' => 'd'); $client = new SoapClient('http://example.com'); $response = $client->GetWeather($data); print_r($response);

Q1-3 Write a suite of javascript functions, which are automatically executed after a page loads, that informs the user (using an in-page dialog) that site-usage requires acknowledgement of cookie usage. The dialog should contain a message and single button which is used to receive acknowledgement from the user that the message has been read. The dialog should continue to be presented until the acknowledgement button has been pressed by the user. The dialog should be a CSS-styled DIV element which is located at the top of the window and, while visible, overlaps page content. You may assume thatwriteCookie() and readCookie() functions exist; you do not have to develop the internal content of these functions.

Js: test =function(){ if(readCookie("notice")=="agree"){ document.getElementById('note').style.visibility = 'hidden'; }else{ document.getElementById('note').style.visibility = 'show'; } } test(); agree = function(){ writeCookie("notice","agree"); document.getElementById('note').style.visibility = 'hidden'; } Html: <div id='note'> <p> Please notice that site-usage requires acknowledgement of cookie usage</p> <button type='button' onclick='agree()' >OK!</button> </div> Css: #note { color: red; font-size: 10px; border: 2px solid black; position:absolute; width:100%; top: 0px; }

Q4-1 Describe, using a suitable diagram, the LAMP web development platform. How does LAMP differ from the MEAN platform?

LAMP is a model of web service solution stack, it named of its original 4 components: Linux OS, Apache THTTP Server, Mysql relational database, PHP programming language. As a solution stack, LAMP is suitable for building dynamic web sites and web applications LAMP Languages: Perl/PHP/Python: Commonly used programming languages. Database: MySQL (RDBMS): Conventional database system Web Server: Apache: Commonly used. MEAN Languages: AngularJS: Extension of Javascript Database:MongoDB(NoSQL database): A cross-platform document-oriented database system. JSON-style documents with dynamic schemas provide simplicity and power, making the integration of data into Web Server: ExpressJS: is a Node.js Web application framework. It creates an MVC-like application on the server side. It also allows users to create routes and templates.

Q3-3 Sample Question: Write single-page PHP application that dynamically checks and retrieves XML data every 30s from a web service located at http://localhost:8080/ and displays the CSS-styled data in a DIV element. The XML data contains three data items: a car park name, the number of cars entering that car park in the last 5 minutes, and the number of cars leaving in the last 5 minutes. (XML)

Php: <!DOCTYPE html> <html> <head> <script type='text/javascript' src='jQuery.js'></script> <script type='text/javascript' > getdata = function(){ $.ajax({ type: "GET", url: "xx.xml", dataType: "xml", success: function(xml){ $(xml).find('entry').each(function(){ $(parkname).html= $(this).find('parkname').text(); $(numberEnter).html= $(this).find('numberEnter').text(); $(numberLeave).html= $(this).find('numberLeave').text(); }); }, complete: function() { setTimeout(getdata, 30000); } }); } } </script> <style> div { background:black; color:white; font-family:sans-serif; } </style> </head> <body> name:<div id ="parkname"></div>; number of entering:<div id ="numberEnter"></div>; number of leaving:<div id ="numberLeave"></div>; </body> </html> Xml: <?xml version="1.0" encoding="UTF-8" ?> <entry> <parkname>carpark1</parkname> <numberEnter>10</numberEnter> <numberLeave>8</numberLeave> </entry>

Q4-1Giving reasons for your answer, outline whether you believe a LAMP or a MEAN platform would be better suited to SPA development.

Reasons: I believe MEAN platform would be better suited to SPA development, Single-Page Applications (SPAs) are Web apps that load a single HTML page and dynamically update that page as the user interacts with the app. SPA is about dealing with a lot of frontend development . In SPA, all interaction with the server happens through AJAX calls. These AJAX calls return data usually in JSON format. The app uses the JSON data to update the page dynamically, without reloading the page. SPA communicates with server only with JSON REST API. MEAN represents a major shift in architecture and mental models — from relational databases to NoSQL (transfor json-like data) and from server-side Model-View-Controller to client-side. which makes the SPA can be easily developed a in MEAN stack. MEAN stands for: MongoDB, the database Express, the server-side web framework AngularJS, the frontend framework Node.js, the server Node.js has the ability to run JavaScript on the server and use the power of the Express framework to build an HTTP proxy and routes. MongoDB is an open source database document oriented for high performance and scalability and is also known as NoSQL database. Thus, we can consider MEAN as a great way for the development of SPAs. The opinions are certainly much divided when it comes to SPA, but SPA is about dealing with a lot of frontend development.

Q3-2 Converting between structured XML and JSON may sometimes be problematic, in particular, when it is necessary to convert to reversible JSON. Show how XML can be converted to a reversible JSON structure, clearly outlining when it is, and is not, possible, using specific code examples. Please provide both JSON and XML code in your answer.

Some time we need to convert an existing XMl document to JSON structure. In the ideal world, the resulting JSON can be converted back to it's original XML. For example : <entries> <entry> <date>20040202</date> <todo>buy apple</todo> </entry> </entries> { "entries": [ { "date": "20040202", "todo": "buy apple" } ] } not reversible <entries> <entry id ="1" order ="2"> <date>20040202</date> <todo>buy apple</todo> </entry> </entries> Json: { "entry": [ { "id": "1", "order":"2", "date": "20040202", "todo": "buy apple" } ] } reversible: 1. An empty element <e/> "e": null 2. An element with pure text content riversible <e>text</e> "e": "text" 3. An empty element with attributes <e name="value" /> "e":{"@name": "value"} 4. An element with pure text content and attributes <e name="value">text</e> "e": { "@name": "value", "#text": "text" }

Q3-2 Give an example of a JSON and XML representation of a TV show broadcasting schedule.

TV show broadcasting schedule: { "tvshows": [ { "date": "20040202", "name": "Modern Family", "Channel": "HBO" }, { "date": "20040201", "name": "Good Day", "Channel": "Fox" }, { "date": "20040209", "name": "Community", "Channel": "SKY" } ] } <?xml version="1.0" encoding="UTF-8" ?> <tvshows> <show> <date>20040202</date> <name>Modern Family</name> <Channel>HBO</Channel> </show> <show> <date>20040201</date> <name>Good Day</name> <Channel>Fox</Channel> </show> <show> <date>20040209</date> <name>Community</name> <Channel>SKY</Channel> </show> </tvshows>

Q1-2 Write a Javascript (JS) function changeAll() that restyles all text in a specified DIV element containing some text when a button is clicked by the user. The restyling should capitalise all words, for example, "There are seven words in this sentence!" would be changed to "THERE ARE SEVEN WORDS IN THIS SENTENCE!". Give the HTML code for the button that is used to invoke changeAll().

changeAll = function() { var str1 = document.getElementById('text1').innerHTML.trim(); var result = str1.toUpperCase(); document.getElementById('text1').innerHTML = result; }

Q1-1 Demonstrate, using suitable command-line tools, how to make a HTTP request to retrieve a file called notice.html from a web server located http://localhost/.

client sent http post request to webserver: curl -X POST --data "name=hello" http://localhost/notice.html

Q3-2 Describe briefly, using relevant code fragments, how to use jQuery to consume a RESTful web service.

how to use jQuery to consume a RESTful web service. {"id":1,"content":"Hello, World!"} <p class="greeting-id">The ID is </p> <p class="greeting-content">The content is </p> JQuery: $.ajax({ Type:"GET", url: "http://rest-service.guides.spring.io/greeting" , dataType: 'json', success: function (response) { var json_obj = $.parseJSON(response); $('.greeting-id').append(json_obj[0].id); $('.greeting-content').append(json_obj[0].content); } });

Q2-1 What is session management, and why is it necessary for web application development

what: session management is the process of keeping track of a user's activity across sessions of interaction with the computer system. why HTTP is stateless. Session management is the technique used to make the stateless HTTP protocol support session state. For example, once a user has been authenticated to the web server, the user will be remembered by the session.

Q3-3 : Write single-page PHP application that dynamically checks and retrieves JSON data every 30s from a web service located at http://localhost:8080/ and displays the CSS-styled data in a DIV element. The JSON data contains three data items: a car park name, the number of cars entering that car park in the last 5 minutes, and the number of cars leaving in the last 5 minutes.(JSON)

{ "parkname":"Aldi", "numberEnter":"10", "numberLeave":"8" } <?php <!DOCTYPE html> <html> <head> <style> div { background:black; color:white; font-family:sans-serif; } </style> <script type='text/javascript' src = 'jquery.js'> <script type='text/javascript' > $.ajax({ type: "GET", url: "xx.json", dataType: "json", success: function(response){ $json_obj = jQuery.parseJSON( response ); $(parkname).html = json_obj[0].parkname; $(numberEnter).html= json_obj[0].numberEnter; $(numberLeave).html= json_obj[0].numberLeave; }); }, complete: function() { setTimeout(getdata, 30000); } }); } } </script> <link rel='stylesheet' type='text/css' href='ajaxTest.css'> </head> <body> name:<div id ="parkname"></div> number of entering:<div id ="numberEnter"></div> number of leaving:<div id ="numberLeave"></div> </body> </html> ?>


संबंधित स्टडी सेट्स

PHARM -The Cardiovascular System Test

View Set

PRFS 4633: Decision-Making in Organizations

View Set

Protect Yourself and Your Computer

View Set

Organizational Behavior Chapter 1 Practice Questions

View Set