Monday 4 March 2013

Magic Contant,Methods and Quotes

What is Magic Constant?
PHP provides a large number of predefined constants to any script which it runs.There are seven magical constants that change depending on where they are used. For example, the value of __LINE__ depends on the line that it's used on in your script. These special constants are case-insensitive and are as follows:

Name
Description
__LINE__
The current line number of the file.
__FILE__
The full path and filename of the file. If used inside an include, the name of the included file is returned. Since PHP 4.0.2, __FILE__ always contains an absolute path with symlinks resolved whereas in older versions it contained relative path under some circumstances.
__DIR__
The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__). This directory name does not have a trailing slash unless it is the root directory. (Added in PHP 5.3.0.)
__FUNCTION__
The function name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the function name as it was declared (case-sensitive). In PHP 4 its value is always lowercased.
__CLASS__
The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the class name as it was declared (case-sensitive). In PHP 4 its value is always lowercased.
__METHOD__
The class method name. (Added in PHP 5.0.0) The method name is returned as it was declared (case-sensitive).
__NAMESPACE__
The name of the current namespace (case-sensitive). This constant is defined in compile-time (Added in PHP 5.3.0).


What is Magic Methods?
The function names __construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state() and __clone() are magical in PHP classes. You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them.


What is Magic Quotes?
 This feature has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.

When ON, all ' (single-quote), " (double quote), \ (backslash) and NULL characters are escaped with a backslash automatically. This is identical to what addslashes() does.

There are three magic quote directives:

magic_quotes_gpc Affects HTTP Request data (GET, POST, and COOKIE). Cannot be set at runtime, and defaults to on in PHP. See also get_magic_quotes_gpc().

magic_quotes_runtime If enabled, most functions that return data from an external source, including databases and text files, will have quotes escaped with a backslash. Can be set at runtime, and defaults to off in PHP. See also set_magic_quotes_runtime() and get_magic_quotes_runtime().

magic_quotes_sybase If enabled, a single-quote is escaped with a single-quote instead of a backslash. If on, it completely overrides magic_quotes_gpc. Having both directives enabled means only single quotes are escaped as ''. Double quotes, backslashes and NULL's will remain untouched and unescaped. See also ini_get() for retrieving its value.


What is register global?

This feature has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.
A common security problem with PHP is the register_globals setting in PHP's configuration file (php.ini). This setting (which can be either On or Off) tells whether or not to register the contents of the EGPCS (Environment, GET, POST, Cookie, Server) variables as global variables. For example, if register_globals is on, the url http://www.example.com/test.php?id=3will declare $id as a global variable with no code required. Similarly, $DOCUMENT_ROOT would also be defined, since it is part of the $_SERVER 'superglobal' array. These two examples are the equivalent of placing the following code at the beginning of a script:
$id = $_GET['id'];
$DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT'];
This feature is a great security risk, and you should ensure that register_globals is Off for all scripts (as of PHP 4.2.0 this is the default). It's preferred to go through PHP Predefined Variables instead, such as the superglobal $_REQUEST. Even more secure is to further specify by using: $_ENV, $_GET, $_POST, $_COOKIE, or $_SERVER instead of using the more general superglobal $_REQUEST.




How can we parse URL?
mixed = parse_url ( string $url [, int $component = -1 ] )
$url = The URL to parse. Invalid characters are replaced by _.
$component = Specify one of PHP_URL_SCHEME, PHP_URL_HOST, PHP_URL_PORT, PHP_URL_USER, PHP_URL_PASS, PHP_URL_PATH, PHP_URL_QUERY or PHP_URL_FRAGMENT to retrieve just a specific URL component as a string .


<?php
$url 
'http://username:password@hostname/path?arg=value#anchor';

print_r(parse_url($url));

echo 
parse_url($urlPHP_URL_PATH);
?>
Array
(
    [scheme] => http
    [host] => hostname
    [user] => username
    [pass] => password
    [path] => /path
    [query] => arg=value
    [fragment] => anchor
)

Htaccess and Modrewrite



# How to change extension through htaccess?
RewriteRule ^viewnews/([0-9]+)/(.*)$ viewnews.php?news_id=$1 [L]
RewriteRule ^gallery/(.+)/(.+)/([0-9]+)$ gallery.php?cat_id=$1&page=$2&list=$3 [L]


# URL are case sensitive?
In Windows, links will get to your pages regardless of capitalization (or lack of it). So if the search engine indexed your page when it was www.example.com/page01.htm, it will still find it even if you renamed it www.example.com/PAGE01.htm (but read on, as there ARE ways that capitalization might effect you). In a Linux or Unix-based environment, things are a little different. The good news is that the base URL (www.example.com) will resolve correctly regardless of capitalization. The (potentially) bad news is that the other pages will not. So if your site is hosted in a Linux/Unix environment and you rename your page www.example.com/PopularPage.htm to www.example.com/popularpage.htm. 


            
Advantage/ Uses of htaccess?
1)   Authorization, authentication: .htaccess files are often used to specify the security restrictions for the particular directory, hence the filename "access". The .htaccess file is often accompanied by an .htpasswd file which stores valid usernames and their passwords.
  
