Showing posts with label PHP Interviews Questions. Show all posts
Showing posts with label PHP Interviews Questions. Show all posts

Friday 9 January 2015

How to stop parsing the HTML tags?

How to stop parsing the HTML tags?

There are couples Method to avoid the parsing of HTML tags, I used following two ways.


How to use XMP Tag for avoid HTML parsing, See Example
Method No 1

<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjOZoBT5-0tL8iOdoHHiqqLgQxwtOtbtLHJp2MaanGJK2BhQOSjIh1FyTgN9uYuCam5kOfUN3NixaLcT7sf46MKGEn7p1PKXJpKG79jMtCZHH4xroHX9AzlQqC97Jbu54Q8pN_H4DLHE9jL/s1600/wordpress.jpg" />

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>



How to use script Tag for avoid HTML parsing, See Example
Method No 2

<script type="text/plain">
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjOZoBT5-0tL8iOdoHHiqqLgQxwtOtbtLHJp2MaanGJK2BhQOSjIh1FyTgN9uYuCam5kOfUN3NixaLcT7sf46MKGEn7p1PKXJpKG79jMtCZHH4xroHX9AzlQqC97Jbu54Q8pN_H4DLHE9jL/s1600/wordpress.jpg" />
<meta content='jX6W4C5R1HdrWqp91JMBxHzxqBM' name='alexaVerifyID'/>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js' type='text/javascript'></script>



Monday 5 January 2015

Difference between Notice and warning and fatal error

Difference between Notice and warning and fatal error


Notice
  • A notice is an advisory message like "You probably shouldn't be doing what you're doing"
  • Execution of the script is not halted
  • Example
    echo $undefinedVariable;



Warning
  • A warning is a message like "You are doing something wrong and it is very likely to cause errors in the future, so please fix it." Execution of the script is not halted;
  • Example
    echo 1/0;



Fatal Error
  • Fatal run-time errors
  • Execution of the script is not halted
  • Example  
    require_once "notexistfile.php"

Sunday 14 December 2014

Object Oriented Programming in PHP

Object Oriented Programming in PHP

Following concept are used in Object Oriented Programming in PHP.

  1. Introduction
  2. The Basics
  3. Properties
  4. Class Constants
  5. Autoloading Classes
  6. Constructors and Destructors
  7. Visibility
  8. Object Inheritance
  9. Scope Resolution Operator (::)
  10. Static Keyword
  11. Class Abstraction
  12. Object Interfaces
  13. Traits
  14. Overloading
  15. Object Iteration
  16. Magic Methods
  17. Final Keyword
  18. Object Cloning
  19. Comparing Objects
  20. Type Hinting
  21. Late Static Bindings
  22. Objects and references
  23. Object Serialization
  24. OOP Changelog


Wednesday 10 December 2014

Htaccess RewriteRule Flags by Code Example

Htaccess RewriteRule Flags by Code Example

A RewriteRule can be modified by flag. Flags are included in square brackets at the end of the rule. We can also and multiple flags are separated by commas.

For Example:
[Flag1] //for 1 flag
[Flag1,Flag2] //for 2 flags
[Flag1,Flag2,Flag3 ] //for multiple flags

Following are most commonly htaccess flag:
1. htacces B(escape backreferences) Flag
Escape non-alphanumeric characters before applying the transformation


2. htaccess C(Chain) Flag
First htaccess Rule will be applied to next htaccess rule. Means if the rule matches, then control moves on to the next rule.


3. htaccess CO(Cookie) Flag
you can set a cookie when a particular RewriteRule matches
RewriteRule ^search/(.*)$ /search.php?term=$1[CO=variable:variableValue]
Set the variable=variableValue in cookie


4. htaccess DPI(discardpath) Flag
PATH_INFO portion of the rewritten URI to be discarded.


5. htaccess E (env) Flag
You can set the value of an environment variable. For example:
RewriteRule ^search/(.*)$ /search.php?term=$1[E=variable:variableValue]
Set the variable=variableValue in environment variable.


