PHP Questions on Files

1) How to include remote file in PHP?
To allow inclusion of remote files, the directive allow_url_include must be set to On in php.ini

But it is bad, in a security-oriented point of view ; and, so, it is generally disabled (I’ve never seen it enabled, actually)

It is not the same as allow_url_fopen, which deals with opening (and not including) remote files — and this one is generally enabled, because it makes fetching of data through HTTP much easier (easier than using curl)

$url = “”;
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$contents = curl_exec($ch);

As long as allow_url_fopen is enabled in php.ini, you can use HTTP and FTP URLs with most of the functions that take a filename as a parameter. In addition, URLs can be used with the include, include_once, require and require_once statements (since PHP 5.2.0, allow_url_include must be enabled for these)

2) What are the different ways of reading a file?

a) file — Reads entire file into an array
$lines = file(''); // $lines is an array

b) file_get_contents – Reads entire file into a string
$file = file_get_contents('./people.txt', true); // $file is a string

c) fread – Binary-safe file read
fread() reads up to length bytes from the file pointer referenced by handle. It stops if it encounters EOF earlier.

$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename)); // $contents is a string

d) fgets – Gets line from file pointer
$handle = @fopen("/tmp/inputfile.txt", "r");
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
echo $buffer;
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";

e) fscanf
fscanf() is similar to sscanf(), but it takes its input from a file associated with handle and interprets the input according to the specified format, which is described in the documentation for sprintf(). Each call to fscanf() reads one line from the file

$handle = fopen("users.txt", "r");
while ($userinfo = fscanf($handle, "%s\t%s\t%s\n")) {
list ($name, $profession, $countrycode) = $userinfo;
//... do something with the values

f) fgetc — Gets character from file pointer
$fp = fopen('somefile.txt', 'r');
if (!$fp) {
echo 'Could not open file somefile.txt';
while (false !== ($char = fgetc($fp))) {
echo "$char\n";

2) How to delete a file ?

What are different ways to change url in javascript?

1) window.location.href = “”;
// document.URL is alternative to window.location.href

2) window.location.assign(“”);
// this will not alter the browser’s history.

3) window.location.replace(“”);
// this will alter the browser’s history

4) window.location.reload(true);
// force to get page from server

5) window.location.reload(false);
// get page from cache if available


INNER JOIN: Returns all rows when there is at least one match in BOTH tables
LEFT JOIN: Return all rows from the left table, and the matched rows from the right table
(Tip: Read it as : All rows from Left + The Join)
RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table
FULL JOIN: Return all rows when there is a match in ONE of the tables

What is your greatest weakness and strength?

1) Effective Delegation : Sometimes end up taking responsibility to complete task on myself which I could have easily delegated.

2) Learning to say NO: Often times we end up saying “Maybe I will try it out”. When it’s clear that saying NO would be the ideal.

3) Shyness :

4) Keeping up with technology

1) Sincerity

2) Creative

3) Good Rapport with Team ,

4) Good observation skills (personal touch to dealings with team members)

5) Eagerness to learn new technologies

Javascript Set1 of 10 Interview Questions

1) What are the basic types used in JavaScript?

Primitive: String, Number, Boolean, Null, Undefined .

undefined means a variable has been declared but has not yet been assigned a value. On the other hand, null is an assignment value. It can be assigned to a variable as a representation of no value. Also, undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.

Complex: Object (Arrays are Objects, Functions are Objects)

2) What are the ways to create object in JS?

1) // object constructor

var mango =  new Object ();
mango.color = "yellow";
mango.shape= "round";
mango.sweetness = 8;

mango.howSweetAmI = function () {
console.log("Hmm Hmm Good");

2) // object literal

      // This is an object with 4 items, again using object literal