2)   Customized error responses: Changing the page that is shown when a server-side error occurs, for example HTTP 404 Not Found.
Example : ErrorDocument 404 /notfound.html

3) Rewriting URLs: Servers often use .htaccess to rewrite "ugly" URLs to shorter and prettier ones.

4)   Cache Control: .htaccess files allow a server to control User agent caching used by web browsers to reduce bandwidth usage, server load, and perceived lag.
  

# RewriteRule And RewriteCond
The order of rules in the ruleset is important because the rewrite engine processes them in a particular order, as follows:
The rewrite engine loops through the rulesets (each ruleset being made up of RewriteRule directives, with or without RewriteConds), rule by rule. When a particular rule is matched, mod_rewrite also checks the corresponding conditions (RewriteCond directives). For historical reasons the conditions are given first, making the control flow a little bit long-winded.

First the URL is matched against the Pattern of a rule. If it does not match, mod_rewrite immediately stops processing that rule, and goes on to the next rule. If the Pattern matches, mod_rewrite checks for rule conditions. If none are present, the URL will be replaced with a new string, constructed from the Substitution string, and mod_rewrite goes on to the next rule.


RewriteRule: Defines rules for the rewriting engine.
RewriteCond: Defines a condition under which rewriting will take place.
The RewriteCond directive defines a rule condition. One or more RewriteCond can precede a RewriteRule directive.

Example:
To rewrite the Homepage of a site according to the "User-Agent" header of the request, you can use the following:
 
RewriteCond  %{HTTP_USER_AGENT}  ^Mozilla
RewriteRule  ^/$                 /homepage.max.html  [L]
RewriteCond  %{HTTP_USER_AGENT}  ^Lynx
RewriteRule  ^/$                 /homepage.min.html  [L]
RewriteRule  ^/$                 /homepage.std.html  [L]

Tuesday 17 January 2012

PHP-Mysql Interview Questions

Some PHP interview question i am sharing with you, which are really interesting and upgraded my knowledge. It might help you out...:)

1) Maximum length of HTTP GET request?
    - Browser support minimum of 2KB to maximum of 8 KB like MSIE and Safari about 2KB, in Opera about 4KB and in Firefox about 8KB.


2) How to jump to a particular record set after fetching all the records form table?
      bool mysql_data_seek ( resource $result , int $row_number );


3) How to store the session into the database
PHP provides session_set_save_handler() function that allows you override the default session mechanism. And it takes six arguments, each of which is a name of function.
session_set_save_handler() sets the user-level session storage functions which are used for storing and retrieving data associated with a session. This is most useful when a storage method other than those supplied by PHP sessions is preferred. i.e. Storing the session data in a local database.
Parameters: Open, Close, Read, Write, Destroy, GC (garbage collector)


4) In-built Exceptions functions available to use in PHP?
Following are the in-built functions available with Exception handling in PHP:
getMessage();          // message of exception
getCode();              // code of exception
getFile();                 // source filename
getLine();                // source line
getTrace();              // an array of the backtrace()
getPrevious();          // previous exception
getTraceAsString();  // formatted string of trace


5) Maximum values that can the store with SET Data type of mysql?
  Mysql set can take zero or more values but at the maximum it can take 64 values


6) How do you find out what is the next auto increment id?
SHOW TABLE STATUS FROM DBName


7) What is the difference between SET and ENUM?
    A SET is a string object that can have zero or more values.
    A SET can have a maximum of 64 different members.
    An enumeration can have a maximum of 65,535 elements.
    If you set a SET column to an unsupported value, the value is ignored.
    If you insert an invalid value into an ENUM (that is, a string not present in the list of allowed values), the empty string is inserted instead as a special error value.
    If an ENUM column is declared to allow NULL, the NULL value is a legal value for the column, and the default value is NULL. If an ENUM column is declared NOT NULL, its default value is the first element of the list of allowed values.
Values from the list of allowable elements in the column specification are numbered beginning with
    The index of the NULL value is NULL
    The index value of the empty string error value is 0. This means that you can use the following     SELECT statement to find rows into which invalid ENUM values were assigned:
    mysql> SELECT * FROM tbl_name WHERE enum_col=0;


8) Is there a query that will Prefix a 0 to a x amount of times? 
Example: In my table i have column with 4 Digit number as 1234, now client want it to make six digit number (001234) without changing the numeric value, so is there any query that will update my table values to six digit number without affecting the values.
  INT(6) UNSIGNED ZEROFIL
OR 
  update tableName set FieldName = LPAD(FieldName,6,'0');