6. htaccess END Flag
This flag terminates not only the current round of rewrite but also prevents any subsequent rewrite from occurring in per-directory.


7. htaccess F(forbidden) Flag
This flag causes the server to return a 403 Forbidden status code to the client. For Example
RewriteRule \.exe - [F]
If anyone trying to open any file with .exe, he will get Forbidden error.



8. htaccess G(gone) Flag
This flag causes the server to return a 410 Gone status with the response code to the client. For Example
RewriteRule old_url - [G]
If old_url called, 410 gone status will be shown in the browser.



9. htaccess H(handler) Flag
This flag causes Forces the request to be handled with the specified handler. For example
RewriteRule !\. - [H=application/x-httpd-php]
Force all files without a file extension to be parsed by the php handler.



10. htaccess L(Last) Flag
This flag causes to stop processing the rule set, if the rule matches, no further rules will be processed.
RewriteRule ^(.*) /index.php?req=$1 [L]



11. htaccess N(Next) Flag
This flag causes ruleset to start over again from the top.
RewriteRule ^(.*) /index.php?req=$1 [N]


12. htaccess NC(nocase) Flag
This flag causes RewriteRule to be matched in a case-insensitive manner.
RewriteRule ^(.*) /index.php?req=$1 [NC]



13. htaccess NE(noescape) Flag
By default, special characters, such as & and ?, are converted to their hexcode equivalent. By Using NE flag prevents we can prevent this.


14. htaccess NS(nosubreq) Flag
This flag causes prevents the rule from being used on subrequests.



15. htaccess P(proxy) Flag
This flag causes the request to be handled by proxy request. For example, if you wanted all image requests to be handled by a image server
RewriteRule /(.*)\.(jpg|gif|png)$ http://images.mysite.com/$1.$2 [P]
Extension having jpg, gif, and png will be handled by images.mysite.com



16. htaccess PT(passthrough) Flag
This flag causes the result of the RewriteRule to be passed back through URL mapping.



17. htaccess QSA(qsappend) Flag
When the replacement URI contains a query string, the default behavior of RewriteRule is to discard the existing query string, and replace it with the newly generated one. Using the [QSA] flag causes the query strings to be combined.

18. htaccess S(Skip) flag
htaccess S flag is used to skip rules that you don't want to run. The syntax of the skip flag is [S=N], where N means the number of rules to skip. For Example
# Does the file exist?
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Create an if-then-else construct by skipping 3 lines if we meant to go to the "else" stanza.
RewriteRule .? - [S=3]

# IF the file exists, then:
    RewriteRule (.*\.gif) images.php?$1
    RewriteRule (.*\.html) docs.php?$1
    # Skip past the "else" stanza.
    RewriteRule .? - [S=1]
# ELSE...
    RewriteRule (.*) 404.php?file=$1
# END


19. htaccess T(type) flag
htaccess T flag cause sets the MIME type with which the resulting response will be sent. For Example
RewriteRule IMG - [T=image/jpg]


20. htaccess R(Redirect) flag
htacces R flag causes a HTTP redirect to be issued to the browser. Normally Redirect does not occur but if we use R Flag, then redirection will be happened to the browser. For Example
RewriteRule (.*\.gif) images.php?$1 [R]

Friday 7 November 2014

Enabling the openssl in Wamp-Xampp

Enabling the openssl in Wamp-Xampp

If you have any of following issue, then you are on right page.

  • How to enable SSL
  • Enabling the openssl in WampServer/xampp
  • How to enable openssl support in XAMPP
  • Unable to Connect to ssl
  • Fatal error: Uncaught exception Zend_Http_Client_Adapter_Exception


Solution: enable the extension php_openssl from PHP Extension

Option 1 (If using Wamp-Server)

Enabling the openssl in Wamp










and Restart your wamp Server