var mango = {
color: "yellow",
shape: "round",
sweetness: 8,

howSweetAmI: function () {
console.log("Hmm Hmm Good");

3) // constructor pattern

function Fruit (theColor, theSweetness, theFruitName, theNativeToLand) {

    this.color = theColor;
    this.sweetness = theSweetness;
    this.fruitName = theFruitName;
    this.nativeToLand = theNativeToLand;

    this.showName = function () {
        console.log("This is a " + this.fruitName);

    this.nativeTo = function () {
    this.nativeToLand.forEach(function (eachCountry)  {
       console.log("Grown in:" + eachCountry);


var mangoFruit = new Fruit ("Yellow", 8, "Mango", ["South America", "Central America", "West Africa"]);

4) // using prototype pattern

function Fruit () {


Fruit.prototype.color = "Yellow";
Fruit.prototype.sweetness = 7;
Fruit.prototype.fruitName = "Generic Fruit";
Fruit.prototype.nativeToLand = "USA";

Fruit.prototype.showName = function () {
console.log("This is a " + this.fruitName);

Fruit.prototype.nativeTo = function () {
            console.log("Grown in:" + this.nativeToLand);

var mangoFruit = new Fruit ();

3) Creating Arrays in JS

var a = new Array();
a[0] = 1.2;
a[1] = “Javascript”;
a[2] = true;
a[3] = { x:1, y:3};

var a = new Array(1.2,”Javascript”, true)

4) What is the difference between using call and apply to invoke a function?

var func = function(){

The main difference is that apply lets you invoke the function with arguments as an array; call requires the parameters be listed explicitly.
[A for apply, A for array]
[C for call, C for column of args]

theFunction.apply(valueForThis, arrayOfArgs), arg1, arg2, …)

5) What do you understand by this keyword in JavaScript?
Ans: In JavaScript the this is a context-pointer and not an object pointer. It gives you the top-most context that is placed on the stack. The following gives two different results (in the browser, where by-default the window object is the 0-level context):

var obj = { outerWidth : 20 };

function say() {

say();//will alert window.outerWidth
say.apply(obj);//will alert obj.outerWidth

6) What would be the output of the following statements?

var object1 = { same: ‘same’ };
var object2 = { same: ‘same’ };
console.log(object1 === object2);
Ans: // Logs false, JavaScript does not care that they are identical and of the same object type.
When comparing complex objects, they are equal only when they reference the same object (i.e., have the same address). Two variables containing identical objects are not equal to each other since they do not actually point at the same object.

What would be the output of the following statements?


var object1 = { same: ‘same’ };
var object2 = object1;
console.log(object1 === object2);

7) Consider the following statements and tell what would be the output of the logs statements?

var price1 = 10;
var price2 = 10;
var price3 = new Number(’10’); // A complex numeric object because new was used.
console.log(price1 === price2);
console.log(price1 === price3);

console.log(price1 === price2); // Logs true.
console.log(price1 === price3); /* Logs false because price3
contains a complex number object and price 1
is a primitive value. */

8 ) Javascript Timing Events
It’s very easy to time events in JavaScript. The two key methods that are used are:

setInterval() – executes a function, over and over again, at specified time intervals
setTimeout() – executes a function, once, after waiting a specified number of milliseconds

9) How do you add a css class to an existing html element?
document.getElementById(“p1″).className += ” big”;

This will add the class big to the list of existing classes of element p1. If the “+=” was replaced by “=” then the class “big” will REPLACE all the existing classes of p1.

10) If you forget to declare a variable using “var” keyword inside a function what happens?
That variable will be treated as a global variable.

Why should I use node.js?

  • real-time websites with push capability
  • unifies the language and data format (JSON) across the stack
  • web applications with real-time, two-way connections, where both the client and server can initiate communication, allowing them to exchange data freely
  • non-blocking, event-driven I/O to remain lightweight and efficient in the face of data-intensive real-time applications that run across distributed devices.
  • You definitely don’t want to use Node.js for CPU-intensive operations
  • Node.js operates on a single-thread, using non-blocking I/O calls, allowing it to support support tens of thousands of concurrent connections
  • Although Node.js really shines with real-time applications, it’s quite a natural fit for exposing the data from object DBs (e.g. MongoDB). JSON stored data allow Node.js to function without the impedance mismatch and data conversion
  • Typical examples include: the logging or writing of user-tracking data, processed in batches and not used until a later time; as well as operations that don’t need to be reflected instantly (like updating a ‘Likes’ count on Facebook) where eventual consistency (so often used in NoSQL world) is acceptable.

htmlentities, htmlspecialchars, html_entity_decode

htmlspecialchars : converts only some characters to their html equivalents. This is preferred over htmlentities.

htmlentities: converts all characters to their html equivalents. This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities.
htmlentities is only necessary if your pages use encodings such as ASCII or LATIN-1 instead of UTF-8.

html_entity_decode: Convert all HTML entities to their applicable characters. html_entity_decode() is the opposite of htmlentities()

Input Validation

1) Use in built functions
filter_input, filter_var, filter_input_array

