Php Interview Question?

Interview Questions

PHP

1)self vs $this

Use $this to refer to the current object.
Use self to refer to the current class.
In other words, use $this->member for non-static members, use self::$member for static members

PHP Code Optimization Techniques

  1. If a method can be static, declare it static. Speed improvement is by a factor of 4.
  2. echois faster than print.
  3. Use echo’s multiple parameters instead of string concatenation.
  4. Set the maxvalue for your for-loops before and not in the loop.
  5. Unset your variables to free memory, especially large arrays.
  6. Avoid magic like __get, __set, __autoload
  7. require_once()is expensive
  8. Use full paths in includes and requires, less time spent on resolving the OS paths.
  9. If you need to find out the time when the script started executing,INSERT:CONTENT:END SERVER[‘REQUEST_TIME’] is preferred to time()
  10. See if you can use strncasecmp, strpbrk and stripos instead of regex
  11. str_replaceis faster than preg_replace, but strtr is faster than str_replace by a factor of 4
  12. If the function, such as string replacement function, accepts both arrays and single characters as arguments, and if your argument list is not too long, consider writing a few redundant replacement statements, passing one character at a time, instead of one line of code that accepts arrays as search and replace arguments.
  13. It’s better to use select statements than multi if, else if, statements.
  14. Error suppression with @ is very slow.
  15. Turn on apache’s mod_deflate
  16. Close your database connections when you’re done with them
  17. $row[‘id’]is 7 times faster than $row[id]
  18. Error messages are expensive
  19. Do not use functions inside of for loop, such asfor ($x=0; $x < count($array); $x) The count() function gets called each time.
  20. Incrementing a local variable in a method is the fastest. Nearly the same as calling a local variable in a function.
  21. Incrementing a global variable is 2 times slow than a local var.
  22. Incrementing an object property (eg.$this->prop++) is 3 times slower than a local variable.
  23. Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.
  24. Just declaring a global variable without using it in a function also slows things down (by about the same amount as incrementing a local var). PHP probably does a check to see if the global exists.
  25. Method invocation appears to be independent of the number of methods defined in the class because I added 10 more methods to the test class (before and after the test method) with no change in performance.
  26. Methods in derived classes run faster than ones defined in the base class.
  27. A function call with one parameter and an empty function body takes about the same time as doing 7-8$localvar++ operations. A similar method call is of course about 15$localvar++ operations.
  28. Surrounding your string by ‘ instead of “will make things interpret a little faster since php looks for variables inside ”…” but not inside ‘…’. Of course you can only do this when you don’t need to have variables in the string.
  29. When echoing strings it’s faster to separate them by comma instead of dot. Note: This only works with echo, which is a function that can take several strings as arguments.
  30. A PHP script will be served at least 2-10 times slower than a static HTML page by Apache. Try to use more static HTML pages and fewer scripts.
  31. Your PHP scripts are recompiled every time unless the scripts are cached. Install a PHP caching product to typically increase performance by 25-100% by removing compile times.
  32. Cache as much as possible. Use memcached – memcached is a high-performance memory object caching system intended to speed up dynamic web applications by alleviating database load. OP code caches are useful so that your script does not have to be compiled on every request
  33. When working with strings and you need to check that the string is either of a certain length you’d understandably would want to use the strlen() function. This function is pretty quick since it’s operation does not perform any calculation but merely return the already known length of a string available in the zval structure (internal C struct used to store variables in PHP). However because strlen() is a function it is still somewhat slow because the function call requires several operations such as lowercase & hashtable lookup followed by the execution of said function. In some instance you can improve the speed of your code by using an isset() trick. Example:
    if (strlen($foo) < 5) { echo “Foo is too short”; } vs.
    if (!isset($foo{5})) { echo “Foo is too short”; }
    Calling isset() happens to be faster then strlen() because unlike strlen(), isset() is a language construct and not a function meaning that it’s execution does not require function lookups and lowercase. This means you have virtually no overhead on top of the actual code that determines the string’s length.
  34. When incrementing or decrementing the value of the variable$i++ happens to be a tad slower then ++$i. This is something PHP specific and does not apply to other languages, so don’t go modifying your C or Java code thinking it’ll suddenly become faster, it won’t.++$i happens to be faster in PHP because instead of 4 opcodes used for $i++ you only need 3. Post incrementation actually causes in the creation of a temporary var that is then incremented. While pre-incrementation increases the original value directly. This is one of the optimization that opcode optimized like Zend’s PHP optimizer. It is a still a good idea to keep in mind since not all opcode optimizers perform this optimization and there are plenty of ISPs and servers running without an opcode optimizer.
  35. Not everything has to be OOP, often it is too much overhead, each method and object call consumes a lot of memory.
  36. Do not implement every data structure as a class, arrays are useful, too
  37. Don’t split methods too much, think, which code you will really re-use
  38. You can always split the code of a method later, when needed
  39. Make use of the countless predefined functions
  40. If you have very time consuming functions in your code, consider writing them as C extensions
  41. Profile your code. A profiler shows you, which parts of your code consumes how many time. The Xdebug debugger already contains a profiler. Profiling shows you the bottlenecks in overview
  42. mod_gzip which is available as an Apache module compresses your data on the fly and can reduce the data to transfer up to 80%

COOKIES vs SESSIONS

COOKIES:

  • Stored on the client computer and are thus decentralized.
  • Can be set to a long lifespan and/or set to expire after a period of time from seconds to years.
  • They work well with large sites that may use several webservers.
  • Won’t do you any good if the client has set their browser to disable cookies.
  • Limitations on size and number: a browser can keep only the last 20 cookies sent from a particular domain, and the values that a cookie can hold are limited to 4 KB in size.
  • Can be edited beyond your control since they reside on the client system.
  • Information set in the cookie is not available until the page is reloaded.

SESSIONS:

  • Server-size cookie can store very large amounts of data while regular cookies are limited in size.
  • Since the client-side cookie generated by a session only contains the id reference (a random string of 32 hexadecimal digits, such as ‘fca17f071bbg9bf7f85ca281653499a4′ called a ‘session id’) you save on bandwidth.
  • Much more secure than regular cookies since the data is stored on the server and cannot be edited by the user.
  • Only last until the user closes their browser.
  • Won’t work if client has cookies disabled in their browser unless some extra measures are taken (example below).
  • Can be easily customized to store the information created in the session to a database.
  • Information is available in your code as soon as it is set.

How to use Sessions when Cookies are Disabled

If cookies are disabled you must use a different method to pass the session id. A popular method is to pass it in the querystring and then process it in the subsequent page using $_GET, like so:

echo “http://www.yoursite.com/yourphppage.php?PHPSESSID=&#8221;.session_id();

Then use the following in the loading page to retrieve the session id:

echo $_GET[‘PHPSESSID’];

Regular Expression for Date Validation (YYYY-MM-DD)

<?php
// Date Validation YYYY-MM-DD
$date = ‘2012-03/13’;
if(preg_match(“/^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}$/”, $date) === 0) {
echo ‘Date must be in : YYYY-MM-DD’;
} else {
echo “Date Correct”;
}
?>

Regular Expression for Password Validation

Password Criteria:

  1. Password must be at least 8 characters.
  2. Must contain at least one lower case letter
  3. One upper case letter
  4. One Digit
  5. One Special Character.

