Monday, March 23

Php Objective Questions with Answers for written test exams


1. Which of the following functions allows you to store session data in a database?

A. session_start();

B. session_set_save_handler();

C. mysql_query();

D. You cannot store session data in a database.

   
Answer B is correct.You can use session_set_save_handler() to override

 

    PHP’s default session-handling functions and store session data any way you want.

 

    Answer A is incorrect because session_start() only activates PHP sessions for

 

    the current script. Answer C is incorrect because mysql_query() only executes a

 

    query with MySQL and does not affect the behavior of PHP’s session mechanism.

 

    Answer D is incorrect because this statement is false



2. Which of the following types can be used as an array key? (Select three.)

A. Integer

B. Floating-point

C. Array

D. Object

E. Boolean

   
Answers A, B, and E are correct. A Boolean value will be converted to either 0 if

    it is false or 1 if it is true, whereas a floating-point value will be truncated to its

integer equivalent.Arrays and objects, however, cannot be used under any circumstance.

3. Which of the following functions can be used to sort an array by its keys in

descending order?

A. sort

B. rsort

C. ksort

D. krsort

E. reverse_sort

   
Answer D is correct.The sort() and rsort() functions operate on values, whereas

  

    ksort() sorts in ascending order and reverse_sort() is not a PHP function.

4. What will the following script output?

<?php

$a = array (‘a’ => 20, 1 => 36, 40);

array_rand ($a);

echo $a[0];

?>

A. A random value from $a

B. ‘a’

C. 20

D. 36

E. Nothing

  
   
ANSWER E Only E is correct.The $a array doesn’t have any element with a numeric key of

  

    zero, and the array_rand() function does not change the keys of the array’s elements—

  

    only their order.


5. Given

$email = ‘bob@example.com’;

which code block will output example.com?

A. print substr($email, -1 * strrpos($email, ‘@’));

B. print substr($email, strrpos($email, ‘@’));

C. print substr($email, strpos($email, ‘@’) + 1);

D. print strstr($email, ‘@’);

   
Answer C is correct. strpos() identifies the position of the @ character in the

  

    string.To capture only the domain part of the address, you must advance one place

  

    to the first character after the @.

6. Which question will replace markup such as img=/smiley.png with <img

src=”/smiley.png”>?

A. print preg_replace(‘/img=(\w+)/’, ‘<img src=”\1”>’, $text);

B. print preg_replace(‘/img=(\S+)/’, ‘<img src=”\1”>’, $text);

C. print preg_replace(‘/img=(\s+)/’, ‘<img src=”\1”>’, $text);

D. print preg_replace(‘/img=(\w)+/’, ‘<img src=”\1”>’, $text);


   
Answer B is correct.The characters / and . are not matched by \w (which only

matches alphanumerics and underscores), or by \s (which only matches whitespace).

7. Which of the following functions is most efficient for substituting fixed patterns in
   strings?
       
        A. preg_replace()
       
        B. str_replace()
       
        C. str_ireplace()
       
        D. substr_replace()

       
   
    Answer B is correct.The PHP efficiency mantra is “do no more work than necessary.”
   
    Both str_ireplace() and preg_replace() have more expensive (and flexible)
   
    matching logic, so you should only use them when your problem requires it.
   
    substr_replace() requires you to know the offsets and lengths of the substrings
   
    you want to replace, and is not sufficient to handle the task at hand.
   
8. If

    $time = ‘Monday at 12:33 PM’;
   
    or
   
    $time = ‘Friday the 12th at 2:07 AM’;
   
    which code fragment outputs the hour (12 or 2, respectively)?
   
    A. preg_match(‘/\S(\d+):/’, $time, $matches);
   
    print $matches[1];
   
    B. preg_match(‘/(\w+)\Sat\S(\d+):\d+/’, $time, $matches);
   
    print $matches[2];
   
    C. preg_match(‘/\s([a-zA-Z]+)\s(\w+)\s(\d+):\d+/’, $time,
   
    $matches);
   
    print $matches[3];
   
    D. preg_match(‘/\s(\d+)/’, $time, $matches);
   
    print $matches[1];
   
    E. preg_match(‘/\w+\s(\d+):\d+/’, $time, $matches);
   
    print $matches[1];  

   
    Answer E is correct. Answer A and B both fail because \S matches nonwhitespace
   
    characters, which break the match. Answer C will correctly match the first $time
   
    correctly, but fail on the second because ‘12th’ will not match [a-zA-Z]. Answer D
   
    matches the first, but will fail on the second, capturing the date (12) instead of the
   
    hour.

