Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Wednesday, August 26

Difference between PHP4 and PHP5

There are some 27 differences which I got to  know between PHP4 and PHP5:

    1. PHP5 removed register_globals, magic quotes, and safe mode. This was due to the fact that register_globals had opened security holes by intentionally allowing runtime data injection and the use of magic quotes had an unpredictable nature.
   
    2. PHP4 was powered by Zend Engine 1.0, while PHP5 was powered by Zend Engine II.
   
    3. PHP5 replaced magic quotes with the addslashes() function in order to escape characters.
   
    4. PHP4 is more of a procedure language while PHP5 is object oriented.
   
    5. In PHP5 one can declare a class as Abstract.
   
    6. PHP5 incorporates static methods and properties.
   
    7. PHP5 introduces a special function called __autoload()
   
    8. PHP5 allows one to declare a class or method as Final
   
    9. PHP5 introduces a number of magic methods, such as __call, __get, __set and __toString
   
    10. In PHP5, there are 3 levels of visibilities: Public, private and protected.
   
    11. PHP5 introduced exceptions.
   
    12. In PHP4, everything was passed by value, including objects. Whereas in PHP5, all objects are passed by reference.
   
    13. PHP5 introduces interfaces. All the methods defined in an interface must be public.
   
    14. PHP5 introduces new error level defined as 'E_STRICT'
   
    15. PHP5 introduces new default extensions such as SimpleXML, DOM and XSL, PDO, and Hash.
   
    16. PHP5 introduces new functions.
   
    17. PHP5 introduces some new reserved keywords.
   
    18. PHP5 includes additional OOP concepts than php4, like access specifiers , inheritance etc.
   
    19. PHP5 includes improved support of current content management systems.
   
    20. PHP5 includes reduced consumption of RAM.
   
    21. PHP5 introduces increased security against exploitation of vulnerabilities in PHP scripts.
   
    22. PHP5 introduces easier programming through new functions and extensions.
   
    23. PHP5 introduces a new MySQL extension named MySQLi for developers using MySQL 4.1 and later.
   
    24. In PHP5, SQLite has been bundled with PHP.
   
    25. PHP5 introduces a brand new built-in SOAP extension for interoperability with Web Services.
   
    26. PHP5 introduces a new SimpleXML extension for easily accessing and manipulating XML as PHP objects. It can also interface with the DOM extension and vice-versa.
   
    27. In PHP5, streams have been greatly improved, including the ability to access low-level socket operations on streams.

PHP4 vs PHP5 (Additional Features of PHP5)

Constructors and Destructors

    In PHP4, Constructor have same name as the Class name.
    In PHP5, name Constructors as _construct and Destructors as _destruct().

Passed by References

    In PHP4, everything was passed by value.
    In PHP5, all objects are passed by references.

Abstract

    In PHP5, we can declare a class as abstract.

Static Methods and Properties

    In PHP5, Static Methods and Properties are also available. When you declare a class as static, then you can access using :: operator without creating an instances of class

_autoload()

    PHP5 introduces a special function called _autoload().

Final

    PHP5 allows you to declare a class or method as final.

Magic Methods

    PHP5 introduces magic methods such as _call, _get, _set and _tostring

Visibility

    PHP5 has 3 level of visibilities
    Public: methods are accessible to everyone including objects outside the class
    Private: methods are accessible to the class itself
    Protected: methods are accessible to the class itself and inherited classes.

Exception

    PHP5 introduces exceptions handling.

Interfaces

    PHP5 introduces Interfaces.

E-Strict Error Level

    PHP5 introduces new error level defined as E_STRICT.
    E_STRICT will notify you when you use depreciated code.

Extensions

    PHP5 introduces new default extensions.
    Simple XML
    DOM and XSL
    PDO
    Hash

Friday, July 24

PHP Singleton pattern for a database class

An example of how you would implement a Singleton pattern for a database class can be seen below:

<?php
class Database implements Singleton {
    private static $instance;
    private $pdo;

    private function __construct() {
        $this->pdo = new PDO(
            "mysql:host=localhost;dbname=database",
            "user",
            "password"
        );
    }

    public static function getInstance() {
        if(self::$instance === null) {
            self::$instance = new Database();
        }
        return self::$instance->pdo;
    }
}
?>
You would make use of the class in the following manner:

<?php
$db = Database::getInstance();
// $db is now an instance of PDO
$db->prepare("SELECT ...");