Option 2 (Direct change in php.ini File)
You can do direct change
Just comment your php_openssl.dll in your php.ini file.
Search
;extension=php_openssl.dll
Replace with
extension=php_openssl.dll
Here we have just removed the semicolon.



Tuesday 23 September 2014

Zend Cache Tutorial - Zend Framework 1.12

Zend Cache Tutorial - Zend Framework 1.12

Zend_Cache provides a flexible approach toward caching data, including support for tagging, manipulating, iterating, and removing data.

Question: What is Zend Cache?
It is Inbuilt component of zend framework which is used to speed up the application by using the caching concept.


Question: Why we use Zend Cache?
We use Zend cache for different purpose are following
  • Increase the website Performance.
  • Reduce the load on database.
  • Reduce the load of api, if using in application.
  • To get the result faster.


What is the use of  Zend Cache?
We can speedup our application as well as can reduce the burdon on database and API.
Zend_Cache use the file system to store the cache. We have option in zend cache to use the other caching component like Memcached, Sqlite, ibmemcached,Apc,Xcache and ZendPlatform etc. In this tutorial we will understand the zend_cache with file system.


How to Setup Zend Cache?
Step1: Add Following function Bootstrap
    public function _initCache() {
        $cache = Zend_Cache::factory(
                        'Core', 'File', array(
                    'lifetime' => 3600 * 24 * 7, /*caching time is 7 days*/                            
                    'automatic_serialization' => true
                        ), array('cache_dir' => APPLICATION_PATH . '/cache' /* This is caching folder where caching data will be stored and it must be writable by apache **/
                    )
        );
       
        Zend_Registry::set('Cache', $cache); /* set the cache object in zend_registery so that you can globally access*/
    }
Step2: cache folder must be writeable by PHP
Step3: Now, Just use the zend cache
        /* get the cache object */
        $cache = Zend_Registry::get('Cache');
        /* create a unique cache key */
        $cacheKey = "mydata";
        $result = array();
        if (empty($cacheKey) || ($result = $cache->load($cacheKey)) == false) {
            /*
            Here Process the and store the data in $result variable
            */            
            $cache->save($result, $cacheKey);
        }





What is Tagging in Zend Cache?
Tags are a way to categorize cache records. You can add two OR more type of records in single tag. You can create unlimited tags and also can add unlimited records in single tag.


How to used Tagging in Zend Cache.
        /* get the cache object */
        $cache = Zend_Registry::get('Cache');
        /* create a unique cache key */
        $cacheKey = "mydata";
        $result = array();
        if (empty($cacheKey) || ($result = $cache->load($cacheKey)) == false) {
            /*
            Here Process the and store the data in $result variable
            */            
            $cache->save($result, $cacheKey , array('Tags'));
        }


Can we add multiple Tags for 1 Record?
Yes, We can do.
$cache->save($result, $cacheKey , array('Tag1','Tag2','Tag3')); 


How can we clean one cache?
$cache->remove('idToRemove');


How to clean all records?
$cache->clean(Zend_Cache::CLEANING_MODE_ALL);


How to clean outdated records?
$cache->clean(Zend_Cache::CLEANING_MODE_OLD);


How to clean all records of one/more tags?
$cache->clean(
    Zend_Cache::CLEANING_MODE_MATCHING_TAG,
    array('Tag1', 'Tag2')
);

Thursday 24 July 2014

Important PHP Interview Questions and Answers - jQuery, SQL Modes, Client Programs and Reset

How to get jQuery nth Element
//include jQuery file
<script type="text/javascript" src="jquery.js"></script>
<script>
function go_to(id_number){     
     var obj=jQuery('div.mydiv ul li:nth-child('+id_number+') a');      
     alert(obj.html()) 
}
go_to(3);
</script>

jQuery Multiple File Upload Plugin
http://www.fyneworks.com/jquery/multiple-file-upload/#tab-Overview