9. Which of the following output ‘True’?

    A. if(“true”) { print “True”; }
   
    B. $string = “true”;
   
    if($string == 0) { print “True”; }
   
    C. $string = “true”;
   
    if(strncasecmp($string, “Trudeau”, 4)) { print “True”; }
   
    D. if(strpos(“truelove”, “true”)) { print “True”; }
   
    E. if(strstr(“truelove”, “true”)) { print “True”; }

   
    Answers A, B, C, and E are correct. Answer A is correct because a non-empty
   
    string will evaluate to true inside an if() block. Answer B is covered in the chapter—
   
    when comparing a string and an integer with ==, PHP will convert the string
   
    into an integer. ‘true’ converts to 0, as it has no numeric parts. In answer C,
   
    strncasecmp() returns 1 because the first four characters of ‘Trud’ come before
   
    the first four characters of true when sorted not case sensitively. Answer D is
   
    incorrect because strpos() returns 0 here (true matches truelove at offset 0).
   
    We could make this return True by requiring strpos() to be !== false. Answer
   
    E is correct because strstr() will return the entire string, which will evaluate to
   
    true in the if() block.
   
10. What are the contents of output.txt after the following code snippet is run?

    <?php
   
    $str = ‘abcdefghijklmnop’;
   
    $fp = fopen(“output.txt”, ‘w’);
   
    for($i=0; $i< 4; $i++) {
   
    fwrite($fp, $str, $i);
   
    }
   
    ?>
   
    A. abcd
   
    B. aababcabcd
   
    C. aababc
   
    D. aaaa

   
    The correct answer is C. On the first iteration, $i is 0, so no data is written. On
   
    the second iteration $i is 1, so a is written. On the third, ab is written, and on the
   
    fourth abc is written.Taken together, these are aababc.

11. Which of the following can be used to determine if a file is readable?

    A. stat()
    B. is_readable()
    C. filetype()
    D. fileowner()
    E. finfo()

   
    The correct answers are A and B. stat() returns an array of information about a
   
    file, including who owns it and what its permission mode is.Together these are
   
    sufficient to tell if a file is readable. is_readable(), as the name implies, returns
   
    true if a file is readable.
   
12. Specifying the LOCK_NB flag to flock() instructs PHP to

    A. Return immediately if someone else is holding the lock.
    B. Block indefinitely until the lock is available.
    C. Block for a number of seconds dictated by the php.ini setting
       flock.max_wait or until the lock is available.
    D. Immediately take control of the lock from its current holder.

   
    The correct answer is A.The LOCK_NB flag instructs PHP to take a nonblocking
   
    lock, which immediately fails if another process holds the lock.

13. If you have an open file resource, you can read data from it one line at a time with
    the _____ function.

   
       
    The correct answer is fgets().
   
14. Which of the following functions require an open file resource?

    A. fgets()
    B. fopen()
    C. filemtime()
    D. rewind()
    E. reset()

           
    The correct answers are A and D. fgets() and rewind() both act on an open file
   
    resource. fopen() opens files to create resources, whereas filemtime() takes a filename
   
    and reset() acts on arrays.
   
15. Which of the following sentences are incorrect?

    A. date() returns the current UNIX datestamp.
    B. date() returns a formatted date string.
    C. date() requires a time stamp to be passed to it.
    D. date() returns a date array.


    The correct answers are A, C, and D. date() takes a format string and an optional
   
    time stamp and produces a formatted date string. If a UNIX time stamp is not
   
    passed into date(), it will use the current time.
   
16. The ________ function will return the current UNIX time stamp.
   
       
    The correct answer is time().
   
17. Which of the following functions will output the current time as 11:26 pm?

    A. print date(‘H:m a’);
    B. print date(‘G:M a’);
    C. print date(‘G:i a’);
    D. print strftime(‘%I:%M %p’);

   
    The correct answers are C and D.
   
18. Which of the following is not an aggregate function?

    A. AVG
    B. SUM
    C. COUNT
    D. GROUP BY
    E. MIN

       
    The correct answer is D. Group by is a grouping clause, not an aggregate function.
   
19. How is a transaction terminated so that the changes made during its course are discarded?

    A. ROLLBACK TRANSACTION
    B. COMMIT TRANSACTION
    C. By terminating the connection without completing the transaction
    D. UNDO TRANSACTION
    E. DISCARD CHANGES

   
    A and C are both valid answers. A transaction is not completed when the connection

    between your script and the database server is discarded, as if a ROLLBACK
   
    TRANSACTION command has been issued.

Saturday, March 21

File's MIME type to validate using PHP.

<?php
    $valid_mime_types = array(
        "image/gif",
        "image/png",
        "image/jpeg",
        "image/pjpeg",
    );
    
    // Check that the uploaded file is actually an image
    // and move it to the right folder if is.
    if (in_array($_FILES["file"]["type"], $valid_mime_types)) {
        $destination = "uploads/" . $_FILES["file"]["name"];
        move_uploaded_file($_FILES["file"]["tmp_name"], $destination);
    }
?>

Wednesday, March 18

Contact Form using jQuery.



Contact Form – Simple and Easy to Customize Contact Form

Contact Form is a simple and easy to customize contact form. A minimal and customizable snippet to throw a semantic form into your web projects on the fly.