<?php
$password = “Password”;
// Password Validation
if(preg_match(“/^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[!@#$%^&*])(?=.*[A-Z]).*$/”, $password) === 0) {
echo ‘<p>1. Password must be at least 8 characters. <br>2. Must contain at least one lower case letter <br>3. One upper case letter <br>4. One Digit <br>5. One Special Character.</p>’;
} else {
echo “Password Strong”;
}
?>

What are PHP Regular Expression Functions?

  1. preg_match() —> The preg_match() function searches string for pattern, returning true if pattern exists, and false otherwise.
  2. preg_match_all() —> The preg_match_all() function matches all occurrences of pattern in string.
  3. preg_replace() —> The preg_replace() function operates just like ereg_replace(), except that regular expressions can be used in the pattern and replacement input parameters.
  4. preg_split() —> The preg_split() function operates exactly like split(), except that regular expressions are accepted as input parameters for pattern.
  5. preg_grep() —> The preg_grep() function searches all elements of input_array, returning all elements matching the regexp pattern.
  6. preg_ quote() —> Quote regular expression characters

Regular Expression Characterization?

  1. a dollar sign ($) is used to match strings that end with the given pattern.
  2. a caret (^) character at the beginning of a regular expression indicates that it must match the beginning of the string.
  3. The dot (.) metacharacter matches any single character except newline (\).
  4. The vertical pipe (|) metacharacter is used for alternatives in a regular expression.

The metacharacters +, * and ? affect the number of times a pattern should be matched.

  1. ‘+’ means Match one or more of the preceding expression
  2. ‘*’ means Match zero or more of the preceding expression
  3. ‘?’ means Match zero or one of the preceding expression

Curly braces {} can be used differently

  1. With a single integer, {n} means match exactly n occurrences of the preceding expression
  2. With one integer and a comma, {n,} means match n or more occurrences of the preceding expression
  3. With two comma-separated integers {n,m} means match the previous character if it occurs at least n times, but no more than m times

Regular Express with Respective Matches

  1. foo ——-> Matches three letters or four numbersThe string “foo”
  2. ^foo ——-> “foo” at the start of a string
  3. foo$ ——-> “foo” at the end of a string
  4. ^foo$ ——-> “foo” when it is alone on a string
  5. [abc] ——-> a, b, or c
  6. [a-z] ——-> Any lowercase letter
  7. [^A-Z] ——-> Any character that is not a uppercase letter
  8. (gif|jpg) ——-> Matches either “gif” or “jpeg”
  9. [a-z]+ ——-> One or more lowercase letters
  10. [0-9\.\-] ——-> Аny number, dot, or minus sign
  11. ^[a-zA-Z0-9_]{1,}$ ——-> Any word of at least one letter, number or _
  12. ([wx])([yz]) ——-> wy, wz, xy, or xz
  13. [^A-Za-z0-9] ——-> Any symbol (not a number or a letter)
  14. ([A-Z]{3}|[0-9]{4}) ——-> Matches three letters or four numbers

Email Id Validation in PHP?

<?php
$email = “emailid@domain.com”;
if(eregi(“^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$”, $email)) {
echo “Valid email address.”;
} else {
echo “Invalid email address.”;
}
?>

What are Try , Throw and Catch blocks in PHP?

  1. Try – A function using an exception should be in a “try” block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is “thrown”
  2. Throw – This is how you trigger an exception. Each “throw” must have at least one “catch”
  3. Catch – A “catch” block retrieves an exception and creates an object containing the exception information

Example how to handle an Exception in PHP?

<?php
/* Function to Throw an Exception */
function checkNum($number) {
if($number>1) {
throw new Exception(“Value must be 1 or below”);
}
return true;
}
/* Function to Throw an Exception */

//trigger exception in a “try” block
try {
checkNum(2);
//If the exception is thrown, this text will not be shown
echo ‘If you see this, the number is 1 or below’;
} catch(Exception $e) {
echo ‘Message: ‘ .$e->getMessage();
}
?>

What is an Exception Handling?

Exception handling is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs. This condition is called an exception.

This is what normally happens when an exception is triggered:

  • The current code state is saved
  • The code execution will switch to a predefined (custom) exception handler function
  • Depending on the situation, the handler may then resume the execution from the saved code state, terminate the script execution or continue the script from a different location in the code

We will show different error handling methods:

  • Basic use of Exceptions
  • Creating a custom exception handler
  • Multiple exceptions
  • Re-throwing an exception
  • Setting a top level exception handler

Note: Exceptions should only be used with error conditions, and should not be used to jump to another place in the code at a specified point.

How to create Custom Exception Class?

<?php
/* Creating Custom Exception Class */
class customException extends Exception {
public function errorMessage() {
//error message
$errorMsg = ‘Error on line ‘.$this->getLine().’ in ‘.$this->getFile()
.’: <b>’.$this->getMessage().'</b> is not a valid E-Mail address’;
return $errorMsg;
}
}
/* Creating Custom Exception Class */

$email = “wrongEmail@domain…com”;
try {
//check if
if(!eregi(“^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$”, $email)) {
//throw exception if email is not valid
throw new customException($email);
}
echo “Email Id is Valid”;
} catch (customException $e) {
//display custom message
echo $e->errorMessage();
}
?>

What are the advantages of CURL Library?

PHP supports libcurl, a library that allows you to connect and communicate to many different types of servers with many
different types of protocols.

LIBCURL (CURL LIBRARY PHP)currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols.

LIBCURL (CURL LIBRARY PHP) also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP’s ftp
extension), HTTP form based upload, proxies, cookies, and
user plus password authentication

Define CURL?

curl is a tool to transfer data from or to a server, using one of the supported protocols (DICT, FILE, FTP, FTPS, GOPHER, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, POP3, POP3S, RTMP, RTSP, SCP, SFTP, SMTP, SMTPS, TELNET and TFTP). The command is designed to work without user interaction.

A typical PHP cURL usage follows the following sequence of steps.

curl_init – Initializes the session and returns a cURL handle which can be passed to other cURL functions.

curl_opt – This is the main work horse of cURL library. This function is called multiple times and specifies what we want the cURL library to do.

curl_exec – Executes a cURL session.

curl_close – Closes the current cURL session.

Below are some examples which should make the working of cURL more clearer.

The below piece of PHP code uses cURL to download Google’s RSS feed.

twitter and facebook integration with PHP?

Twitter and Facebook Integration:http://onlinewebapplication.com/2011/08/login-facebook-twitter-php.html

Facebook Integration:
http://ryanmerket.com/connectdocs/

What are the differences between API and Webservices?

Web service is like advanced Urls and API is Programmed Interface. API contains classes and Interfaces just like a program.

A web service is a form of API (Application Programming Interface).

An API is used by a computer programmer to establish a link between software applications. This interface can take several forms, a web service is just one of these.

There are several types of web service. SOAP (Simple Object Access Protocol) is one of the most common.

The API takes the form of a service description (WSDL) which is used to automatically generate the program code which makes the connection.

How can we increase the execution time of a PHP script?

by changing the following setup at php.inimax_execution_time = 30; Maximum execution time of each script, in seconds

What is the maximum size of a file that can be uploaded using PHP and how can we change this?

By default the maximum size is 2MB. and we can change the following
setup at php.ini upload_max_filesize = 2M

How can we get the browser properties using PHP?

By using
$_SERVER[‘HTTP_USER_AGENT’]
variable.

How can we get the properties (size, type, width, height) of an image using PHP image functions?

To know the Image type use exif_imagetype () function
To know the Image size use getimagesize () function
To know the image width use imagesx () function
To know the image height use imagesy() function

What is the functionality of the function strstr and stristr?

strstr Returns part of string from the first occurrence of needle(sub string that we finding out ) to the end of string.
$email= ‘sonialouder@gmail.com’;
$domain = strstr($email, ‘@’);
echo $domain; // prints @gmail.com
here @ is the needle
stristr is case-insensitive means able not able to differentiate between a and A

How can we find the number of rows in a result set using PHP?

$result = mysql_query($sql, $db_link);

$num_rows = mysql_num_rows($result);

echo “$num_rows rows found”;

How can I make a script that can be bi-language (supports English, German)?

We can maintain two separate language file for each of the language. all the labels are putted in both language files as variables and assign those variables in the PHP source. on runtime choose the required language option.

List out the predefined classes in PHP?

Directory
stdClass
__PHP_Incomplete_Class
exception
php_user_filter

How can I retrieve values from one database server and store them in other database server using PHP?

We can always fetch from one database and rewrite to another. here is a nice solution of it.

$db1 = mysql_connect(“host”,”user”,”pwd”);

mysql_select_db(“db1”, $db1);

$res1 = mysql_query(“query”,$db1);

$db2 = mysql_connect(“host”,”user”,”pwd”);

mysql_select_db(“db2”, $db2);

$res2 = mysql_query(“query”,$db2);

At this point you can only fetch records from you previous ResultSet,
i.e $res1
But you cannot execute new query in $db1, even if you supply the link as because the link was overwritten by the new db.so at this point the following script will fail

$res3 = mysql_query(“query”,$db1); //this will failSo how to solve that?
take a look below.

$db1 = mysql_connect(“host”,”user”,”pwd”)

mysql_select_db(“db1”, $db1);

$res1 = mysql_query(“query”,$db1);

$db2 = mysql_connect(“host”,”user”,”pwd”, true)

mysql_select_db(“db2”, $db2);

$res2 = mysql_query(“query”,$db2);
So mysql_connect has another optional boolean parameter which indicates whether a link will be created or not. as we connect to the $db2 with this optional parameter set to ‘true’, so both link will remain live.

now the following query will execute successfully.

$res3 = mysql_query(“query”,$db1);

List out some tools through which we can draw E-R diagrams for mysql.

Case Studio
Smart Draw

Name a few ways to output (print) a block of HTML code in PHP?

Well you can use any of the output statments in PHP, such as, print, echo, and printf. Most individuals use the echo statement as in:

PHP:

echo “My test string $variable”;

However, you can also use it like so:

PHP

echo <<<OUTPUT
This text is written to the screen as output and this $variable is parsed too. If you wanted you can have <span> HTML tags in here aswell.</span> The END; remarks must be on a line of its own, and can‘t contain any extra white space.
END;

How can you get round the stateless nature of HTTP using PHP?

The top two options that are used are sessions and cookies. To access a session, you will need to have session_start() at the top of each page, and then you will use the $_SESSION hash to access and store your session variables. For cookies, you only have to remember one rule. You must use the set_cookie function before any output is started in your PHP script. From then on you can use the $_COOKIE has to access your cookie variables and values.

There are other methods, but they are not as fool proof and most often than not depend on the IP address of the visitor, which is a very dangerous thing to do.

Given a line of text $string, how would you write a regular expression to strip all the HTML tags from it?

First of all why would you write a regular expression when a PHP function already exists? Seephp.net’s strip_tags function. However, considering this is an interview question, I would write it like so:

PHP:

$stringOfText = “<p>This is a testing</p>”;
$expression = “/<(.*?)>(.*?)<\/(.*?)>/”;
echo preg_replace($expression, “\\2″, $stringOfText);
// It was suggested (by Fred) that /(<[^>]*>)/ would work too.
$expression = “/(<[^>]*>)/”;
echo preg_replace($expression, “”, $stringOfText);

What does the following code do? Explain what’s going on there.

PHP:

$date=’09/25/2008′;

print ereg_replace(“([0-9]+)/([0-9]+)/([0-9]+)”,“\\2/\\1/\\3″, $date);
This code is reformatting the date from MM/DD/YYYY to DD/MM/YYYY. A good friend got me hooked on writing regular expressions like below, so it could be commented much better, granted this is a bit excessive for such a simple regular expression.

PHP:

// Match 0-9 one or more times then a forward slash

 $regExpression = “([0-9]+)/”

// Match 0-9 one or more times then another forward slash

 $regExpression .= “([0-9]+)/”;

// Match 0-9 one or more times yet again.

 $regExpression .= “([0-9]+)”Now the \\2/\\1/\\3 denotes the parentheses matches. The first parenthesis matches the month, the second the day, and the third the year.

What function can you use to open a file for reading and writing?

  1. fget()
    This is not a function in PHP, so it will fail with an error.
  2. file_open()
    This is not a function in PHP, so it will fail with an error.
  3. fopen()
    This is the correct function, it allows you to open a file for reading and/or writing. In fact, you have a lot of options, check outphp.net for more information.
  4. open_file()
    This is not a function in PHP, so it will fail with an error.

What function would you use to redirect the browser to a new page?

  1. redir()
    This is not a function in PHP, so it will fail with an error.
  2. header()
    This is the correct function, it allows you to write header data to direct the page to a new location. For example:

PHP:

  1. header(“Location: http://www.google.com/”);
  2. location()
    This is not a function in PHP, so it will fail with an error.
  3. redirect()
    This is not a function in PHP, so it will fail with an error.

What is the difference between include, include_once? and require?

All three allow the script to include another file, be it internal or external depending on if allow_url_fopen is enabled. However, they do have slight differences, which are denoted below.

  1. include()
    The include() function allows you to include a file multiple times within your application and if the file does not exist it will throw a Warning and continue on with your PHP script.
  2. include_once()
    include_once() is like include() except as the name suggests, it will only include the file once during the script execution.
  3. require()
    Like include(), you can request to require a file multiple times, however, if the file does not exist it will throw a Warning that will result in a Fatal Error stopping the PHP script execution.

How do you access and set properties of a class from within the class?

We can use the $this->PropertyName syntax.

PHP:

class myclass {
private $propertyName;
public function __construct() {
$this->propertyName = “value”;
   }

How would you create an object, which is an instance of “myclass”?

PHP:

$obj = new myclass();

How would you declare a class named “myclass” with no methods or properties?

PHP:class myclass
{
}

What does === do? What’s an example of something that will give true for ‘==’, but not ‘===’?

The === operator is used for functions that can return a Boolean false and that may also return a non-Boolean value which evaluates to false.
Such functions would be strpos and strrpos.
We are having a hard time with the second portion, as We are able to come up with scenarios where ‘==’ will be false and ‘===’ would come out true, but it’s hard to think of the opposite.

So here is the example:

PHP:

if (strpos(“abc”, “a”) == true) {
// this does not get hit, since “a” is in the 0 index position, it returns false.
}
if (strpos(“abc”, “a”) === true) {
// this does get hit as the === ensures this is treated as non-boolean.
}

How do you debug a PHP application?

PHP – Advanced PHP Debugger or PHP-APD.

First we have to install it by running:
pear install apd

Once installed, start the trace by placing the following code at the beginning of your script:
apd_set_pprof_trace();
Then once we have executed our script, look at the log in apd.dumpdir.
We can even use the pprofp command to format the data as in:
pprofp -R /tmp/pprof.22141.0

What is the difference between foo() & @foo()?

foo() executes the function and any parse/syntax/thrown errors will be displayed on the page.

@foo() will mask any parse/syntax/thrown errors as it executes.
we will commonly find most applications use @mysql_connect() to hide mysql errors or @mysql_query.

However, that approach is significantly flawed as we should never hide errors, rather we should manage them accordingly and if we can, fix them.

What functions can you use to add library code to the currently running script?

  1. Class libraries written in PHP, so include(), include_once(), require(), and require_once().
  2. However, we can also include COM objects and .NET libraries.
  3. By utilizing thecom_load and the dotnet_load respectively you can incorporate COM objects and .NET libraries into your PHP code, thus anytime you see “library code” in a question, make sure we remember these two functions.

What is the difference between a reference and a regular variable? How do you pass by reference and why would you want to?

Reference variables pass the address location of the variable instead of the value. So when the variable is changed in the function, it is also changed in the whole application, as now the address points to the new value.
Now a regular variable passes by value, so when the value is changed in the function, it has no affect outside the function.

PHP:

  1. $myVariable= “its’ value”;
  2. Myfunction(&$myVariable);// Pass by Reference Example

So why would you want to pass by reference? The simple reason, is you want the function to update the value of your variable so even after you are done with the function, the value has been updated accordingly.

What would the following code print to the browser? Why?

PHP:

$num = 10;

function multiply(){

  $num = $num * 10;

}

multiply();

echo $num; // prints 10 to the screen

Since the function does not specify to use $num globally either by using global $num; or by $_GLOBALS[‘num’] instead of $num, the value remains 10.

What’s the difference between sort(), asort() and ksort? Under what circumstances would you use each of these?

  1. sort()
    Sorts an array in alphabetical order based on the value of each element. The index keys will also be renumbered 0 to length – 1. This is used primarily on arrays where the indexes/keys do not matter.
  2. asort()
    Like the sort() function, this sorts the array in alphabetical order based on the value of each element, however, unlike the sort() function, all indexes are maintained, thus it will not renumber them, but rather keep them. This is particularly useful with associate arrays.
  3. ksort()
    Sorts an array in alphabetical order by index/key. This is typically used for associate arrays where you want the keys/indexes to be in alphabetical order.

Which of the following will NOT add john to the users array?

  1. $users[ ] = ‘john’;

Successfully adds john to the array

  1. array_add($users,’john’);

Fails stating Undefined Function array_add()

  1. array_push($users,‘john’);

Successfully adds john to the array

  1. $users ||= ‘john’;

Fails stating Syntax Error

What is shift operator?

The shift operations allow bits to be moved to the left or right in a word. There are three types of shift operations: logical, rotate and arithmetic.

http://www.cs.uaf.edu/~cs301/notes/Chapter5/node3.html

$a & $b    –  And        –  Bits that are set in both $a and $b are set.
$a | $b    –  Or (inclusive or)    –  Bits that are set in either $a or $b are set.
$a ^ $b    –  Xor (exclusive or)-  Bits that are set in $a or $b but not both are set.
~ $a    –  Not        –  Bits that are set in $a are not set, and vice versa.
$a << $b    –  Shift left    –  Shift the bits of $a $b steps to the left (each step means “multiply by two”)
$a >> $b    –  Shift right    –  Shift the bits of $a $b steps to the right (each step means “divide by two”)

How do I find second highest value from a table?

<?php

$query = mysql_query(“SELECT number FROM table ORDER BY number DESC LIMIT 2”);
$second_highest = mysql_result($query,1,0);
echo “the answer to your question is $second_highest”;
?>

How do I find the ID of a new row added to a table?

<?php
$q = mysql_query(“INSERT INTO mytable VALUES(‘test’)”);
$rownumber = mysql_insert_id();
//$rownumber contains the id of the new row
?>

Posted by C

What is Opcode & Opcode Caching

Opcode:
After an interpreted language has been parsed, it is compiled into an intermediate language known as operation code (hence forth known as opcode).
When a PHP program is actually executed, it is using the opcode it generated during the parsing process, and not the actual code that the developer has written.

Usage of Opcode:
By generating opcode as opposed to simply executing the program as written, it provides the interpreter an opportunity for internal optimization.
For example, if it discovers that a variable has been declared but never used or assigned a value, it may be intelligent enough to remove that declaration in the opcode.
Similarly, if the specificc language being used is particularly fast at post-incrementing an integer, but is dreadfully slow at pre-incrementing an integer, if pre-incrementing is used, the interpreter may switch to post-incrementing if it will not a ffect the execution of the program.
Hundreds of these optimizations may take place in order to generate the most effcient code possible.

Opcode Caching:
Normally after a program is executed, the associated opcode is removed from RAM and is recreated each time the program is executed.
In order to solve the issue of poor associated with this process, opcode caching can be used.
The idea behind opcode caching is relatively simple. Instead of parsing and generating opcode each time the same program is executed, instead keep the resulting opcode in memory or disk based cache and only re-parse the fi le if the original has changed.
Now, instead of interpreting the program, a quick and simple check as to whether the fi le is the same as the last time it was interpreted can be done, and if it is the same, the program can be immediately executed.

What are the two new error levels introduced in PHP5.3?

E_DEPRECATED
The E_DEPRECATED error level is used to indicate that a function or feature has been deprecated.

E_USER_DEPRECATED
The E_USER_DEPRECATED level is intended for indicating deprecated features in user code, similarly to the E_USER_ERROR and E_USER_WARNING levels.

How can we convert the time zones using PHP?

By using date_default_timezone_get and
date_default_timezone_set function on PHP 5.1.0 <?php
// Discover what 8am in Tokyo relates to on the East Coast of the US

// Set the default timezone to Tokyo time:
date_default_timezone_set(‘Asia/Tokyo’);

// Now generate the timestamp for that particular timezone, on Jan 1st, 2000
$stamp = mktime(8, 0, 0, 1, 1, 2000);

// Now set the timezone back to US/Eastern
date_default_timezone_set(‘US/Eastern’);

// Output the date in a standard format (RFC1123), this will print:
// Fri, 31 Dec 1999 18:00:00 EST
echo ‘<p>’, date(DATE_RFC1123, $stamp) ,'</p>’;?>

What are the differences between public, private, protected, static, transient, final and volatile?

Public: Public declared items can be accessed everywhere.
Protected: Protected limits access to inherited and parent
classes (and to the class that defines the item).
Private: Private limits visibility only to the class that defines
the item.
Static: A static variable exists only in a local function scope,
but it does not lose its value when program execution leaves this scope.
Final: Final keyword prevents child classes from overriding a
method by prefixing the definition with final. If the class itself is
being defined final then it cannot be extended.
transient: A transient variable is a variable that may not
be serialized. 
volatile: a variable that might be concurrently modified by multiple
threads should be declared volatile. Variables declared to be volatile
will not be optimized by the compiler because their value can change at
any time.

What is the Syntax for move_uploaded_file()

move_uploaded_file — Moves an uploaded file to a new location

Syntax:
bool move_uploaded_file ( string $filename , string $destination );

Example:

<?php
$uploads_dir = ‘/uploads’;
foreach ($_FILES[“pictures”][“error”] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES[“pictures”][“tmp_name”][$key];
$name = $_FILES[“pictures”][“name”][$key];
move_uploaded_file($tmp_name, “$uploads_dir/$name”);
}
}
?>

What is a Factory Design Pattern? Explain with an example?

The Factory pattern allows for the instantiation of objects at runtime. It is called a Factory Pattern since it is responsible for “manufacturing” an object. A Parameterized Factory receives the name of the class to instantiate as argument.

Parameterized Factory Method

<?php
class Example
{
// The parameterized factory method
public static function factory($type)
{
if (include_once ‘Drivers/’ . $type . ‘.php’) {
$classname = ‘Driver_’ . $type;
return new $classname;
} else {
throw new Exception(‘Driver not found’);
}
}
}
?>

Defining this method in a class allows drivers to be loaded on the fly. If the Example class was a database abstraction class, loading a MySQL and SQLite driver could be done as follows:

<?php
// Load a MySQL Driver
$mysql = Example::factory(‘MySQL’);

// Load an SQLite Driver
$sqlite = Example::factory(‘SQLite’);
?>

What are Patterns?

Patterns are ways to describe best practices and good designs. They show a flexible solution to common programming problems.

Explain singleton pattern?

If a system only needs one instance of a class, and that instance needs to be accessible in many different parts of a system, you control both instantiation and access by making that class a singleton.

Ensure a class has only one instance, and provide a global point of access to it.

Singletons are very similar to GlobalVariables, and are often implemented with global variables, even if they masquerade as class members.

The Singleton ensures that there can be only one instance of a Class and provides a global access point to that instance. Singleton is a “Gang of Four” Creational Pattern.

The Singleton pattern is often implemented in Database Classes, Loggers, Front Controllers or Request and Response objects.

How can remove duplicate values from an array php

We can use array_unique function in php

<?php
$array1 = array(“test”,”test1″,”test2″,”test”);
$result = array_unique($array1);
print_r($result); ?>

Outputs:

Array
(
[0] => test
[1] => test1
[2] => test2
)

Access Specifiers in PHP

Definition of Access Specifiers
Access specifiers specify the level of access that the outside world (i.e. other class objects, external functions and global level code) have on the class methods and class data members. Access specifiers can either be publicprivate or protected.


Why do we need Access specifiers
Access specifiers are used as a key component of Encapsulation and Data Hiding. By using either of the access specifiers mentioned above i.e. public, private or protected you can hide or show the internals of your class to the outside world.


Explanation of each access specifier
1. Private
2. Protected
3. Public

1. Private
A private access specifier is used to hide the data member or member function to the outside world. This means that only the class that defines such data member and member functions have access them. Look at the example below:

class Customer {

private $name;

public function setName($name) {

$this->name = $name;

}

public function getName() {

return $this->name;

}

}

$c = new Customer();

$c->setName(“Sunil Bhatia”);

echo $c->name; //error, $name cannot be accessed from outside the class

//$name can only be accessed from within the class

echo $c->getName(); //this works, as the methods of the class have access

//to the private data members or methods

In the above example, echo $c->name will give you an error as $name in class Customer has been declared private and hence only be accessed by its member functions internally. Therefore, the following line echo $c->getName() will display the name.

  1. Public
    A public access specifier provides the least protection to the internal data members and member functions. A public access specifier allows the outside world to access/modify the data members directly unlike the private access specifier. Look at the example below:

class Customer {

public $name;

public function setName($name) {

$this->name = $name;

}

public function getName() {

return $this->name;

}

}

$c = new Customer();

$c->setName(“Sunil Bhatia”);

echo $c->name;  // this will work as it is public.

$c->name = “New Name” ; // this does not give an error.

In the above example, echo $c->name will work as it has been declared as public and hence can be accessed by class member functions and the rest of the script.

  1. Protected
    A protected access specifier is mainly used with inheritance. A data member or member function declared as protected will be accessed by its class and its base class but not from the outside world (i.e. rest of the script). We can also say that a protected data member is public for the class that declares it and it’s child class; but is private for the rest of the program (outside world). Look at the example below:

class Customer {

protected $name;

public function setName($name) {

$this->name = $name;

}

public function getName() {

return $this->name;

}

}

class DiscountCustomer extends Customer {

private $discount;

public function setData($name, $discount) {

$this->name = $name; //this is storing $name to the Customer

//class $name variable. This works

// as it is a protected variable

$this->discount = $discount;

}

}

$dc = new DiscountCustomer();

$dc->setData(“Sunil Bhatia”,10);

echo $dc->name; // this does not work as $name is protected and hence

// only available in Customer and DiscountCustomer class

In the above example, echo $dc->name will not work work $name has been defined as a protected variable and hence it is only available in Customer and DiscountCustomer class.

Difference between array_search() and in_array() in php

in_array() checks if the specified value exits in the array, while
array_search() searches an array for a given value and returns the key

Example of in_array():
<?
$a1=array(“a”=>”one”,”b”=>”two”);
if(in_array(“one”,$a1)) {
  echo “exist”;
} else {
  echo “not exist”;
}

O/P: exist
?>

Example of array_search():
<?php
$a1=array(“a”=>”one”,”b”=>”two”);
echo array_search(“one”,$a1);


O/P: a
?>

What is array_shift?

array_shift — Shift an element off the beginning of array
Returns the shifted value, or NULL if array is empty or is not an array.

Example:
<?php
$stack = array(“orange”, “banana”, “apple”, “raspberry”);
$fruit = array_shift($stack);
print_r($stack);
?>

O/P:
Array
(
[0] => banana
[1] => apple
[2] => raspberry
)

What is array_unshift?

array_unshift — Prepend one or more elements to the beginning of an array
Returns the new number of elements in the array.

Example:
<?php
$queue = array(“orange”, “banana”);
array_unshift($queue, “apple”, “raspberry”);
print_r($queue);
?>
O/P:
Array
(
[0] => apple
[1] => raspberry
[2] => orange
[3] => banana
)

Persistent Cookies in PHP

A persistent cookie is a cookie which is stored in a cookie file permanently on the browser’s computer. By default, cookies are created as temporary cookies which stored only in the browser’s memory. When the browser is closed, temporary cookies will be erased. You should decide when to use temporary cookies and when to use persistent cookies based on their differences:

Temporary cookies can not be used for tracking long-term information.
Persistent cookies can be used for tracking long-term information.

Temporary cookies are safer because no programs other than the browser can access them.
Persistent cookies are less secure because users can open cookie files see the cookie values.

Static Keyword in PHP

  1. Declaring class properties or methods as static makes them accessible without needing an instantiation of the class.
  2. A property declared as static can not be accessed with an instantiated class object (though a static method can).
  3. Because static methods are callable without an instance of the object created, the pseudo-variable$this is not available inside the method declared as static.
  4. Static properties cannot be accessed through the object using the arrow operator ->.
  5. Calling non-static methods statically generates anE_STRICT level warning.

How will you optimize php applications?

Use Firebug with YSlow:
Firebug and YSlow are powerful tools to analyze the front end of your site.  Run the most common request on your site and see what YSlow says.  Expect a low grade, probably a D or lower.  If you can reach a level C or greater you’re doing really well as some of the requirements are not practical for most applications.

Firebug Options:
Net: How many calls are there?  Try to minize these calls and definitely remove any 404 calls as they can eat up server resources.

Console:  Do you have a lot of POST calls?  Some libraries, like dojo’s javascript framework, can make a lot of POST requests.  Reduce these if possible.

YSlow: Rules I would pay attention to:

  1. Make fewer HTTP Requests
    3. Add an Expires Header
    4. Gzip components (server related)
    5. Put CSS at the top
    6. Put JS at the bottom (not always possible)
    7. Avoid CSS expressions
    10. Minify JS

Minify Javascript and CSSMinification is the process of compacting your scripts by removing extraneous content such as white space.   In addition, minification can make attempts at refactoring the code to remove redunancies.  If you want to play it safe, only remove white space to ensure your code is still running. The Yahoo compressor is one of the best minifiers out there and reduces both Javascript and CSS by a significant percentage.

How-to:
java -jar yuicompressor-x.y.z.jar -o style_minified.css style.css
add the “–nomunge” to only do whitespace compressions.

Merge css and js http requests– manually or automated
Reduce the amount of calls you make to various CSS and JS files by merging them to one URL.  This is more work but will reduce the overhead.

How-to – manually:
This is really easy, take your css and copy and paste them together into one file.  Make sure your preserve the order of your css.  The same applies to your Javascript files.
How-to – Automated – google or your own custom:
Google has a php script which can take various sources and return them as one.

Resources:

CSS Background Images are bad – usually
Using a div for all of your images with a background image is not that great for performance as it requires more calls.  I’ll be the first to admit it’s my favourite way to design, but you should try to avoid them where possible.  In addition, for hover states try using one large image with background-position calls to show specific parts.

How to:
Use background-position to select which portion of the large image you want to show.  There isn’t much more to explain.

GZipGzipping files on the server side will reduce the amount of overhead significantly.  It adds a bit more on the server side, but generally the pay off should be well worth it.

How to:
It depends on your server situation, but here’s a snippet:
mod_gzip_on Yes
mod_gzip_item_include mime ^application/x-javascript$
Refer to http://snipplr.com/view/9017/gzip-your-components/ for details

Resources:
http://developer.yahoo.com/performance/rules.html#gzip
http://snipplr.com/view/9017/gzip-your-components/

Compound Datatypes in PHP

Compound data can contain multiple values. PHP has 2 compound data types:

  1. array  – Can hold multiple values indexed by numbers or strings
  2. object -Can hold multiple values (properties), and can also contain methods (functions) for working on properties

PHP array sorting Functions

sort
rsort
asort
arsort
ksort
krsort
usort
uasort
uksort
array_multisort
natsort
natcasesort

List PHP Array Functions

  • array_change_key_case— Changes all keys in an array
  • array_chunk— Split an array into chunks
  • array_combine— Creates an array by using one array for keys and another for its values
  • array_count_values— Counts all the values of an array
  • array_diff_assoc— Computes the difference of arrays with additional index check
  • array_diff_key— Computes the difference of arrays using keys for comparison
  • array_diff_uassoc— Computes the difference of arrays with additional index check which is performed by a user supplied callback function
  • array_diff_ukey— Computes the difference of arrays using a callback function on the keys for comparison
  • array_diff— Computes the difference of arrays
  • array_fill_keys— Fill an array with values, specifying keys
  • array_fill— Fill an array with values
  • array_filter— Filters elements of an array using a callback function
  • array_flip— Exchanges all keys with their associated values in an array
  • array_intersect_assoc— Computes the intersection of arrays with additional index check
  • array_intersect_key— Computes the intersection of arrays using keys for comparison
  • array_intersect_uassoc— Computes the intersection of arrays with additional index check, compares indexes by a callback function
  • array_intersect_ukey— Computes the intersection of arrays using a callback function on the keys for comparison
  • array_intersect— Computes the intersection of arrays
  • array_key_exists— Checks if the given key or index exists in the array
  • array_keys— Return all the keys or a subset of the keys of an array
  • array_map— Applies the callback to the elements of the given arrays
  • array_merge_recursive— Merge two or more arrays recursively
  • array_merge— Merge one or more arrays
  • array_multisort— Sort multiple or multi-dimensional arrays
  • array_pad— Pad array to the specified length with a value
  • array_pop— Pop the element off the end of array
  • array_product— Calculate the product of values in an array
  • array_push— Push one or more elements onto the end of array
  • array_rand— Pick one or more random entries out of an array
  • array_reduce— Iteratively reduce the array to a single value using a callback function
  • array_replace_recursive— Replaces elements from passed arrays into the first array recursively
  • array_replace— Replaces elements from passed arrays into the first array
  • array_reverse— Return an array with elements in reverse order
  • array_search— Searches the array for a given value and returns the corresponding key if successful
  • array_shift— Shift an element off the beginning of array
  • array_slice— Extract a slice of the array
  • array_splice— Remove a portion of the array and replace it with something else
  • array_sum— Calculate the sum of values in an array
  • array_udiff_assoc— Computes the difference of arrays with additional index check, compares data by a callback function
  • array_udiff_uassoc— Computes the difference of arrays with additional index check, compares data and indexes by a callback function
  • array_udiff— Computes the difference of arrays by using a callback function for data comparison
  • array_uintersect_assoc— Computes the intersection of arrays with additional index check, compares data by a callback function
  • array_uintersect_uassoc— Computes the intersection of arrays with additional index check, compares data and indexes by a callback functions
  • array_uintersect— Computes the intersection of arrays, compares data by a callback function
  • array_unique— Removes duplicate values from an array
  • array_unshift— Prepend one or more elements to the beginning of an array
  • array_values— Return all the values of an array
  • array_walk_recursive— Apply a user function recursively to every member of an array
  • array_walk— Apply a user function to every member of an array
  • array— Create an array
  • arsort— Sort an array in reverse order and maintain index association
  • asort— Sort an array and maintain index association
  • compact— Create array containing variables and their values
  • count— Count all elements in an array, or something in an object
  • current— Return the current element in an array
  • each— Return the current key and value pair from an array and advance the array cursor
  • end— Set the internal pointer of an array to its last element
  • extract— Import variables into the current symbol table from an array
  • in_array— Checks if a value exists in an array
  • key— Fetch a key from an array
  • krsort— Sort an array by key in reverse order
  • ksort— Sort an array by key
  • list— Assign variables as if they were an array
  • natcasesort— Sort an array using a case insensitive “natural order” algorithm
  • natsort— Sort an array using a “natural order” algorithm
  • next— Advance the internal array pointer of an array
  • pos— Alias of current
  • prev— Rewind the internal array pointer
  • range— Create an array containing a range of elements
  • reset— Set the internal pointer of an array to its first element
  • rsort— Sort an array in reverse order
  • shuffle— Shuffle an array
  • sizeof— Alias of count
  • sort— Sort an array
  • uasort— Sort an array with a user-defined comparison function and maintain index association
  • uksort— Sort an array by keys using a user-defined comparison function
  • usort— Sort an array by values using a user-defined comparison function

Difference between array_merge and array_combine in php

array_merge — Merge one or more arrays

Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one.
It returns the resulting array.
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one.
If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
If only one array is given and the array is numerically indexed, the keys get reindexed in a continuous way.

Example:

<?php
$array1 = array(“color” => “red”, 2, 4);
$array2 = array(“a”, “b”, “color” => “green”, “shape” => “trapezoid”, 4);
$result = array_merge($array1, $array2);
print_r($result);
?>

Array
(
[color] => green
[0] => 2
[1] => 4
[2] => a
[3] => b
[shape] => trapezoid
[4] => 4
)
array_combine — Creates an array by using one array for keys and another for its values

Example:

<?php
$a = array(‘green’, ‘red’, ‘yellow’);$b = array(‘avocado’, ‘apple’, ‘banana’);$c = array_combine($a, $b);
print_r($c);?>

Array

(

[green]  => avocado

[red]    => apple

[yellow] => banana

)

Difference between Echo and Print

echo and print are the two most construct for printing out put.

  1. The value returned by print will be 1 if printing was successful otherwise returned 0 if un success.
  2. echo is a statement and print is function

Difference between Implode() and Join in PHP

Join is an Alias of Implode. Both these functions allow you to convert an array into a string.
Join allows us to join the items in an array with a ‘glue’ string.

Example:
<?php
$arr = array(‘Chaitanya’, ‘Lakshmi’, ‘Lella’);
$str = join(“,”, $arr);
echo $str;
?>
Output: Chaitanya,Lakshmi,Lella.

implode: implode Returns a string from array elements.

Example:
<?php
$arr = array(‘Chaitanya’, ‘Lakshmi’, ‘Lella’);
$str = implode(“,”, $arr);
echo $str;
?>
Output: Chaitanya,Lakshmi,Lella.

Difference between explode() and implode() in php

Explode: Split a string by another string

Example . explode() 
<?php
// Example 1
$history= “php4 php5 php6″;
$pieces = explode(” “, $history);
echo $history[0]; // php4
echo $history[1]; // php5
echo $history[1]; // php6
?>

Implode: Joins Array Elements using a Given String

Example . implode()

<?php
$array = array(‘lastname’, ’email’, ‘phone’);
$comma_separated = implode(“,”, $array);
echo $comma_separated; // lastname,email,phone
?>

Difference Between Split and explode functions in PHP

Both the functions are used to Split a string. 

1. Split is used to split a string using a regular expression.

2. Explode is used to split a string using another string.

E.g explode (” this”, “this is a string”); will return “Is a string”
Split (” + “, “This+ is a string”)

The split() function splits the string into an array using a regular expression and returns an array.
Ex: split(:India:Pakistan:Srilanka); returns an array that contains India, Pakistan, Srilanka.

The explode() function splits the string by string.
Ex: explode(and India and Pakistan and Srilanka); returns an array that contains India, Pakistan, Srilanka

What is Magic Method __call()

The magic method __call() is to undeclared methods. This method is automatically called internally when the program tires to execute a method that has not been defined within the class at the time of development.

The magic method __call() takes two arguments. The first argument is the name of the undeclared method invoked by the program and the second is an array that contains a list of parameters passed to the undeclared array.

CSS

How will you fix cross browser issues for CSS and JAVASCRIPT?

http://www.catswhocode.com/blog/15-techniques-and-tools-for-cross-browser-css-coding

  1. Reset CSS
  2. Internet Explorer conditionnal comments
  3. Internet Explorer hacks
  4. Targeting Opera only
  5. Targeting Safari only
  6. Targeting Google Chrome only
  7. “Browser Detect” PHP Class
  8. JQuery browser detection

How to override inline css with external css?

We can override the Inline CSS with External CSS using “important” keyword.

Example:
strong[style] { color: blue !important; }

How do you make a tool tip that appears on hover?

The most simple way is to use the ‘title’ attribute like this…

HTML
<span title=”Example of the title attribute in use”>like this</span>

CSS

a.tooltip {

position:relative;

cursor:help;

}

a.tooltip span {

display: none;

position:absolute;

top:1.5em;

left:0;

width:15em;

padding:0 2px;

}

a.tooltip:hover {

display:inline;

}

a.tooltip:hover span {

display:block;

border:1px solid gray;

background-color:white;

}
HTML

<a class=”tooltip” href=”#n”>Karl Marx<span>-info goes here-</span></a>

Without this part… a.tooltip:hover {
display:inline;
}
..it won’t work in IE.

The “#n” in the link is to prevent the page from jumping to the top if the link is clicked. The “href” part is necessary as it won’t work in IE without it.

What is the difference between ID and CLASS Selector?

ID identifies and sets style to one and only one occurrence of an element while class can be attached to any number of elements. By singling out one occurrence of an element the unique value can be declared to said element.

CSS

#eva1 {background: red; color: white}

.eva2 {background: red; color: white}
HTML – ID

<P ID=eva1>

Paragraph 1 – ONLY THIS occurrence of the element P (or single occurrence of some other element) can be identified as eva1

</P>

<P ID=eva1>

Paragraph 2 – This occurrence of the element P CANNOT be identified as eva1

</P>
HTML – CLASS

<P class=eva2>

Paragraph 1 – This occurrence of the element P can be classified as eva2

</P>

<P class=eva2>

Paragraph 2 – And so can this, as well as occurrences of any other element,

</P>

What are pseudo-classes?

Pseudo-classes are fictional element types that do not exist in HTML. In CSS1 there is only one element type which can be classed this way, namely the A element (anchor). By creating three fictional types of the A element individual style can be attached to each class. These three fictional element types are: A as unvisited link, A as active link and A as visited link. Pseudo-classes are created by a colon followed by pseudo-class’s name. They can also be combined with normal classes,

e.g.:

A:link {background: black; color: white}

A:active {background: black; color: red}

A:visited {background: transparent; color: black}

<A HREF….>This anchor (or rather these anchors) will be displayed as declared above</A>

A.foot:link {background: black; color: white}

A.foft:active {background; black: color: red}

A.foot:visited {background: transparent; color: black}

<A CLASS=foot HREF….>This anchor and all other anchors with CLASS foot will be displayed as declared above</A>

Can Style Sheets and HTML stylistic elements be used in the same document?

Yes. Style Sheets will be ignored in browsers without CSS-support and HTML stylistic elements used.

Can CSS be used with other than HTML documents?

Yes. CSS can be used with any structured document format. e.g. XML, however, the method of linking CSS with other document types has not been decided yet.

CSS Box Model

The CSS Box Model

All HTML elements can be considered as boxes. In CSS, the term “box model” is used when talking about design and layout.
The CSS box model is essentially a box that wraps around HTML elements, and it consists of: margins, borders, padding, and the actual content.
The box model allows us to place a border around elements and space elements in relation to other elements.
The image below illustrates the box model:
Explanation of the different parts:

  • Margin– Clears an area around the border. The margin does not have a background color, it is completely transparent
  • Border– A border that goes around the padding and content. The border is affected by the background color of the box
  • Padding– Clears an area around the content. The padding is affected by the background color of the box
  • Content– The content of the box, where text and images appear

In order to set the width and height of an element correctly in all browsers, you need to know how the box model works.

How to Override Inline CSS with External CSS

we CAN override inline styles directly from the stylesheet.

Example:

<div style=”background: red;”>

The inline styles for this div should make it red.

</div>

div[style] {

background: yellow !important;

}

How to display one Image on Another?

<style >
.imgA1 { position:absolute; top: 25px; left: 25px; z-index: 1; }
.imgB1 { position:absolute; top: 40px; left: 40px; z-index: 3; }
</style>

<img src=”http://t3.gstatic.com/images?q=tbn:ANd9GcT8yv4Qjw7wRZDOXU50eBWbUooauqYthOfLsf-ZSh2gYdsE8fDF1A”&gt;
<img src=”http://t3.gstatic.com/images?q=tbn:ANd9GcR5FsMdkqaqwXM0cTHDc63tOzpoUW8oH9wBE6PvcWIaRWxS_fZW”&gt;

Difference between DIV and SPAN Tags

DIV Tag Characteristics:

  1. As the name indicates, the div tag defines a ‘division’ in a web page.
  2. div is a block-element; its default display value is “block”.
  3. div tag is commonly used while creating Css based layouts in html.
  4. by default, a line-break is placed before and after this element.

SPAN Tag  Characteristics:

  1. span tag makes no visual difference in the page, unless customised with style attribute.
  2. span is an in-line element.
  3. span is commonly used to stylize texts. The in-line feature makes it easy to use custom styles without changing the layout.
  4. No line-breaks by default, but this can be achieved if we change its in-line nature by specifying in the style attribute to ‘display:block;’

How do u place two div elements side by side

Using float:left Style Attribute we can place two Divs Side by Side

Difference between visibility :hidden and display:none?

The display: none and visibility: hidden CSS properties appear to be the same thing, but they aren’t.

Answer: These two style properties do two different things.

visibility: hidden hides the element, but it still takes up space in the layout.
display: none removes the element completely from the document. It does not take up any space, even though the HTML for it is still in the source code.

You can see the effect of these style properties on this page. I created three identical swatches of code, and then set the display and visibility properties on two so you can see how they look.

CSS Positioning

The CSS positioning properties allow you to position an element. It can also place an element behind another, and specify what should happen when an element’s content is too big.

Elements can be positioned using the top, bottom, left, and right properties. However, these properties will not work unless the position property is set first. They also work differently depending on the positioning method.

There are four different positioning methods.

Static: 

HTML elements are positioned static by default. A static positioned element is always positioned according to the normal flow of the page.
Static positioned elements are not affected by the top, bottom, left, and right properties.

Fixed:

An element with fixed position is positioned relative to the browser window.
It will not move even if the window is scrolled.
Fixed positioned elements can overlap other elements.

Relative:
A relative positioned element is positioned relative to its normal position.
The content of relatively positioned elements can be moved and overlap other elements, but the reserved space for the element is still preserved in the normal flow.
Relatively positioned elements are often used as container blocks for absolutely positioned elements.

Absolute:
An absolute position element is positioned relative to the first parent element that has a position other than static.
If no such element is found, the containing block is <html>:
Absolutely positioned elements can overlap other elements.

CSS Image Sprites

  1. CSS image sprite is a collection of images put into a single image.
  2. A web page with many images can take a long time to load and generates multiple server requests.
  3. Using image sprites will reduce the number of server requests and save bandwidth.

Combining two / more images into a Single image and using CSS Background Positioning to display the specific portion of an image is called CSS Sprites.

Ex:

  1. I have an image called “image_navsprites.gif” which is having 3 images inside.
  2. To display a specific position of image, we have to write code like below

img.home
{
width:46px;
height:44px;
background:url(img_navsprites.gif) 0 0;
}

Example explained:

  • <img class=”home” src=”img_trans.gif” /> – Only defines a small transparent image because the src attribute cannot be empty. The displayed image will be the background image we specify in CSS
  • width:46px;height:44px; – Defines the portion of the image we want to use
  • background:url(img_navsprites.gif) 0 0; – Defines the background image and its position (left 0px, top 0px)

Partitioning a Div into Blocks

Partitioning a Div into Blocks

To Achieve Above Output, the Code is as Follows:

<html>
<style>
.mainDiv {
width:100%;
}
.div1, .div2,.div3, .div6, .div7, .div8 {
float:left;
width:33%;
}
.div4, .div5 {
float:left;
width:49%;
}
.div3, .div5, .div8 {
text-align:right;
}
.div2, .div7 {
text-align:center;
}
.div5 {
padding-left:12px;
}
div {
border: 1px #FF0000 solid;
}

</style>
<body>
<div class=”mainDiv”>
<div class=”div1″><img src=”https://encrypted-tbn2.google.com/images?q=tbn:ANd9GcQ7NXuIsddGM-EigZXUmKzIIZ8kC9IZ5TPTteKTVPMkiZpvqLHd”></div&gt;
<div class=”div2″><img src=”https://encrypted-tbn2.google.com/images?q=tbn:ANd9GcQ7NXuIsddGM-EigZXUmKzIIZ8kC9IZ5TPTteKTVPMkiZpvqLHd”></div&gt;
<div class=”div3″><img src=”https://encrypted-tbn2.google.com/images?q=tbn:ANd9GcQ7NXuIsddGM-EigZXUmKzIIZ8kC9IZ5TPTteKTVPMkiZpvqLHd”></div&gt;
<div class=”div4″><img src=”https://encrypted-tbn2.google.com/images?q=tbn:ANd9GcQ7NXuIsddGM-EigZXUmKzIIZ8kC9IZ5TPTteKTVPMkiZpvqLHd”></div&gt;
<div class=”div5″><img src=”https://encrypted-tbn2.google.com/images?q=tbn:ANd9GcQ7NXuIsddGM-EigZXUmKzIIZ8kC9IZ5TPTteKTVPMkiZpvqLHd”></div&gt;
<div class=”div6″><img src=”https://encrypted-tbn2.google.com/images?q=tbn:ANd9GcQ7NXuIsddGM-EigZXUmKzIIZ8kC9IZ5TPTteKTVPMkiZpvqLHd”></div&gt;
<div class=”div7″><img src=”https://encrypted-tbn2.google.com/images?q=tbn:ANd9GcQ7NXuIsddGM-EigZXUmKzIIZ8kC9IZ5TPTteKTVPMkiZpvqLHd”></div&gt;
<div class=”div8″><img src=”https://encrypted-tbn2.google.com/images?q=tbn:ANd9GcQ7NXuIsddGM-EigZXUmKzIIZ8kC9IZ5TPTteKTVPMkiZpvqLHd”></div&gt;
</div>
</body>

</html>

CSS Font Declaration

CSS Font Declaration
CSS font properties define the font family, boldness, size, and the style of a text.

The font shorthand property sets all the font properties in one declaration.
The properties that can be set, are (in order):
“font-style
font-variant
font-weight
font-size/line-height
font-family”

The font-size and font-family values are required. If one of the other values are missing, the default values will be inserted, if any.

Ex: font:italic bold 12px/30px Georgia, serif;

Refer: http://www.w3schools.com/cssref/pr_font_font.asp

Difference between Margin and Padding

Padding is the space inside the border between the border and the actual image or cell contents.
Margins are the spaces outside the border, between the border and the other elements next to this object.

Shortcode / Shorttags in CSS

CSS Short Code

If we are too boring to code long attribute here we can cut down your coding time

General CSS Code :

div {
font-size: 28px;
font-weight: bold;
font-family: “Arial”, Helvetica, sans-serif;
color: #f4f4f4;
line-height: 24px;
}

Short Code:
p {
font: 900 160%/240% “Arial”, Helvetica, sans-serif;
color: #f4f4f4;
}

What’s that code?

The order of the attributes are font: weight size/line-height family;
400 = normal and 900 for bold;

Few Example Shotcodes:

  1. font
  2. padding
  3. margin
  4. background
  5. list-style
  6. border

Refer: http://www.cssnewbie.com/css-shorthand/

Ajax

How many types of ready states in ajax?

0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready

Different response types in ajax?

JSON
HTML
XML
Text
CSV
YAML

What is the Maximum Execution time of Ajax Request?

120 Seconds

Difference between asychronus and activex control

IE supports activex control

Remaining all browsers support Asychronus data transfer

What is Ajax

AJAX = Asynchronous JavaScript and XML.
AJAX is a technique for creating fast and dynamic web pages.
AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.
Classic web pages, (which do not use AJAX) must reload the entire page if the content should change.
Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs.

How AJAX Works

AJAX is Based on Internet Standards

AJAX is based on internet standards, and uses a combination of:

  • XMLHttpRequest object (to exchange data asynchronously with a server)
  • JavaScript/DOM (to display/interact with the information)
  • CSS (to style the data)
  • XML (often used as the format for transferring data)

AJAX applications are browser- and platform-independent!

Is DOJO a part of AJAX What is AJAX and WHAT is DOJO

AJAX is Asyncrynous JavaScript and XML toghather they make it possible to make a JavaScript function call to your server and get the response. They use XMLHttpRequest and XMLHttpResponse opbeject.

Dojo is an open source JavaScript library which provides you lots of custom components like calendar datagrid scroller etc it provides some datastructure mode like arraylist and collection and it also provides some advance API’s like API to make AJAX calls.

What API function provides the connection between the client and server?

XMLHttpRequest

Should I use an HTTP GET or POST for my AJAX calls?

AJAX requests should use an HTTP GET request when retrieving data where the data will not change for a given request URL. An HTTP POST should be used when state is updated on the server. This is in line with HTTP idem potency recommendations and is highly recommended for a consistent web application architecture.

Othersites

For UI perspective nothing more they ask but you should have to prepare :

HTML :- cross browser issues, box model, HTML div and other element

CSS:- CSS hacks, CSS tweaks

PHP: oops concepts

mysql: query

How will you get student name and total marks of a first rank student?

id name

1 sdsd

2 dddd

3 ffff

studeid m1 m2 m3

1       10 1111

SELECT s.name, (

m.m1 + m.m2 + m.m3 + m.m4

) AS total

FROM student s

LEFT JOIN marks m ON s.id = m.stdid

ORDER BY total DESC

LIMIT 0 , 1

one employee can take interview to any number of candidates.How will you get count of candidates an employee taken interview?

Here is the answer for 56

SELECT name, count( i.candidate ) as total

FROM employee e

JOIN interview i ON e.id = i.empid

GROUP BY i.empid

1.what is ajax?

2.different states in ajax?

3.different response types in ajax?

4.what is json?

5.how to parse json response data?

6.how do u place two div elements side by side?

7.how do u place two images one on another?

8.stored procedures?

9.diff b/w echo and print?

10.”sk.aariz@gmail.com” how to get the string b/w two dots(.) using php string functions?

11.what is shift operator?

12.what is array_shift?

13 .what is array_unshift?

14.array_combine().

$array1 = (a=>abc,a=>bc,a=>ac,a=>abcd);

$array2 = (azaad,aariz);

what ia the o/p of array_combine()?

15.how to override inline css with external css?

16.how will you validate input data in javascript and in php?(cross site scripting)

17.echo print(‘hello’); what is the o/p?

18.CSS sprite technique?

19.document types in html?

20.Difference between HTML and DHTML?

21.How willa create the following layout using div’s?

22.what is the difference between padding and margin?

23.I have two iframes in a page how can I pass variables of one frame to another using javascript?

24.Explain singleton pattern?

25.What is Encapsulation?How will you achieve that in PHP?

26 What is load balencing? How will you do it?

27.How will you pass sessions from one server to another?

28.What is opcode & opcode cache?

29.How will you fix cross browser issues for CSS and JAVASCRIPT?

30.Is there any place in your project where the application is running slow?How will you fix that?

31.What is CSS sprite technique?

32.AJAX states?

33.In which variable you will get the response states?

34.What are environment variables.

35.Difference between PHP4 and PHP5?

36.How will you improve the page performence in front-end(front-end caching)?

37.Diff between a div teg and a span tag?

38.Explain CSS box model?

39.What is cascading?

40.Separating a number from a string using javascript?

41.CSS hacks?

42.What are access specifiers in PHP?

43.Diffenrece between Abstract class and Interface?

44.What are the different mysql Engines?

45.What is a persistance cookie?

46.What is static keyword?

47.Different query optimization techniques?

48.Inheritance in Javascript?

49.Difference between visibility :hidden and display:none?

50.XHTML Rules?

51.How will you optimize php applications?

52.What are the properties of CSS “position” ?

53.Different types of joins in mysql?

54.How will you find whether your browser supports cookies using javascript?

55.

Jquery

Use jQuery.getScript to load external js files

jQuery provides a function called “getScript“, which allows to load external Javascript or js file on the fly. The advantage of using $.getScript is that it loads the content on run time, which is far better than including <script> tag in your head section. jQuery getScript load a JavaScript file from the server using a GET HTTP request, then execute it. The syntax of $.getScript is,

//Code Starts
$.getScript(‘url’, callback function(){
 //call the function here….
});
//Code Ends
  • url : A string containing the URL to which the request is sent. It will be URL of your js file.
  • callback function : A callback function that is executed if the request succeeds.

For example,

//Code Starts
$.getScript(‘js/jsPlugin.js’,function(){
   Demo(); //This function is placed in jsPlugin.js
});
//Code Ends

This is a shorthand Ajax function, which is equivalent to

//Code Starts
$.ajax({
  url: url,
  dataType: “script”,
  success: success
});
//Code Ends

But do you know what happens internally? When loading external js file using .getScript method, what it does it that it appends a timestamp with every request. So the request may look like,
<script src=”/js/jsPlugin.js?_=ts2499874935″>
instead of,
<script src=”/js/jsPlugin.js”>
So what it does by appending timestamp is, it tells the browser to get a fresh copy of js file every time. In other words, it disables the cache or it doesn’t allow browser to cache the js file. Which can be great sometimes but not always.

What if you want to cache the script, so that it doesn’t download every time from the server.

Well, there are 2 ways. First is, before making call to $.getScript method, you can set the cache true for ajax request and set it to false once script is loaded.

$.ajaxSetup({ cache: true });
$.getScript(urlhere, function(){
  //call the function here….
  //Set cache to false.
  $.ajaxSetup({ cache: false });
});
//Code Ends

Second solution is to modify the default implementation of $.getScript to allow cache. The default implementation of $.getScript is,

//Code Starts
$.getScript = function(url, callback){
  $.ajax({
    type: “GET”,
    url: url,
    success: callback,
    dataType: “script”
  });
};
//Code Ends

All you need to do is to add a boolean parameter, which will set the cache attribute to true or false. That’s the beauty of jQuery that you can redefine things the way you need.

//Code Starts
$.getScript = function(url, callback, cache){
  $.ajax({
    type: “GET”,
    url: url,
    success: callback,
    dataType: “script”,
    cache: cache
  });
};
//Code Ends

So,now you call the $.getScript like, (notice the 3rd argument)

//Code Starts
$.getScript(‘js/jsPlugin.js’,function(){
   Demo(); //This function is placed in jsPlugin.js
}, true);
//Code Ends

Don’t worry, it will not break your existing code as if jQuery doesn’t find the 3rd parameter then it will assign undefined or no to this attribute.

Read and Process XML using jQuery Ajax

While working on my current project, for one of my requirement I need to read and process theXML file using jQuery and Ajax. The actual XML file was very huge and I can’t share. So in this post, I will show you how to process XML file with jQuery and Ajax.

Below is the sample XML file that we will be using for the demo.The XML file is having list of books with Title and Publisher as 2 XML node with every book.

//Code Starts
<?xml version=”1.0″ encoding=”utf-8″ ?>
<BookList>
  <Book>
     <Title>jQuery: Novice to Ninja</Title>
     <Publisher>Site point</Publisher>
  </Book>
  <Book>
     <Title>Learning jQuery</Title>
     <Publisher>PACKT</Publisher>
  </Book>
  <Book>
     <Title>Head First jQuery</Title>
     <Publisher>O’Reilly</Publisher>
  </Book>
  <Book>
     <Title>jQuery UI 1.8</Title>
     <Publisher>PACKT</Publisher>
  </Book>
</BookList>
//Code Ends

Now, to process the XML using jQuery, below is the idea to how to do it..

  • Declare a div which will be used to show the XML content.
  • As the display will be in the list so append the UL to the div element.
  • Call the ajax method to process the xml file.
  • Set HTTP request type to “GET” and also provide the name of XML file in url.
  • Set the datatype to “xml“.
  • We also need to define a callback functions, which gets called when request is successful or if some error occurred.
  • So when success callback is called then loop through the xml content.
  • Get the node value for “Title” and “Publisher” and append it to the div.
  • Define error callback to handle the error.

So here is the complete jQuery code.

//Code Starts
$(document).ready(function(){
  $(“#dvContent”).append(“<ul></ul>”);
  $.ajax({
    type: “GET”,
    url: “BookList.xml”,
    dataType: “xml”,
    success: function(xml){
    $(xml).find(‘Book’).each(function(){
      var sTitle = $(this).find(‘Title’).text();
      var sPublisher = $(this).find(‘Publisher’).text();
      $(“<li></li>”).html(sTitle + “, ” + sPublisher).appendTo(“#dvContent ul”);
    });
  },
  error: function() {
    alert(“An error occurred while processing XML file.”);
  }
  });
});
//Code Ends

And below is the output:

Get JSON with jQuery using Ajax

JSON (JavaScript Object Notation) is an data exchange format and which is human-readable data. JSON has became very popular since that web pages have became interactive using AJAX. JSON format is easy to create from the server and easy to parse at client. In this post I will show you how to get JSON file from different server/ same server using jquery and Ajax and display it on webpage.

jQuery provides a method called “getJSON” to load JSON-encoded data from the server using a GET HTTP request.

jQuery.getJSON( url [, data] [, success(data, textStatus, jqXHR)] )

url: A string containing the URL to which the request is sent.
data: A map or string that is sent to the server with the request.
success(data, textStatus, jqXHR): A callback function that is executed if the request succeeds.

The “getJSON” method is shorthand Ajax function. To show you how getJSON method works, we will be using Flickr public gallery images. Flickr provides JSON format file for its public gallery images. You can select photos with particular tag from http://www.flickr.com/photos/tags/.

$(document).ready(function() {
    $.getJSON(“http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?“, {
        tags: “sunset”,
        tagmode: “any”,
        format: “json”
    }, function(data) {
        $.each(data.items, function(i, item) {
            var img = $(“<img>”);
            img.attr(‘width’, ‘200px’);
            img.attr(‘height’, ‘150px’);
            img.attr(“src”, item.media.m).appendTo(“#dvImages”);
            if (i == 3) return false;
        });
    });
});​

As you can see from above code, using getJSON method load the JSON file and once it is loaded, now loop through the file and show the images on the page. For demo purpose, I am showing only 4 images.

How to Read and Parse JSON using jQuery

In this short post, you will find how you to parse the JSON string using jQueryJSON(JavaScript Object Notation) is an data exchange format and which is human-readable data.jQuery provides a metohd called “parseJSON” which takes a well-formed JSON string and returns the resulting JavaScript object.

Some facts about JSON

  • JSON is limited to text and numeric values.
  • It doesn’t support binary data.
  • An JSON object is a set of key / name pairs which starts with “{” and ends with “}”.

Below is sample jQuery code which parses JSON string using parseJSON method which returns an object.

//Code Starts
$(document).ready(function() {
    var jsonp = ‘[{“Language”:”jQuery”,”ID”:”1″},{“Language”:”C#”,”ID”:”2″}]’;
    var lang = ”;
    var obj = $.parseJSON(jsonp);
    $.each(obj, function() {
        lang += this[‘Language’] + “
“;
    });
    $(‘span’).html(lang);
});​
//Code Ends

How to move items between ListBox using jQuery

In this post, I will show you how you can easily move items from one listbox to another listbox using jQuery. The beauty of this code is that you can also move multiple items together.
As you can see from above image that there should be 2 button to move items from one list to another. So code will be identical for both the buttons, only the listbox’s id gets changed.

1. First get the list box selected options.

//Code Starts
var selectedOpts = $(‘#lstBox1 option:selected’);
//Code Ends
  1. It is quite possible that nothing is selected and button is clicked. So it is important to check if anything is selected or not. If not then alert the user.
//Code Starts
if (selectedOpts.length == 0) {
   alert(“Nothing to move.”);
   e.preventDefault();
}
//Code Ends
  1. Now if something is selected then add the selected options to other list and also remove it from the selected list box.
//Code Starts
$(‘#lstBox2’).append($(selectedOpts).clone());
$(selectedOpts).remove();
e.preventDefault();
//Code Ends

So complete jQuery code for both the buttons is,

//Code Starts
$(document).ready(function() {
    $(‘#btnRight’).click(function(e) {
        var selectedOpts = $(‘#lstBox1 option:selected’);
        if (selectedOpts.length == 0) {
            alert(“Nothing to move.”);
            e.preventDefault();
        }
        $(‘#lstBox2’).append($(selectedOpts).clone());
        $(selectedOpts).remove();
        e.preventDefault();
    });
    $(‘#btnLeft’).click(function(e) {
        var selectedOpts = $(‘#lstBox2 option:selected’);
        if (selectedOpts.length == 0) {
            alert(“Nothing to move.”);
            e.preventDefault();
        }
        $(‘#lstBox1’).append($(selectedOpts).clone());
        $(selectedOpts).remove();
        e.preventDefault();
    });
});​
//Code Ends

How to clear textbox value using jQuery

In this short post, I will show you simple jQuery code to clear textbox value. The reason for writing this post is because I have seen many beginner programmers using val() == ”, which is wrong asval() is a method that takes argument. It is not a property or attribute. You can call this code on click of button or any other event.

Clear all textbox

$(document).ready(function() {
    $(‘input[type=text]’).each(function() {
        $(this).val(”);
    });
});​

Clear single textbox value

$(document).ready(function() {
   $(‘#txtID’).val(”); //txtID is textbox ID
});​

Clear textbox value onfocus

$(document).ready(function() {
    $(‘#txtID’).focus(function() {
        $(this).val(”);
    });
});​

Associate focus event with every textbox

$(document).ready(function() {
    $(‘input[type=text]’).focus(function() {
        $(this).val(”);
    });
});​

JQuery selectors code snippets demo

Selector is the most basic things in jQuery. Their use is very simple and straight and correct use of selectors can enhance the efficiency of writing jQuery code. I have put together some of the common selectors which are pretty common.

ID Selector

$(document).ready(function () {
  $(‘#dvDummy’).css(‘background’, ‘#000000’);
});

Class Selector

$(document).ready(function () {
   $(‘.class1’).css(‘background’, ‘#000000’);
});

Element Selector

$(document).ready(function () {
   $(‘p’).css(‘font-size’, ’14px’);
});

Selector (loop through all elements)

$(document).ready(function () {
   $(‘form *’).css(‘color’, ‘#FFFF00’);
});

Select Multiple Elements

$(document).ready(function () {
   $(‘p, div’).css(‘margin’, ‘0’);
});

The parent > child (immediate child element)

$(document).ready(function () {
   $(‘div > span’).css(‘color’, ‘#FF0000’);
});

:first and :last (take the first element or the last element)

1 $(document).ready(function () {
2    $(‘span:first’).css(‘color’, ‘#FFFF00’);
3    $(‘span:last’).css(‘color’, ‘#FFFF00’);
4 });

:even and :odd (Select elements with an even index or odd index elements. The index starts from 0.)

$(document).ready(function () {
   $(‘tr:even’).css(‘color’, ‘#00FF00’);
   $(‘tr:odd’).css(‘color’, ‘#0000FF’);
});

:eq(x) (Selects element with the specified index)

$(document).ready(function () {
  $(‘tr:eq(2)’).css(‘background’, ‘#FFFF00’);
});

:contains(text) (Select element which contains specified text)

$(document).ready(function () {
  $(‘div:contains(“jQuery”)’).css(‘color’, ‘#FFFF00’);
});

:hidden (Selects hidden elements)

$(document).ready(function() {
  $(‘div:hidden’).show(500);
});

:visible (Selects visible elements)

$(document).ready(function() {
  $(‘div:visible’).css(‘color’, ‘#FFFF00’);
});

What is Chaining in jQuery?

You may have come across a term “Chaining” in jQuery. But do you know what is Chaining in jQuery? There is no specific definition available for this term in jQuery but it is also not different from the general meaning of Chain. In general term Chain is, “A connected flexible series of metal links used for fastening or securing objects and pulling or supporting loads.” Below images dictates what is chaining. Isn’t it?
Okay..As far as jQuery is concerned then undoubtedly Chaining is one of the most powerful feature of jQuery. Even in jQuery, Chaining means to connect multiple functions, events on selectors. To understand it better take a look at Sample Code 1 and 2.

Sample Code 1

​$(document).ready(function(){
    $(‘#dvContent’).addClass(‘dummy’);
    $(‘#dvContent’).css(‘color’, ‘red’);
    $(‘#dvContent’).fadeIn(‘slow’);
});​

Sample Code 2

​$(document).ready(function(){
    $(‘#dvContent’).addClass(‘dummy’)
          .css(‘color’, ‘red’)
          .fadeIn(‘slow’);
});​

Both the sample codes above will perform the exact same thing but the only difference is that Sample code 2 is using Chaining. But Code 2 is faster and shorter then Code 1. But you must be thinking that why do I say so?

The problem with the Sample Code 1 is that for every statement, jQuery has to search the entire DOM and find the element and after that executes the attached function on it. But when chaining is used, then jQuery has to find the element only once and it will execute all the attached functions one by one. This is the advantage of Chaining.

Important points about Chaining

  • It makes your code short and easy to manage.
  • It gives better performance.
  • The chain starts from left to right. So left most will be called first and so on.

Not only functions or methods, chaining also works with events in jQuery. For example, below piece of code have click, mouseover and mouseout event for a button.

​$(document).ready(function() {
    $(“#btnDummy”).click(function(e) {
        alert(“click!”);
    }).mouseover(function(e) {
        alert(“mouse over!”)
    }).mouseout(function(e) {
        alert(“mouse out!”)
    });
});​

How to Zoom an image using jQuery

You must had seen the zoom in and zoom out functionality for images on many sites. We can very easily achieve the Zoom In and Zoom Out functionality using jQuery toggle method. It is really simple. Let me first tell you the logic behind the implementation. Initially when document is ready then we will set the width of the image and after that on click of the image we will change the width of the image with some animation (Zoom In) and reset the width on alternate click (Zoom Out). Let’s directly go to the point.

Place an image on the page.

<h1>Click image to Zoom In and Zoom Out</h1>
<img src=”Images/smile.png” alt=”Smile” id=”imgSmile” />

Now jQuery code.

$(document).ready(function(){
$(‘#imgSmile’).width(200);
$(‘#imgSmile’).mouseover(function()
{
$(this).css(“cursor”,”pointer”);
});
$(“#imgSmile”).toggle(function()
{$(this).animate({width: “500px”}, ‘slow’);},
function()
{$(this).animate({width: “200px”}, ‘slow’);
});
});

Let’s understand the code.
Initially we have set the image width to 200px and on mouseover event, mouse cursor is changed to pointer. So it gives an impression that image is clickable.

As in the above code, toggle method is used. toggle method binds two or more handlers to the element, which will be executed on click. If two handlers are specified then on first click first handler will be called and on second click second handler will be called. Toggle method internally makes a call to click event only.

So in our code, when first time is click width is increased to 500 px and on second click width is reset to 200 px. Animate function is also used to show zooming effect in animated manner. To use animate, we need to pass CSS properties to be set and the timespan. Timespan value can be in milliseconds or one of the string values from ‘slow’, ‘normal’ or ‘fast’.

Check if radio button is checked or selected using jQuery

Yesterday I need to find out if radio button is checked/selected or not using jQuery. I was knowing one way to find out but there are couple of other ways as well to find out if radio button is checked using jQuery. In this post, you will find all different possible ways.

1. First Way:

Below single line of code will provide the status of radio button using jQuery. It checks whether the checked property is checked or not using jQuery and will return true or false. Below code will work with jQuery 1.7.2 version.

var isChecked = $(‘#rdSelect’).prop(‘checked’);

If you are using older version of jQuery (before 1.7.2) then you can use below code.

var isChecked = $(‘#rdSelect’).attr(‘checked’)?true:false;

I have noticed that on many website it is written that ‘checked’ attribute will return true or false if used with ‘attr’ method, but this is not correct. If the checked box is checked then it return status as “checked”, otherwise “undefined”.

So if you want to have true or false, then you need to use conditional expression as I have done in the code.

  1. Second Way
var isChecked = $(‘#rdSelect:checked’).val()?true:false;

$(‘#rdSelect:checked’).val() method returns “on” when radio button is checked and “undefined”, when radio button is unchecked.

  1. Third Way
var isChecked = $(‘#rdSelect’).is(‘:checked’);

The above method uses “is” selector and it returns true and false based on radio button status.

  1. Fourth Way

The below code is to find out all the radio button checked through out the page.

$(“input[type=radio][checked]”).each(
    function() {
       // Your code goes here…
    }
);

Feel free to contact me for any help related to jQuery, I will gladly help

Check if Checkbox is checked using jQuery

Yesterday I need to find out if checkbox is checked or not using jQuery. I was knowing one way to find out but there are couple of other ways as well to find out if checkbox is checked using jQuery. In this post, you will find all different possible ways.

1. First Way:

Below single line of code will provide the status of checkbox using jQuery. It checks whether the checked is checked or not using jQuery and will return 1 or 0.

var isChecked = $(‘#chkSelect’).attr(‘checked’)?true:false;

I have noticed that on many website it is written that ‘checked’ attribute will return true or false, but this is not correct. If the checked box is checked then it return status as “checked”, otherwise “undefined”.

So if you want to have true or false, then you need to use conditional expression as I have done in the code.

2. Second Way

var isChecked = $(‘#chkSelect:checked’).val()?true:false;

$(‘#chkSelect:checked’).val() method returns “on” when checkbox is checked and “undefined”, when checkbox is unchecked.

3. Third Way

var isChecked = $(‘#chkSelect’).is(‘:checked’);

The above method uses “is” selector and it returns true and false based on checkbox status.

4. Fourth Way
The below code is to find out all the checkbox checked through out the page.

$(“input[type=’checkbox’]:checked”).each(
    function() {
       // Your code goes here…
    }
);

Feel free to contact me for any help related to jQuery, I will gladly help you.

How to create, read and delete cookies using jQuery

We all know that Cookies are delicious and also comes in many flavors. But Do you know thatcookies can be used to store small piece of information on client machine and that is with jQueryflavor. In this post, you will see how to create, read and delete cookies using jQuery.

jQuery cookie plugin is popular plugin, which is used to accomplish cookies tasks but one of the problem with this plugin is that it doesn’t support JSON cookies. So what is the solution?

Dough is an easy to use cookie plugin for jQuery with powerful features. Dough can auto set your domain name with ‘.’ prefix so your cookies work with subdomains and will allow you to easily go from local to staging to product servers with out a problem.

Create Cookie

//Code Starts
$.dough(“cookieName”, “cookieValue”);
//Code Ends

Read Cookie

//Code Starts
$.dough(“cookieName”);
//Code Ends

Delete Cookie

//Code Starts
$.dough(“cookieName”, “remove”);
//Code Ends

Available Options

This plugin also comes with options to play with.

  • expires: Days ’til cookie expires
  • path: Default is root ‘/’, set to ‘current’ to use the path of current page
  • domain: Auto detect and set domain with subdomain prefix
  • secure: Set to true if you’re using https://

Set full cookie

//Code Starts
$.dough(“cookieName”, “cookieValue”,
   { expires: 365,
     path: “current”,
     domain: “auto”,
     secure: true
  });
//Code Ends

Example cookie has a name of “cookieName”, a value of “cookieValue”, will expire in 1 year, have path of current page, domain will be autodetected and is set to secure for a use under https://.

The beauty of this plugin it also supports JSON cookies. So using this plugin, you can create JSON cookies.
Create JSON cookie

//Code Starts
$.dough(“jsonCookie”, “{‘someName’:’someValue’,’someOtherName’:’someOtherValue’}”);
//Code Ends

Read JSON cookie

//Code Starts
$.dough(“jsonCookie”).someName;
//Code Ends

Jquery Delegate vs Bind

With jQuery 1.4.2 launch, a new method called “delegate()” was introduced. This method attaches a handler to one or more events for selected/specified elements. Let’s take an example. I have created a table and using delegate method, I will attach the click event handler to every td element.
<table border=”1″ width=”200px” cellspacing=”5″ cellpadding=”5″>
<tr>
<td>Item 1</td>
<td>Item 2</td>
</tr>
<tr>
<td>Item 3</td>
<td>Item 4</td>
</tr>
</table>

jQuery delegate() method code.
<script src=”Scripts/jquery-1.4.2.min.js” type=”text/javascript”></script>

<script src=”Scripts/jquery-1.4.2.min.js” type=”text/javascript”></script>
<script type=”text/javascript” language=”javascript”>
$(document).ready(function(){
$(“table”).delegate(“td”,”click”,function(){
alert(‘I am’ + $(this).text());
});
});
</script>

It takes 3 arguments.

  1. Selector
  2. Event Type
  3. Event Handler

See live Demo and Code.

You will say that this is very much possible with the bind() method. Below code will serve the purpose.

$(document).ready(function(){

$(“table td”).bind(“click”,function(){

alert(‘I am’ + $(this).text());

});

});

Then what’s new with delegate() method?

bind() vs delegate()

bind() method will add event to element which are on the page when it was called. For example, there are only 4 td on the page when bind() was  called. Later on, when you dynamically add more td in the table then bind() will not attach click event handler to those td. Let’s extend our demo and place a button on the page which will add the td dynamically.

$(“#btnAdd”).click(function(){

$(“table”).append(“<tr><td>Item 5</td><td>Item 6</td></tr>”);

});

Now, when you run this page, you will not find click event for newly added td.

See live Demo and Code.

But with delegate(), you will find click event for newly added td.

delegate() method adds event which are on the page and also listens for

new element and add event to them.

See live Demo and Code.

Jquery Access nth Level Child

$(‘#start > * > * > *’).prepend(‘*’);

How to find nth row of table using jQuery?

$(document).ready(function(){
$(“table tr:eq(3)).css(“background”,”#000″);
}) ;

$(‘li:nth-child(1)’) selects the first
while $(‘li:eq(1)’) selects the second.

Because jQuery’s implementation of :nth-child(n) is strictly derived from the CSS specification, the value of n is “1-indexed”, meaning that the counting starts at 1. For all other selector expressions, however, jQuery follows JavaScript’s “0-indexed” counting.

How do I determine the state of a toggled element?

Here is the example of toggled element using the :visible or :hidden selectors.

var vis = $(’#formdiv’).is(’:visible’);
var hide= $(’#formdiv’).is(’:hidden’);

change the URL for a Hyperlink using jQuery?

There are three way to change the URL for a Hyperlink using jQuery.

1- $(“a”).attr(“href”, “http://www.phpinterviewquestion.com/”);

2- $(“a[href=’http://www.phpinterviewquestion.com/’%5D“)
.attr(‘href’, ‘http://phpinterviewquestion.com/’);

3- $(“a[href^=’http://phpinterviewquestion.com’%5D“).each(function() {

this.href = this.href.replace(/^http:\/\/beta\.phpinterviewquestion\.com/,
“http://phpinterviewquestion.com”);

How we can apply css in multiple Selectors in jquery.

$(”div,span,p.myClass”).css(”border”,”1px solid green”);

the border will be apply in all div,span ,p.myClass class element.

How can we apply css in odd/even/last childs of parent node using JQuery library.

$(”tr:odd”).css(”background-color”, “#bbbbff”);

$(”tr:even”).css(”background-color”, “#bbbbff”);

$(”tr:last”).css({backgroundColor: ‘yellow’, fontWeight: ‘bolder’});

Why is jQuery better than javascript?

  • jQuery is great library for developing ajax based application.
  • It helps the programmers to keep code simple and concise and reusable.
  • jQuery library simplifies the process of traversal of HTML DOM tree.
  • jQuery can also handle events, perform animation, and add the ajax support in web applications.

Features of jQuery?

Features of jQuery are :

* Effects and animations
* Ajax
* Extensibility
* DOM element selections functions
* Events
* CSS manipulation
* Utilities – such as browser version and the each function.
* JavaScript Plugins
* DOM traversal and modification.

Advantages of jQuery?

The advantages of using jQuery are:

* JavaScript enhancement without the overhead of learning new syntax
* Ability to keep the code simple, clear, readable and reusable
* Eradication of the requirement of writing repetitious and complex loops and DOM scripting library calls

What does dollar Sign ($) means in JQuery?

Dollar Sign is nothing but it’s an alias for JQuery. Take a look at below jQuery code

$(document).ready(function(){

});

Over here $ sign can be replaced with “jQuery ” keyword.

jQuery(document).ready(function(){

});

What is Jquery?

JQuery is Java Script library or Java Script Framework which helps in how to traverse HTML documents, do some cool animations, and add Ajax interaction to any web page. It mainly helps programmer to reduce lines of code as huge code written in Java Script, can be done easily with JQuery in few lines

How can you select all elements in a page using jQuery?

To select all elements in a page, we can use all selectors, for that we need to use *(asterisk symbol).

<script language=”javascript” >
$(“*”).css(“border”, “2px dotted red”);
</script>

Posted by Chait

What is the difference between jQuery-x.x.x.js and jQuery.x.x.x-min.js

In terms of functionality, there is no difference between the jQuery-x.x.x.js and jQuery-x.x.x-min.js (also called minified version). However this can play a vital role in the performance of the web page.

How it affects the performance? 
jQuery-1.4.4.js file size is 178 KB as against its minified version jQuery-1.4.4-min.js that is only 76.7 KB in size. So when your page loads in the client?s browser if you are not using minified version, it loads 178 KB file that takes more time to load than 76.7 KB.

How to do Cross Domain Ajax Calls using JQuery?

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01//EN” “http://www.w3.org/TR/html4/strict.dtd”&gt;
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title>Cross-Domain Ajax & JQuery</title>
<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js”></script&gt;
    <script language=”JavaScript”>
        $(document).ready(function() {
              $.getJSON(‘http://twitter.com/users/usejquery.json?callback=?&#8217;, function(json) { //get information about the user usejquery from twitter api
                $(‘#twitter_followers’).text(json.followers_count); //get the follower_count from the json object and put it in a span
              });
          });
    </script>
</head>
 <body>
      Twitter Followers: <span id=”twitter_followers”>Loading…</span>
  </body>
</html>

jQuery parent() vs. parents()

Given the following HTML:

<html>…<body><div ”one”><div ”two”><p><span>Some text</span></p></div></div></body></html>

$(‘span’).parent() will select the <p> tag such that the element set in the jQuery object is [span].

$(‘span’).parents() will select all parent tags such that the element set in the jQuery object is [p, div.two, div.one, body, html].

So parent() will select the first parent element while parents() will select all elements straight up the DOM tree.

Now jQuery has some great flexibility in that you could do that following:

$(‘span’).parents().filter(‘div’) which would result in [div.two, div.one]. jQuery makes it even easier as the parent() and parents() methods support filtering built in so the above can be reduced to:

$(‘span’).parents(‘div’) giving you [div.two, div.one].

Let’s continue with one more example, let’s say that you only need the first div in the parent DOM tree, jQuery to the rescue $(‘span’).parents(‘div:eq(0)’) will give you [div.two]

htaccess

htaccess rewrite url syntax

RewriteEngine on
RewriteBase /
RewriteRule ^newsroom/events/(.*) /index.php?mod=events&pid=$1

Redirection

One of the most useful functions of the .htaccess file is to redirect requests to different files, either on the same server, or on a completely different web site. It can be extremely useful if you change the name of one of your files but allow users to still find it. Another use (which I find very useful) is to redirect to a longer URL, for example in my newsletters I can use a very short URL for my affiliate links. The following can be done to redirect a specific file:

Redirect /location/from/root/file.ext http://www.othersite.com/new/file/location.xyz

In this above example, a file in the root directory called oldfile.html would be entered as:

/oldfile.html

and a file in the old subdirectory would be entered as:

/old/oldfile.html

You can also redirect whole directoires of your site using the .htaccess file, for example if you had a directory called olddirectory on your site and you had set up the same files on a new site at: http://www.newsite.com/newdirectory/ you could redirect all the files in that directory without having to specify each one:

Redirect /olddirectory http://www.newsite.com/newdirectory

Then, any request to your site below /olddirectory will bee redirected to the new site, with the
extra information in the URL added on, for example if someone typed in:

http://www.youroldsite.com/olddirecotry/oldfiles/images/image.gif

They would be redirected to:

http://www.newsite.com/newdirectory/oldfiles/images/image.gif

This can prove to be extremely powerful if used correctly.

Alternative Index Files

You may not always want to use index.htm or index.html as your index file for a directory, for example if you are using PHP files in your site, you may want index.php to be the index file for a directory. You are not limited to ‘index’ files though. Using .htaccess you can set foofoo.blah to be your index file if you want to!

Alternate index files are entered in a list. The server will work from left to right, checking to see if each file exists, if none of them exisit it will display a directory listing (unless, of course, you have turned this off).

DirectoryIndex index.php index.php3 messagebrd.pl index.html index.htm

Deny/Allow Certian IP Addresses

In some situations, you may want to only allow people with specific IP addresses to access your site or you may want to ban certian IP addresses this will only work if you know the IP addresses you want to ban and, as most people on the internet now have a dynamic IP address, so this is not always the best way to limit usage.

You can block an IP address by using:

deny from 000.000.000.000 

You can allow an IP address by using:

allow from 000.000.000.000 

If you want to deny everyone from accessing a directory, you can use:

deny from all

but this will still allow scripts to use the files in the directory

Stop A Directory Index From Being Shown

if someone types the directory name into their browser, a full listing of all the files in that directory will be shown. This could be a security risk for your site.

To prevent against this (without creating lots of new ‘index’ files, you can enter a command into your .htaccess file to stop the directory list from being shown:

Options -Indexes

Posted by Chaitanya Laksh

Custom Error Pages

These will allow you to have your own, personal error pages (for example when a file is not found) instead of using your host’s error pages or having no page.

You can use custom error pages for any error as long as you know its number (like 404 for page not found) by adding the following to your .htaccess file:

ErrorDocument errornumber /file.html

These are some of the most common errors:

401 – Authorization Required
400 – Bad request
403 – Forbidden
500 – Internal Server Error
404 – Wrong page

how can I protect my folders and file using htaccess file?

The password protection depends on two files. The first one is the .htaccess file. It tells the webserver that viewing the file and/or folder requires authorization. The second file is the .htpasswd file it stores information about the users and their passwords. Its content will look similar to the following line:

webuser:qkbPmuht5Gzgc

The first part is the username, the second part of the line after the colon symbol is the password. The password is encrypted either using a modified version of MD5 or the system crypt() function.

Creation of the .htpasswd file is usually handled by the Apache htpasswd command line utility.
In case you do not have access to it on your server, you can use the following form to generate your .htpasswd file.

It is recommended that the .htpasswd file is located in a folder that is not accessible through the web. However most servers retrict acces to these files in their setup.

Once you have the .htpasswd file ready you need to create a file named .htaccess and place it in the folder you wish to have protected. The file should have the following lines

AuthType Basic
AuthUserFile “/home/username/path_to_htpasswd/.htpasswd”
AuthName “Enter valid username and password!”
require valid-user

The line AuthUserFile tells the web server where to look for the file containing the usernames which are allowed to access the folder.

The AuthName is what is printed in the user/prompt of the visitor’s browser.

Protecting a single file is a little tricky, you will need to add some more lines to the .htaccess file. Let’s say you wish to protect a file named “my-secret-file.html”. Then you will need to following .htaccess:

AuthType Basic
AuthUserFile “/home/username/path_to_htpasswd/.htpasswd”
AuthName “Enter valid username and password!”

require valid-user

The .htaccess file should be located in the same folder where the my-secret-file.html is located.

How to disable directory browsing using .htaccess – Apache Web Server

Disable directory browsing using .htaccess:-

* Open your .htacces file
* Look for Options Indexes
* If Options Indexes exists modify it to Options -Indexes or else add Options -Indexes as a new line
* The directory browsing feature should be disable by now

Disable directory browsing using httpd.conf:-

* Open your httpd.conf, normally it’s located at /usr/local/apache/conf or /etc/httpd.conf
* Go to your own Virtual Host settings and look for “Options Indexes”
* Change the Indexes to -Indexes if Option Indexes exists or else add the Options -Indexes line
* Restart your apache web server.
* The directory browsing feature should be disable by now

Disable directory browsing in CPanel Share Hosting enviroment:-

* Login to your CPanel
* Click on Index Manager
* Directory will be list down. Click on the directory name which you want to disable the directory browsing
* Select No Index and click Save
* The directory browsing feature should be disable by now

What is htaccess?

.htaccess files (or “distributed configuration files”) provide a way to make configuration changes on a per-directory basis.
In several web servers (most commonly Apache), .htaccess (hypertext access) is the default name of a directory-level configuration file that allows for decentralized management of web server configuration. The .htaccess file is placed inside the web tree, and is able to override a subset of the server’s global configuration; the extent of this subset is defined by the web server administrator.[1] The original purpose of .htaccess was to allow per-directory access control (e.g. requiring a password to access the content), hence the name. Nowadays .htaccess can override many other configuration settings, mostly related to content control, e.g. content type and character set, CGI handlers, etc.

Using this “.htaccess” file we can control “php.ini” and “httpd.conf” file.

How to upload 100mb file using .htaccess..

you have to overwrite php.ini’s s settings in .htacess

upload_max_filesize 100M

php_value post_max_size 100M

How to upload 100mb file using .htaccess..

you have to overwrite php.ini’s s settings in .htacess

upload_max_filesize 100M

php_value post_max_size 100M
php_value upload_max_filesize 100M

Why are we using the htaccess file?

htaccess file is quite useful for the following reasons:

1. If you’re reorganising your site and moving pages around,you can use the .htaccess file to redirect visitors from the old page to the new one.

2. Another function of the .htaccess file is to allow you to serve up pages which include PHP or Server Side Includes (SSI) but whose file name still uses the .htm or .html extension.

3. Allow or prevent directory browsing.

4. Because the server should check the .htaccess file before anything is delivered to the client, you can use it to password protect parts of your site.

5. You can also block various bots with the .htaccess file — for example, you can keep some spammers out, or prevent search engine spiders from indexing your images folder.

Leave a comment