$search_html = filter_input(INPUT_GET, ‘search’, FILTER_SANITIZE_SPECIAL_CHARS);

$args = array(
‘component’ => array(‘filter’ => FILTER_VALIDATE_INT,
‘options’ => array(‘min_range’ => 1, ‘max_range’ => 10)
‘doesnotexist’ => FILTER_VALIDATE_INT,
‘testscalar’ => array(
‘testarray’ => array(

$myinputs = filter_input_array(INPUT_POST, $args);

2) htmlspecialchars()
The htmlspecialchars() function converts special characters to HTML entities. This means that it will replace HTML characters like < and > with < and >. This prevents attackers from exploiting the code by injecting HTML or Javascript code (Cross-site Scripting attacks) in forms.

3) stripslashes($data)

4) Use PHP Data Objects (PDO) for binding query parameters and prepared statements to avoid sql injection: PDO provides a data-access abstraction layer, which means that, regardless of which database you’re using, you use the same functions to issue queries and fetch data.

Cross Site Scripting (XSS), CSRF and SQL Injection

SQL Injection:
It is the type of attack that takes advantage of improper coding of your web applications that allows hacker to inject SQL commands into say a login form to allow them to gain access to the data held within your database.

In essence, SQL Injection arises because the fields available for user input allow SQL statements to pass through and query the database directly.


The query sent to MySQL will be:

SELECT * FROM users WHERE user='aidan' AND password='' OR ''=''

Cross Site Scripting:

In general, cross-site scripting refers to that hacking technique that leverages vulnerabilities in the code of a web application to allow an attacker to send malicious content from an end-user and collect some type of data from the victim. Always validate user input to avoid cross site scripting.

Cross Site Scripting allows an attacker to embed malicious JavaScript, VBScript, ActiveX, HTML, or Flash into a vulnerable dynamic page to fool the user, executing the script on his machine in order to gather data. The use of XSS might compromise private information, manipulate or steal cookies, create requests that can be mistaken for those of a valid user, or execute malicious code on the end-user systems. The data is usually formatted as a hyperlink containing malicious content and which is distributed over any possible means on the internet.


BODY BACK GROUND="javascript:alert('XSS')
IMG S R C="javascript:alert('XSS');

Simplified View:
XSS is when the user trusts the server too much, CSRF is when the server trusts the user too much

Take these two URL examples that an attacker might send to a victim, the XSS example would abuse a vulnerability on the page and inject javascript into the page and cause the user’s browser to execute the malicious code, the CSRF example causes the server to except malicious input from the user and process it as if the user intended to submit password change:

XSS:’< script >alert(1)

In simple terms XSS is when you can execute arbitrary Javascript in the victim’s browser typically because input wasn’t sanitised correctly. From there you can do whatever Javascript can, send their cookies to a malicious person, rewrite the DOM to make it seem like the page has been vandalised, redirect them to a malicious page / phishing website, etc.
CSRF is when you trick a user into performing actions with the authority the browser believes they have. Let’s say to change a password you need to submit a form along with being logged in under your account. The server would check you’re logged in via a session token. If I can get this user (‘the victim’) to click on a link which tells the browser to submit the form, the browser will submit it, along with the victim’s logged in session ID (which is always sent when visiting the site). Because as far as the website is concerned the user is logged it and submitting the form it will quite happily complete the action and change the password. An attacker could now log in with the (known) password themselves.