For demo and code visit:

 jquery-plugins.net

Converting Text to Image using php, command script.



This example script will produce a white PNG , with the words "This is a TEXT!!!" in black, in the font Serif.

<?php  
    //Font Family
    $font_family = 'Serif';
  
    //Color of the font
    $color = 'rgb(0,0,0)';
  
    //Size of the font
    $font_size = intval(substr('14px', 0, -2));
  
    //The Text to make image
    $text = 'This is a TEXT!!!';
  
    //Rotate the text in degree
    $arc = 0;
  
    //File path
    $file_path = dirname(__FILE__).'/temp.png';
  
    $command="convert -background none -font '$font_family' -fill '$color' -pointsize $font_size label:' $text ' \
          -virtual-pixel Background  -background none \
          -distort Arc ".$arc."   $file_path";
  
    //To excute commands
    exec($command);

    if (file_exists($filepath)) {
       echo '<img src="'.$save_temp_dir.$filename.'" />';
    } 
?>

Tuesday, March 17

Simple PHP MYSQL Pagination





1. Database Connection:
    Create connection.php file and put that php code (provided below) in it.

<?php
    $db_username = 'root'; // Your MYSQL Username.
    $db_password = ''; // Your MYSQL Password.
    $db_name = 'database_name_here'; // Your Database name.
    $db_host = 'localhost';
     
    $conDB = mysqli_connect($db_host, $db_username, $db_password,$db_name)or die('Error: Could not connect to database.');
?>


2. Pagination function:
    Let’s create pagination function and store it in your functions.php file.
   
<?php
    function pagination($query,$per_page=10,$page=1,$url='?'){ 
        global $conDB;
        $query = "SELECT COUNT(*) as `num` FROM {$query}";
        $row = mysqli_fetch_array(mysqli_query($conDB,$query));
        $total = $row['num'];
        $adjacents = "2";
         
        $prevlabel = "&lsaquo; Prev";
        $nextlabel = "Next &rsaquo;";
        $lastlabel = "Last &rsaquo;&rsaquo;";
         
        $page = ($page == 0 ? 1 : $page);
        $start = ($page - 1) * $per_page;                             
         
        $prev = $page - 1;                        
        $next = $page + 1;
         
        $lastpage = ceil($total/$per_page);
         
        $lpm1 = $lastpage - 1; // //last page minus 1
         
        $pagination = "";
        if($lastpage > 1){ 
            $pagination .= "<ul class='pagination'>";
            $pagination .= "<li class='page_info'>Page {$page} of {$lastpage}</li>";
                 
                if ($page > 1) $pagination.= "<li><a href='{$url}page={$prev}'>{$prevlabel}</a></li>";
                 
            if ($lastpage < 7 + ($adjacents * 2)){ 
                for ($counter = 1; $counter <= $lastpage; $counter++){
                    if ($counter == $page)
                        $pagination.= "<li><a class='current'>{$counter}</a></li>";
                    else
                        $pagination.= "<li><a href='{$url}page={$counter}'>{$counter}</a></li>";                  
                }
             
            } elseif($lastpage > 5 + ($adjacents * 2)){
                 
                if($page < 1 + ($adjacents * 2)) {
                     
                    for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++){
                        if ($counter == $page)
                            $pagination.= "<li><a class='current'>{$counter}</a></li>";
                        else
                            $pagination.= "<li><a href='{$url}page={$counter}'>{$counter}</a></li>";                  
                    }
                    $pagination.= "<li class='dot'>...</li>";
                    $pagination.= "<li><a href='{$url}page={$lpm1}'>{$lpm1}</a></li>";
                    $pagination.= "<li><a href='{$url}page={$lastpage}'>{$lastpage}</a></li>";
                         
                } elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2)) {
                     
                    $pagination.= "<li><a href='{$url}page=1'>1</a></li>";
                    $pagination.= "<li><a href='{$url}page=2'>2</a></li>";
                    $pagination.= "<li class='dot'>...</li>";
                    for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++) {
                        if ($counter == $page)
                            $pagination.= "<li><a class='current'>{$counter}</a></li>";
                        else
                            $pagination.= "<li><a href='{$url}page={$counter}'>{$counter}</a></li>";                  
                    }
                    $pagination.= "<li class='dot'>..</li>";
                    $pagination.= "<li><a href='{$url}page={$lpm1}'>{$lpm1}</a></li>";
                    $pagination.= "<li><a href='{$url}page={$lastpage}'>{$lastpage}</a></li>";    
                     
                } else {
                     
                    $pagination.= "<li><a href='{$url}page=1'>1</a></li>";
                    $pagination.= "<li><a href='{$url}page=2'>2</a></li>";
                    $pagination.= "<li class='dot'>..</li>";
                    for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++) {
                        if ($counter == $page)
                            $pagination.= "<li><a class='current'>{$counter}</a></li>";
                        else
                            $pagination.= "<li><a href='{$url}page={$counter}'>{$counter}</a></li>";                  
                    }
                }
            }
             
                if ($page < $counter - 1) {
                    $pagination.= "<li><a href='{$url}page={$next}'>{$nextlabel}</a></li>";
                    $pagination.= "<li><a href='{$url}page=$lastpage'>{$lastlabel}</a></li>";
                }
             
            $pagination.= "</ul>";      
        }
         
        return $pagination;
    }