// ...

$db = Database::getInstance();
// $db is the same instance as before
?>

And for reference, the Singleton interface would look like:
<?php
interface Singleton {
    public static function getInstance();
}
?>

Write a class that implements singleton pattern PHP.

In the singleton pattern a class can distribute one instance of itself to other classes.

<?php

/*
 *   Singleton classes
 */
class BookSingleton {
    private $author = 'Gamma, Helm, Johnson, and Vlissides';
    private $title  = 'Design Patterns';
    private static $book = NULL;
    private static $isLoanedOut = FALSE;

    private function __construct() {
    }

    static function borrowBook() {
      if (FALSE == self::$isLoanedOut) {
        if (NULL == self::$book) {
           self::$book = new BookSingleton();
        }
        self::$isLoanedOut = TRUE;
        return self::$book;
      } else {
        return NULL;
      }
    }

    function returnBook(BookSingleton $bookReturned) {
        self::$isLoanedOut = FALSE;
    }

    function getAuthor() {return $this->author;}

    function getTitle() {return $this->title;}

    function getAuthorAndTitle() {
      return $this->getTitle() . ' by ' . $this->getAuthor();
    }
  }

class BookBorrower {
    private $borrowedBook;
    private $haveBook = FALSE;

    function __construct() {
    }

    function getAuthorAndTitle() {
      if (TRUE == $this->haveBook) {
        return $this->borrowedBook->getAuthorAndTitle();
      } else {
        return "I don't have the book";
      }
    }

    function borrowBook() {
      $this->borrowedBook = BookSingleton::borrowBook();
      if ($this->borrowedBook == NULL) {
        $this->haveBook = FALSE;
      } else {
        $this->haveBook = TRUE;
      }
    }

    function returnBook() {
      $this->borrowedBook->returnBook($this->borrowedBook);
    }
  }

/*
 *   Initialization
 */

  writeln('BEGIN TESTING SINGLETON PATTERN');
  writeln('');

  $bookBorrower1 = new BookBorrower();
  $bookBorrower2 = new BookBorrower();

  $bookBorrower1->borrowBook();
  writeln('BookBorrower1 asked to borrow the book');
  writeln('BookBorrower1 Author and Title: ');
  writeln($bookBorrower1->getAuthorAndTitle());
  writeln('');

  $bookBorrower2->borrowBook();
  writeln('BookBorrower2 asked to borrow the book');
  writeln('BookBorrower2 Author and Title: ');
  writeln($bookBorrower2->getAuthorAndTitle());
  writeln('');

  $bookBorrower1->returnBook();
  writeln('BookBorrower1 returned the book');
  writeln('');

  $bookBorrower2->borrowBook();
  writeln('BookBorrower2 Author and Title: ');
  writeln($bookBorrower1->getAuthorAndTitle());
  writeln('');

  writeln('END TESTING SINGLETON PATTERN');

  function writeln($line_in) {
    echo $line_in.'<br/>';
  }
?>

Output

BEGIN TESTING SINGLETON PATTERN


BookBorrower1 asked to borrow the book
BookBorrower1 Author and Title:
Design Patterns by Gamma, Helm, Johnson, and Vlissides


BookBorrower2 asked to borrow the book
BookBorrower2 Author and Title:
I don't have the book


BookBorrower1 returned the book


BookBorrower2 Author and Title:
Design Patterns by Gamma, Helm, Johnson, and Vlissides


END TESTING SINGLETON PATTERN

Tuesday, July 14

Get Just The Path from a Request in PHP


It can be a little tricky to get just the path of a request in PHP.
$_SERVER['REQUEST_URI'] includes the query string.
$_SERVER['SCRIPT_NAME'] may return index.php instead of the request if you’re using a CMS like WordPress which rewrites URLs.

The most reliable method I’ve found for returning only the path without the query string uses PHP’s built in parse_url() function:

<?php

    $path_only = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

?>

Friday, June 5

Check uploaded file is actually an image using PHP.


<?php
    if (@getimagesize($_FILES["file"]["tmp_name"]) !== false) {
        $destination = "uploads/" . $_FILES["file"]["name"];
        move_uploaded_file($_FILES["file"]["tmp_name"], $destination);
    }
?>

Monday, June 1

Remove all characters except letters and numbers.

Receiving short codes in an app via URL query strings? Instead of using complex sanitization functions, this simple RegEx replace will get rid of all the junk in the input $string except for letters and numbers:

$clean_code = preg_replace('/[^\w]/', '', $string);
 

If you want more control over which character classes are 
preserved, you can specify them explicitly:
 
 
$clean_code = preg_replace('/[^a-zA-Z0-9]/', '', $string);

Wednesday, May 20

Passing Values From JavaScript to PHP and Back

1. PHP to JavaScript

    <?php
        echo "Just wanted to say $hello";
    ?>

2. JavaScript to PHP

    <script>
        function sayHelloWorld() {
            var hello = "hello";
            var world = "world";
       
            window.location.href = "somepage.php?w1=" + hello + "&w2=" + world;
        }
    </script>
   
3. PHP Receiving and Processing The Variables

    <?php
    function sayHiBack() {
       // Check if we have parameters w1 and w2 being passed to the script through the URL
       if (isset($_GET["w1"]) && isset($_GET["w2"])) {
   
          // Put the two words together with a space in the middle to form "hello world"
          $hello = $_GET["w1"] . " " . $_GET["w2"];
   
          // Print out some JavaScript with $hello stuck in there which will put "hello world" into the javascript.
          echo "<script language='text/javascript'>function sayHiFromPHP() { alert('Just wanted to say $hello!'); }</script>";
       }
    }
    ?>

Post Multiple JavaScript Values to PHP Using jQuery AJAX

Step 1. To Package Up data for Sending

    <script>
        // Create an object using an object literal.
        var ourObj = {};
       
        // Create a string member called "data" and give it a string.
        // Also create an array of simple object literals for our object.
        ourObj.data = "Some Data Points";
        ourObj.arPoints = [{'x':1, 'y': 2},{'x': 2.3, 'y': 3.3},{'x': -1, 'y': -4}];

    </script>
   
Step 2: Transmitting This Data in jQuery AJAX

    <script>
        $.ajax({
           url: 'process-data.php',
           type: 'post',
           data: {"points" : JSON.stringify(ourObj)},
           success: function(data) {
                // Do something with data that came back.
           }
        });
    </script>
   
Step 3: Package Sent, Package Received

    <?php
    // Test if our data came through
    if (isset($_POST["points"])) {
        // Decode our JSON into PHP objects we can use
        $points = json_decode($_POST["points"]);
   
        // Access our object's data and array values.
        echo "Data is: " . $points->data . "<br>";
        echo "Point 1: " . $points->arPoints[0]->x . ", " . $points->arPoints[0]->y;
    }
    ?>

Monday, May 11

Multiple File Extensions validate using PHP.


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

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

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

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

Wednesday, March 11

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

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

Friday, February 27

Check if PHP Session has already started

Recommended way for versions of PHP >= 5.4.0

<?PHP
    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }
?>

Source: http://www.php.net/manual/en/function.session-status.php

For versions of PHP < 5.4.0

<?PHP
    if(session_id() == '') {
        session_start();
    }
?>

Prepared Statements using PHP or Fix SQL Injection.

PHP coders should use the PDO module if possible as it supports prepared statements across various databases. MySQL users should in particular avoid the old "mysql" module which does not support prepared statements. As of PHP 5, mysqli is available and it supports prepared statements.

Secure Usage:

<?PHP
    $oDB=new PDO('... your connection details... ');
    $hStmt=$oDB->prepare("select name, age from users where userid=:userid");
    $hStmt->execute(array(':userid',$nUserID));
?>

Vulnerable Usage

<?PHP
    // Example #1 (using old mysql library)
    $q=$_GET["q"];
    $con = mysql_connect('localhost', 'peter', 'abc123');
    mysql_select_db("ajax_demo", $con);
    $sql="SELECT * FROM user WHERE id = '".$q."'";
    $result = mysql_query($sql);
?>
(code copied from http://www.w3schools.com/PHP/php_ajax_database.asp )

This code is vulnerable to SQL injection. It uses the old mysql library, which does not support prepared statements. However, the vulnerability could still be avoided by either properly escaping or validating the user input.

<?PHP
    // Example #2 (incorrectly preparing a statement with PDO)
    $oDB=new PDO('... your connection details...');
    $hStmt=$oDB->prepare("select name, age from users where userid=".$_GET['userid']);
    $hStmt->execute();
?>

The second vulnerable example looks just like the secure one above. But instead of properly binding the user data, it assembles dynamic SQL and prepared it after adding user data.