jQuery Paging
Here you can table Sorting, Searching and Paging in Easy Way
http://www.datatables.net/examples/


Paypal return error : malformed

Hi,
I am using payapl gateway for payment in my project.
It is working fine for sandbox(test account) but no working for paypal (original paypal detail on client server);
It return following errror from paypal
  Array
    (
        [Error] => Array
            (
                [Number] =>  malformed
            )

    )



Solution: When you are sending amount in api call, sent amount with 2 digit decimal places. For Example 100.02 OR 22.32 


How to Download Openinviter?
You want to implement openInviter and your project is in Wordpress, Joomla, Drupal, Social engine, phpBB, Dolphin, Symfony & webmail. then Its maximum 2-5 min work. Just download the plugin/component & install in your application it will start working.


If your project is in some other CMS or Core PHP, then you need to download the files.
Include the file & call the appropriate function. It will start working...
http://openinviter.com/download.php


What is PHP?
PHP is language that enable web-developer to create the dynamic web pages with the use of HTML/CSS/JavaScript.


What is Full Form of PHP?
Full Form of PHP is Personal Home Page but now it stand for PHP: Hypertext Preprocessor


Who is Father of PHP?
Rasmus Lerdorf


When php was invented?
PHP was created by Rasmus Lerdorf in 1995


What is Rest
REpresentational Sate Transfer.
It is set of architectural rules by which you design a web service that focus on transfer of data from one server to another ignorance of operating system and language.
It was introduced in 2000.


What is Invoking Client Programs?
MySQL client programs can be invoked from the command line. For example from a Windows console prompt OR a Unix shell prompt.
For Example
shell> mysql -h localhost -p -u myname


What are Server SQL modes?
It define what SQL syntax, MySQL should support and what kind of data validation checks it should perform.
It easier to use MySQL in different environments.


How many server SQL modes?
The MySQL server can operate in different SQL modes, and can apply these modes differently for different clients.


Thanks for reading our page
http://www.web-technology-experts-notes.in/2014/07/important-php-interview-questions-and-Answers.html

Thursday 5 June 2014

PHP DataStructures

Data structure is a way of storing and organizing data in a computer so that it can be used efficiently. It provide a efficient way to manage large amounts of data efficiently, such as large databases and Internet indexing services.


SPL provides a following set of standard datastructures.
SplDoublyLinkedList: The SplDoublyLinkedList class provides the main functionalities of a doubly linked list.

SplStack
The SplStack class provides the main functionalities of a stack implemented using a doubly linked list.

SplQueue
The SplQueue class provides the main functionalities of a queue implemented using a doubly linked list.
See Example
echo "Create Object of SplQueue:";
$obj = new SplQueue();

echo "
Check for Queue, is it Empty:";
if($obj->isEmpty())
{
    $obj->enqueue("Simple");
    $obj->enqueue("Example");
    $obj->enqueue("Of");
    $obj->enqueue("PHP");
}
echo "
View queue:";
print_r($obj);
if(! $obj->offsetExists(4))
{
    $obj->enqueue(10);
}
print_r($obj);
echo "
"; echo " Get the value of the offset at 3 "; if($obj->offsetGet(3)) { echo $obj->offsetGet(3); echo " Resetting the value of a node:"; $obj->offsetSet(4,6); }
SplHeap The SplHeap class provides the main functionalities of a Heap. Heaps are crucial in several efficient graph algorithms such as Dijkstra's algorithm, and in the sorting algorithm heapsort.

SplMaxHeap The SplMaxHeap class provides the main functionalities of a heap, keeping the maximum on the top.

SplMinHeap The SplMinHeap class provides the main functionalities of a heap, keeping the minimum on the top.


SplPriorityQueue The SplPriorityQueue class provides the main functionalists of an functionalists of an prioritized queue, implemented using a max heap.