?>  


3. Displaying Database Records with pagination:

<?php
    include_once('connection.php');
    include_once('functions.php');
    
    $page = (int)(!isset($_GET["page"]) ? 1 : $_GET["page"]);
    if ($page <= 0) $page = 1;
    
    $per_page = 10; // Set how many records do you want to display per page.
    
    $startpoint = ($page * $per_page) - $per_page;
    
    $statement = "`records` ORDER BY `id` ASC"; // Change `records` according to your table name.
     
    $results = mysqli_query($conDB,"SELECT * FROM {$statement} LIMIT {$startpoint} , {$per_page}");
    
    if (mysqli_num_rows($results) != 0) {
        
        // displaying records.
        while ($row = mysqli_fetch_array($results)) {
            echo $row['name'] . '<br>';
        }
     
    } else {
         echo "No records are found.";
    }
    
     // displaying paginaiton.
    echo pagination($statement,$per_page,$page,$url='?');
?>


4. Simple CSS:
   
<style>
    ul.pagination { text-align:center; color:#829994; }
   
    ul.pagination li { display:inline; padding:0 3px; }
   
    ul.pagination a { color:#0d7963; display:inline-block; padding:5px 10px; border:1px solid #cde0dc; text-decoration:none; }
   
    ul.pagination a:hover,
    ul.pagination a.current { background:#0d7963; color:#fff;     }
</style>


Monday, March 16

Send HTTP POST Data to Remote URL.


    I’d like to share with you a function that I use a lot in my web projects. It’s useful to send data through POST from one location to another. It’s very useful if you need to send information from a server to a remote one. For example, you can use AJAX to call a PHP file from your website that when being accessed, it will send POST data to a Remote URL location and get its output, all of this being processed in the background.

    <?php
    /**
     * SendPostData()
     *
     * @param mixed $_p
     * @param mixed $remote_url
     * @return
     */
    function SendPostData($_p, $remote_url) {
        $remote_url = trim($remote_url);
    
        $is_https = (substr($remote_url, 0, 5) == 'https');
    
        $fields_string = http_build_query($_p);
    
        // Run this code if you have cURL enabled
        if(function_exists('curl_init')) {
            
            // create a new cURL resource
            $ch = curl_init();
            
            // set URL and other appropriate options
            curl_setopt($ch, CURLOPT_URL, $remote_url);
            
            if($is_https && extension_loaded('openssl')) {
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            }
            
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);          
            curl_setopt($ch, CURLOPT_HEADER, false);
    
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            
            // grab URL and pass it to the browser
            $response = curl_exec($ch);
                        
            // close cURL resource, and free up system resources
            curl_close($ch);
    
        // No cURL? Use an alternative code 
        } else {
            
            $context_options = array (
                'http' => array (
                    'method' => 'POST',
                    'header' => "Content-type: application/x-www-form-urlencoded\r\n".
                                "Content-Length: ".strlen($fields_string)."\r\n",
                    'content' => $fields_string
                 )
             );
    
            $context = stream_context_create($context_options);
            $fp = fopen($remote_url, 'r', false, $context);
    
            if (!$fp) {
                throw new Exception("Problem with $remote_url, $php_errormsg");
            }
    
            $response = @stream_get_contents($fp);
    
            if ($response === false) {
                throw new Exception("Problem reading data from $remote_url, $php_errormsg");
            }
        }
        return $response;
    }
    ?>


Usage Example:

    $response = SendPostData($_POST, 'http://www.myserver2location.com/receive-data.php');

PS: You can use any array variable as the first argument. $_POST is just a common one used in these situations.

SOURCE: www.bitrepository.com

Fancy & User-Friendly Select DropDowns with Chosen jQuery Plugin.


Chosen is a jQuery plugin that makes long, unwieldy ordinary select boxes much more user-friendly. Comes with a number of options and attributes that allow you to have full control of your select boxes.

    The following select types are supported:
       
        1. Standard Select
        2. Multiple Select
        3. <optgroup> Support
        4. Selected and Disabled Support
        5. Hide Search on Single Select
       
    Setup:
        Using Chosen is easy as can be.
       
        1. Download the plugin and copy the chosen files to your app.
        2. Activate the plugin on the select boxes of your choice:
            jQuery(".chosen-select").chosen();
       
    All modern browsers are supported (Firefox, Chrome, Safari and IE9). Legacy support for IE8 is also enabled.

Sunday, March 15

__sleep and __wakeup in PHP language.

Meaning of ___sleep:- It returns the array of all the variables which need to be saved.
Meaning of ___wakeup:- It is used to retrieve the array of all the variables.

Here is a code is given:
    <?php
   
        $str = ‘Hello, there.nHow are you?nThanks for visiting Our Website’;
       
        print $str;
   
    ?>

   
Slowing down bruit force attacks on wrong password attempts

    <?php
        public function handle_login() {
            if($uid = user::check_password($_REQUEST['email'], $_REQUEST['password'])) {
                return self::authenticate_user($uid);
            }
            else {
                // delay failed output by 2 seconds
                // to prevent bruit force attacks
                sleep(2);
                return self::login_failed();
            }
        }
    ?>



The intended use of __wakeup() is to reestablish any database connections that may have been lost during serialization and perform other reinitialization tasks.

    Example #1 Sleep and wakeup:

    <?php
        class Connection
        {
            protected $link;
            private $dsn, $username, $password;
           
            public function __construct($dsn, $username, $password)
            {
                $this->dsn = $dsn;
                $this->username = $username;
                $this->password = $password;
                $this->connect();
            }
           
            private function connect()
            {
                $this->link = new PDO($this->dsn, $this->username, $this->password);
            }
           
            public function __sleep()
            {
                return array('dsn', 'username', 'password');
            }
           
            public function __wakeup()
            {
                $this->connect();
            }
        }
    ?>
 

SOURCE: php.net

Friday, March 13

jQuery( document ).ready() vs jQuery.holdReady() vs body.onload

jQuery.holdReady():
    The jQuery.holdReady() method allows the caller to delay jQuery's ready event. This advanced feature would typically be used by dynamic script loaders that want to load additional JavaScript such as jQuery plugins before allowing the ready event to occur, even though the DOM may be ready. This method must be called early in the document, such as in the <head> immediately after the jQuery script tag. Calling this method after the ready event has already fired will have no effect.
   
    Example:
        Delay the ready event until a custom plugin has loaded.
   
        <script>
        jQuery.holdReady( true );
       
        jQuery.getScript( "myplugin.js", function() {
            jQuery.holdReady( false );
        });
        </script>

       
jQuery( document ).ready():
    A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $( window ).load(function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready.
   
    Example:
        <script>
        // A $( document ).ready() block.
        $( document ).ready(function() {
            console.log( "ready!" );
        });
        </script>


body.onload:
    The onload attribute fires when an object has been loaded.
    onload is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.). However, it can be used on other elements as well.

    The onload attribute can be used to check the visitor's browser type and browser version, and load   the proper version of the web page based on the information.
    The onload attribute can also be used to deal with cookies.
   
    Example:
        <!DOCTYPE html>
        <html>
        <head>
        <script>
        function myFunction() {
            alert("Page is loaded");
        }
        </script>
        </head>
       
        <body onload="myFunction()">
        <h1>Hello World!</h1>
        </body>
       
        </html>

Wednesday, March 11

Redirect request after a jQuery Ajax call.

1. Adding a custom header to the response:
   
    <script>
        public ActionResult Index(){
          if (!HttpContext.User.Identity.IsAuthenticated)
          {
            HttpContext.Response.AddHeader("REQUIRES_AUTH","1");
          }
          return View()   
        }
    </script>


2. Binding a JavaScript function to the ajaxSuccess event and checking to see if the header exists:
   
    <script>
        jQuery('body').bind('ajaxSuccess',function(event,request,settings){
            if (request.getResponseHeader('REQUIRES_AUTH') === '1'){
               window.location = '/';
            };
        });
    </script>



SOURCE: stackoverflow.com

How to generate and display widgets areas dynamically?

Not a good thing if you have a lot of categories, so be careful!

First, add the following function in functions.php:

    <?php
    add_action( 'widgets_init', 'generate_widget_areas' );
   
    function generate_widget_areas() {   
   
        //Do not create for uncategorized category
        $terms = get_categories('exclude=1&hide_empty=0');
       
        foreach ($terms as $term) {
                register_sidebar( array(
                'name' => 'Category '.$term->name,
                'id' => $term->slug.'-widget-area',
                'description' => 'Widget area for category and posts in '.$term->name,
                'before_widget' => '<li id="%1$s" class="widget-container %2$s">',
                'after_widget' => '</li>',
                'before_title' => '<h3 class="widget-title">',
                'after_title' => '</h3>'    ) );
        }
    }
    ?>

This is enough, now in Widgets you have a widget area for every category. Now you have to show the area for the category. I like to display the area for categories listings (categories posts listings) and the same area for posts using the category as well (single posts pages).

In sidebar.php, add:

    <?php if (is_category() || is_archive() || is_single()) : ?>
        <div id="categories" class="widget-area" role="complementary">
        <ul class="xoxo">
          <?php
           $category = get_the_category();
           if (in_category($category[0]->slug) || is_category($category[0]->slug)){
                dynamic_sidebar( $category[0]->slug.'-widget-area' );
            };
           ?>
        </ul>
        </div><!-- #categories .widget-area -->
    <?php endif; ?>


That's all, I bet someone can came up with a better code, by now this does the trick.

SOURCCE: stackexchange

Friday, March 6

Simple navigation tab in jQuery.

<!-- HTML -->

    <div id="tabs">
        <ul>
            <li><a href="#tabs-1">Tab 1</a>
            </li>
            <li><a href="#tabs-2">Tab 2</a>
            </li>
            <li><a href="#tabs-3">Tab 3</a>
            </li>
        </ul>
        <div id="tabs-1">
            <p>Content for Tab 1</p>
        </div>
        <div id="tabs-2">
            <p>Content for Tab 2</p>
        </div>
        <div id="tabs-3">
            <p>Content for Tab 3</p>
        </div>
    </div>
    <div id="tabid"></div>


<!-- CSS -->

<style>
    body {
        background-color: #eef;
    }
    #tabs {
        width: 95%;
        margin-left: auto;
        margin-right: auto;
        margin-top: 10px;
    }

/* Note that jQuery UI CSS is loaded from Google's CDN in the "Add Resources" pane to the left.  Normally this would be done in your <head> */
</style>

<!-- SCRIPT -->

<script>
    jQuery("#tabs").tabs({
        activate: function (event, ui) {
            var active = jQuery('#tabs').tabs('option', 'active');
            jQuery("#tabid").html('the tab id is ' + jQuery("#tabs ul>li a").eq(active).attr("href"));
        }
    });
</script>

Scroll to top on a selector with animate in jQuery.

<script>

    jQuery('html, body').animate({
        scrollTop: (jQuery('.tab-container').first().offset().top)
    },500);

</script>

Best way to add options to a select from an array with jQuery

 
This is slightly faster and cleaner.
 
And it's better idea to cache ' $('#mySelect') ' , so 
that you look up only once before the loop. Currently it is searching 
the DOM for the element for every single option .
  
<script>

    selectValues = { "1": "test 1", "2": "test 2" };
   
    jQuery.each(selectValues, function(key, value) {
        $('#mySelect').append(jQuery("<option/>", {
            value: key,
            text: value
        }));
    });

</script>

Wednesday, March 4

Angular JS Interview Questions and Answers

What You Should Already Know

Before you study AngularJS, you should have a basic understanding of:

    1. HTML
    2. CSS
    3. JavaScript

Q: What is AngularJS ?
Ans: AngularJS is a JavaScript framework. It can be added to an HTML page with a <script> tag.
         1. AngularJS extends HTML attributes with Directives, and binds data to HTML with Expressions.
         2. AngularJS is a JavaScript framework. It is a library written in JavaScript.
         3. AngularJS is distributed as a JavaScript file, and can be added to a web page with a script tag:
    
     <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>

Q: How AngularJS Extends HTML ?
Ans: AngularJS extends HTML with ng-directives.

Q: What is AngularJS Directives ?
Ans: AngularJS directives are HTML attributes with an ng prefix.

Q: Explain what are the key features of Angular.js ?
Ans:
The key features of angular.js are

    1. Scope
    2. Controller
    3. Model
    4. View
    5. Services
    6. Data Binding
    7. Directives
    8. Filters
    9. Testable

Q: Explain what is scope in Angular.js ?
Ans:
Scope refers to the application model, it acts like glue between application controller and the view.
     Scopes are arranged in hierarchical structure and impersonate the DOM ( Document Object Model) structure of the application.
     It can watch expressions and propagate events.

Q: Explain what is services in Angular.js ?
Ans:
In angular.js services are the singleton objects or functions that are used for carrying out specific tasks.
     It holds some business logic and these function can be called as controllers, directive, filters and so on.

Q: What is ng-app ?
Ans:
1. The ng-app directive defines an AngularJS application.
     2. The ng-app directive defines the root element of an AngularJS application.
     3. The ng-app directive will auto-bootstrap (automatically initialize) the application when a web page is loaded.

Q: What is ng-model ?
Ans:
The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
     The ng-model directive can also:
        1. Provide type validation for application data (number, email, required).
        2. Provide status for application data (invalid, dirty, touched, error).
        3. Provide CSS classes for HTML elements.
        4. Bind HTML elements to HTML forms.


Q: What is ng-bind ?
Ans:
The ng-bind directive binds application data to the HTML view.

Q: What is ng-init ?
Ans:
1. The ng-init directive initialize AngularJS application variables.
     2. The ng-init directive defines initial values for an AngularJS application.

    Note: You can use data-ng-, instead of ng-, if you want to make your page HTML5 valid.

Q: What is ng-disabled ?
Ans:
The ng-disabled directive binds AngularJS application data to the disabled attribute of HTML elements.

    Example:
        <div ng-app="">
       
            <p>
                <button ng-disabled="mySwitch">Click Me!</button>
            </p>
           
            <p>
                <input type="checkbox" ng-model="mySwitch">Button
            </p>
       
        </div>


    Application explained:

        1. The ng-disabled directive binds the application data mySwitch to the HTML button's disabled attribute.   
        2. The ng-model directive binds the value of the HTML checkbox element to the value of mySwitch.
   
        If the value of mySwitch evaluates to true, the button will be disabled:
            <p>
                <button disabled>Click Me!</button>
            </p>

   
        If the value of mySwitch evaluates to false, the button will not be disabled:
            <p>
                <button>Click Me!</button>
            </p>


Q: What is ng-show ?
Ans:
The ng-show directive shows or hides an HTML element.

    Example:
        <div ng-app="">
       
            <p ng-show="true">I am visible.</p>
           
            <p ng-show="false">I am not visible.</p>
       
        </div>

   
    The ng-show directive shows (or hides) an HTML element based on the value of ng-show.
    You can use any expression that evaluates to true or false:

   
    Example:
        <div ng-app="">
       
            <p ng-show="hour > 12">I am visible.</p>
       
        </div>

Q. What is ng-hide ?
Ans:
The ng-hide directive hides or shows an HTML element.

    Example:
        <div ng-app="">
       
            <p ng-hide="true">I am not visible.</p>
           
            <p ng-hide="false">I am visible.</p>
       
        </div>

       
Q: what is ng-click ?
Ans:
The ng-click directive defines an AngularJS click event.

    Example:
        <div ng-app="" ng-controller="myController">
       
            <button ng-click="count = count + 1">Click me!</button>
           
            <p>{{ count }}</p>
       
        </div>


Q: What is AngularJS Expressions ?
Ans:
1. AngularJS expressions are written inside double braces: {{ expression }}.
     2. AngularJS expressions bind data to HTML the same way as the ng-bind directive.
     3. AngularJS will "output" data exactly where the expression is written.

Q: How to Repeat HTML Elements ?
Ans:
1. The ng-repeat directive repeats an HTML element.
     2. The ng-repeat directive clones HTML elements once for each item in a collection (in an array).

    Example:
        <div ng-app="" ng-init="names=['Jani','Hege','Kai']">
          <ul>
            <li ng-repeat="x in names">
              {{ x }}
            </li>
          </ul>
        </div>


Q: What is controllers ?
Ans:
1. AngularJS applications are controlled by controllers.
     2. The ng-controller directive defines the application controller.
     3. A controller is a JavaScript Object, created by a standard JavaScript object constructor.
    
    Example:
        <div ng-app="" ng-controller="personController">
       
            First Name: <input type="text" ng-model="firstName"><br>
            Last Name: <input type="text" ng-model="lastName"><br>
            <br>
            Full Name: {{firstName + " " + lastName}}
       
        </div>
       
        <script>
        function personController($scope) {
            $scope.firstName="John",
            $scope.lastName="Doe"
        }
        </script>


Q: Write an Example for Controller Methods.
Ans:
 
        <div ng-app="" ng-controller="personController">
       
            First Name: <input type="text" ng-model="firstName"><br>
            Last Name: <input type="text" ng-model="lastName"><br>
            <br>
            Full Name: {{fullName()}}
       
        </div>
       
        <script>
        function personController($scope) {
            $scope.firstName = "John",
            $scope.lastName = "Doe",
            $scope.fullName = function() {
                return $scope.firstName + " " + $scope.lastName;
            }
        }
        </script>

       
Q: What is AngularJS Filters? Explain each of them with example.
Ans:
AngularJS filters can be used to transform data:
            
        1. currency => Format a number to a currency format.
        2. filter => Select a subset of items from an array.
        3. lowercase => Format a string to lower case.
        3. orderBy => Orders an array by an expression.
        4. uppercase => Format a string to upper case.
   
    A filter can be added to an expression with a pipe character (|) and a filter.
    The uppercase filter format strings to upper case:
   
    Example:
        <div ng-app="" ng-controller="personController">

           <p>The name is {{ lastName | uppercase }}</p>
           <p>The name is {{ lastName | lowercase }}</p>
       
        </div>

       
    The currency Filter:
        <div ng-app="" ng-controller="costController">
            <input type="number" ng-model="quantity">
            <input type="number" ng-model="price">
                       
            <p>Total = {{ (quantity * price) | currency }}</p>       
        </div>

   
    Adding Filters to Directives:
        <div ng-app="" ng-controller="namesController">
       
            <ul>
                <li ng-repeat="x in names | orderBy:'country'">
                    {{ x.name + ', ' + x.country }}
                </li>
            </ul>
       
        <div>


    Filtering Input:
        An input filter can be added to a directive with a pipe character (|) and filter followed by a colon and a model name.
        The filter filter selects a subset of an array:
       
        <div ng-app="" ng-controller="namesController">
       
            <p><input type="text" ng-model="test"></p>
           
            <ul>
                <li ng-repeat="x in names | filter:test | orderBy:'country'">
                    {{ (x.name | uppercase) + ', ' + x.country }}
                </li>
            </ul>
       
        </div>


Q: What is AngularJS $http and how it works ?
Ans:
AngularJS $http is a core service for reading data from web servers.
     $http.get(url) is the function to use for reading server data.
    
     Example:
        <div ng-app="" ng-controller="customersController">
       
            <ul>
              <li ng-repeat="x in names">
                {{ x.Name + ', ' + x.Country }}
              </li>
            </ul>
       
        </div>
       
        <script>
        function customersController($scope,$http) {
            $http.get("http://www.w3schools.com/website/Customers_JSON.php")
            .success(function(response) {
                $scope.names = response;
            });
        }
        </script> 


Q: How to Displaying tables with AngularJS ?
Ans:
Displaying tables with angular is very simple:

    Example:
        <div ng-app="" ng-controller="customersController">
       
        <table>
          <tr ng-repeat="x in names">
            <td>{{ x.Name }}</td>
            <td>{{ x.Country }}</td>
          </tr>
        </table>
       
        </div>
       
        <script>
        function customersController($scope,$http) {
          $http.get("http://www.w3schools.com/website/Customers_JSON.php")
          .success(function(response) {
            $scope.names = response;
          });
        }
        </script>

       
Q: How to Fetch Data From a PHP Server Running MySQL ?
Ans:

    Example:
        <div ng-app="" ng-controller="customersController">
       
        <table>
          <tr ng-repeat="x in names">
            <td>{{ x.Name }}</td>
            <td>{{ x.Country }}</td>
          </tr>
        </table>
       
        </div>
       
        <script>
        function customersController($scope,$http) {
            $http.get("http://www.w3schools.com/website/customers_mysql.php")
            .success(function(response) {
                $scope.names = response;
            });
        }
        </script>


Q: What is Cross-Site HTTP Requests ?
Ans:
1. Requests for data from a different server (than the requesting page), are called cross-site HTTP requests.
     2. Cross-site requests are common on the web. Many pages load CSS, images, and scripts from different servers.
     3. In modern browsers, cross-site HTTP requests from scripts are restricted to same site for security reasons.
    
    The following line, in our PHP examples, has been added to allow cross-site access.
        header("Access-Control-Allow-Origin: *");
   
    Server Code PHP and MySQL:   
    <?php
        header("Access-Control-Allow-Origin: *");
        header("Content-Type: application/json; charset=UTF-8");
       
        $conn = new mysqli("myServer", "myUser", "myPassword", "myDatabse");
       
        $result = $conn->query("SELECT CompanyName, City, Country FROM Customers");
       
        $outp = "[";
        while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
            if ($outp != "[") {$outp .= ",";}
            $outp .= '{"Name":"'  . $rs["CompanyName"] . '",';
            $outp .= '"City":"'   . $rs["City"]        . '",';
            $outp .= '"Country":"'. $rs["Country"]     . '"}';
        }
        $outp .="]";
       
        $conn->close();
       
        echo($outp);
    ?>


