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.