SplFixedArray The SplFixedArray class provides the main functionalities of array. The main differences between a SplFixedArray and a normal PHP array is that the SplFixedArray is of fixed length and allows only integers within the range as indexes. The advantage is that it allows a faster array implementation. See Example Below
$array = new SplFixedArray(5);
$array[1] = 2;
$array[4] = "foo";
var_dump($array[0]); // NULL
var_dump($array[1]); // int(2)

var_dump($array["5"]); // Fatal error: Uncaught exception 'RuntimeException' with message 'Index invalid or out of range'

SplObjectStorage The SplObjectStorage class provides a map from objects to data or, by ignoring data, an object set. This dual purpose can be useful in many cases involving the need to uniquely identify objects. 

Monday 19 May 2014

PHP Check Mime Type of File - Return Information About A File

PHP Check Mime Type of File - Return Information About A File

Now a days, we are uploading files like Profile images, Video files OR excel files in our web application. 
With uploading these files there are chances some user upload the .exe file (Virus) by renaming the .exe into .jpg, which can damage website.

You might have added the extension check from javaScript as well as PHP. But this is not enough from security end because someone can upload the file after changing the extension of file( ".exe" to ".png"). In this case your security check will be failed.

What to do.
Answer is  check the Mime of file before get uploaded in your web server.

How to do this
"fileinfo" is extension which must be enabled in your php.ini. (for existence you can check  in phpinfo)
If this extension is not enabled ask your server admin, he will do this for you OR you can also do this your self (http://php.net/manual/en/fileinfo.installation.php).


After installing the fileinfo extension, use following code to get the mime type of file before get uploaded in web server.
if (function_exists("finfo_file")) {
    $finfo = finfo_open(FILEINFO_MIME_TYPE);    

    //file which you want to check the mime of the file
    $file = $_SERVER['DOCUMENT_ROOT'] . '/images/feedback.png';    //file which is going to get uploaded in web server
    try {
        $type = finfo_file($finfo,$file);        
        echo "File Type: ".$type;
    } catch (Exception $e) {
        echo $e->getMessage();
    }
} else {
    echo "'finfo_file' is Not installed";
}


When you execute above code, if will get the mime-type of file. This is directly checking the mime type of already uploaded file.
You can use $type = finfo_file($finfo,$file); for checking the file type, before using move_uploaded_file function.

Wednesday 5 March 2014

Zend Database Query - Zend Profiler Example - Code Snippets

Zend Profiler: It is used to display the queries executed by zend indirectly with MySql. It will show all the queries like insert, update, delete etc.

Zend Profiler is very important just because it show the queries but It can help you to improve the performance of your website.

See How you can use the Zend Profiler.
  1. With zend profiler you will get to know what type of queries are running in your application and which is making slow your website.
  2. Zend Profiler also also how much time each query is taking to execute.
  3. you can get to know, what are un-necessary queries are running
  4. What queries are running multiple times
  5. For future you can store these queries for further use.


 See below Example, How to use zend Profiler

//create class
class Application_Model_Test extends Zend_Db_Table_Abstract {
    protected $_name = 'tests';
    protected $_primary = 'id';

    //create function
    function insertData($data) {
        /** enable the zend profiler **/
        $this->getAdapter()->getProfiler()->setEnabled(true);
        $profiler = $this->getAdapter()->getProfiler();
        /** enable the zend profiler **/

        //save data
        $this->insert($data);

        /** to list the mysql queries * */
        foreach ($profiler->getQueryProfiles() as $query) {
            $sqlQuery = $query->getQuery();
            $params = $query->getQueryParams();
            echo $sqlQuery = str_replace(array('?'), $params, $sqlQuery);
            echo '';            
        }
        
        /** to list the mysql queries * */
    }
}




5 Best Related Posts are Following:1. Web service - current time zone for a city- Free API
2. Zend Gdata Youtube API - Search Video - View Video Detail
3. Download the video from Amazon Simple Storage Service S3
4. How to set Cron in Zend Framework
5. Zend Cache Tutorial - Zend Framework 1.12