Q: What is use of AngularJS Modules and how it works ?
Ans:
Global values should be avoided in applications. They can easily be overwritten or destroyed by other scripts.
     AngularJS modules can solve (or reduce) this problem.
    
     Example:
        <!DOCTYPE html>
        <html>
       
            <head>
                <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
            </head>
           
            <body>
           
                <div ng-app="myApp" ng-controller="myCtrl">
                    {{ firstName + " " + lastName }}
                </div>
               
                <script>
                var app = angular.module("myApp", []);
               
                app.controller("myCtrl", function($scope) {
                    $scope.firstName = "John";
                    $scope.lastName = "Doe";
                });
                </script>
           
            </body>
        </html>

       
        The application has a name (ng-app="myApp"), and the controller is a property of the module.

Tuesday, March 3

Geographical location of the IP address using PHP

This code uses the PHP Webservice of http://www.geoplugin.com/ to geolocate IP addresses

Geographical location of the IP address (visitor) and locate currency (symbol, code and exchange rate) are returned.

See http://www.geoplugin.com/webservices/php for more specific details of this free service

<?PHP
    class Geocall{
       
        public function get_location()
        {
            require_once('geoplugin.class.php');
       
            $geoplugin = new geoPlugin();
                   
            //locate the IP
         
            $geoplugin->locate();
            $data['json'] = array("ip"=>"{$geoplugin->ip}",
                          "city" => "{$geoplugin->city}",
                          "countryNmae" => "{$geoplugin->countryName}",
                "currency" => "{$geoplugin->currency}",
                "countryCode" => "{$geoplugin->countryCode}",
        );
           
            echo json_encode($data);
        }
    }
   
    $geo_call = new Geocall();
    $data=$geo_call->get_location();
   
    //prints location
    print_r($data);
?>


There are so many options available at http://www.geoplugin.com/webservices/php