DEV Community

Cover image for 11 Most Asked Questions About PHP
KiranPoudel98 for Truemark Technology

Posted on • Originally published at thedevpost.com

11 Most Asked Questions About PHP

PHP (Hypertext Pre-processor) is a popular server-side scripting language mainly used for developing websites and web applications. It can be used to build either static or dynamic websites. It is very simple and easy to learn. So, today we will be checking out the 11 most frequently asked questions about PHP.

11 Most Asked Questions About PHP

1. How to prevent SQL injection in PHP?

Answer:

Use prepared statements and parameterized queries.

These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.

You basically have two options to achieve this:

i. Using PDO (for any supported database driver):

$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');

$stmt->execute([ 'name' => $name ]);

foreach ($stmt as $row) {
    // Do something with $row
}
Enter fullscreen mode Exit fullscreen mode

ii. Using MySQLi (for MySQL):

$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name); // 's' specifies the variable type => 'string'

$stmt->execute();

$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // Do something with $row
}
Enter fullscreen mode Exit fullscreen mode

If you’re connecting to a database other than MySQL, there is a driver-specific second option that you can refer to (for example, pg_prepare() and pg_execute() for PostgreSQL). PDO is the universal option.

Correctly setting up the connection

Note that when using PDO to access a MySQL database real prepared statements are not used by default. To fix this you have to disable the emulation of prepared statements. An example of creating a connection using PDO is:

$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'password');

$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Enter fullscreen mode Exit fullscreen mode

In the above example the error mode isn’t strictly necessary, but it is advised to add it. This way the script will not stop with a Fatal Error when something goes wrong. And it gives the developer the chance to catch any error(s) which are thrown as PDOExceptions.

What is mandatory, however, is the first setAttribute() line, which tells PDO to disable emulated prepared statements and use real prepared statements. This makes sure the statement and the values aren’t parsed by PHP before sending it to the MySQL server (giving a possible attacker no chance to inject malicious SQL).

Although you can set the charset in the options of the constructor, it’s important to note that ‘older’ versions of PHP (before 5.3.6) silently ignored the charset parameter in the DSN.

Explanation

The SQL statement you pass to prepare is parsed and compiled by the database server. By specifying parameters (either a ? or a named parameter like :name in the example above) you tell the database engine where you want to filter on. Then when you call execute, the prepared statement is combined with the parameter values you specify.

The important thing here is that the parameter values are combined with the compiled statement, not an SQL string. SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database. So by sending the actual SQL separately from the parameters, you limit the risk of ending up with something you didn’t intend.

Any parameters you send when using a prepared statement will just be treated as strings (although the database engine may do some optimization so parameters may end up as numbers too, of course). In the example above, if the $name variable contains 'Sarah'; DELETE FROM employees the result would simply be a search for the string "'Sarah'; DELETE FROM employees", and you will not end up with an empty table.

Another benefit of using prepared statements is that if you execute the same statement many times in the same session it will only be parsed and compiled once, giving you some speed gains. Oh, and about how to do it for an insert, here’s an example (using PDO):

$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)');

$preparedStatement->execute([ 'column' => $unsafeValue ]);
Enter fullscreen mode Exit fullscreen mode

Can prepared statements be used for dynamic queries?

While you can still use prepared statements for the query parameters, the structure of the dynamic query itself cannot be parametrized and certain query features cannot be parametrized.

For these specific scenarios, the best thing to do is use a whitelist filter that restricts the possible values.

// Value whitelist
// $dir can only be 'DESC', otherwise it will be 'ASC'
if (empty($dir) || $dir !== 'DESC') {
   $dir = 'ASC';
}
Enter fullscreen mode Exit fullscreen mode

2. How to check if a string contains a specific word?

Answer:

You can use the strpos() function which is used to find the occurrence of one string inside another one:

$a = 'How are you?';

if (strpos($a, 'are') !== false) {
    echo 'true';
}
Enter fullscreen mode Exit fullscreen mode

Note that the use of !== false is deliberate (neither != false nor === true will return the desired result); strpos() returns either the offset at which the needle string begins in the haystack string, or the boolean false if the needle isn’t found. Since 0 is a valid offset and 0 is “falsey”, we can’t use simpler constructs like !strpos($a, 'are').

Alternative Answer:

You could use regular expressions, it’s better for word matching compared to strpos as it will also return true for strings such as fare, care, stare, etc. This can simply be avoided in regular expression by using word boundaries. A simple match for are could look something like this:

$a = 'How are you?';

if (preg_match('/\bare\b/', $a)) {
    echo 'true';
}
Enter fullscreen mode Exit fullscreen mode

On the performance side, strpos is about three times faster and have in mind, when we did one million compares at once, it took preg_match 1.5 seconds to finish and for strpos it took 0.5 seconds.

In order to search any part of the string, not just word by word, we would recommend using a regular expression like

$a = 'How are you?';
$search = 'are y';
if(preg_match("/{$search}/i", $a)) {
    echo 'true';
}
Enter fullscreen mode Exit fullscreen mode

The i at the end of regular expression changes regular expression to be case-insensitive, if you do not want that, you can leave it out.

Now, this can be quite problematic in some cases as the $search string isn’t sanitized in any way, meaning, it might not pass the check-in some cases as if $search is a user input they can add some string that might behave like some different regular expression.

Also, here’s a great tool for testing and seeing explanations of various regular expressions Regex101.

To combine both sets of functionality into a single multi-purpose function (including with selectable case sensitivity), you could use something like this:

function FindString($needle,$haystack,$i,$word)
{   // $i should be "" or "i" for case insensitive
    if (strtoupper($word)=="W")
    {   // if $word is "W" then word search instead of string in string search.
        if (preg_match("/\b{$needle}\b/{$i}", $haystack)) 
        {
            return true;
        }
    }
    else
    {
        if(preg_match("/{$needle}/{$i}", $haystack)) 
        {
            return true;
        }
    }
    return false;
    // Put quotes around true and false above to return them as strings instead of as bools/ints.
}
Enter fullscreen mode Exit fullscreen mode

3. Why not to use mysql_* functions in PHP?

Answer:

The MySQL extension:

  • Is not under active development
  • Is officially deprecated as of PHP 5.5 (released June 2013).
  • Has been removed entirely as of PHP 7.0 (released December 2015)
    • This means that as of 31 Dec 2018 it does not exist in any supported version of PHP. If you are using a version of PHP which supports it, you are using a version that doesn’t get security problems fixed.
  • Lacks an OO interface
  • Doesn’t support:
    • Non-blocking, asynchronous queries
    • Prepared statements or parameterized queries
    • Stored procedures
    • Multiple Statements
    • Transactions
    • The “new” password authentication method (on by default in MySQL 5.6; required in 5.7)
    • Any of the new functionality in MySQL 5.1 or later

Since it is deprecated, using it makes your code less future proof. Lack of support for prepared statements is particularly important as they provide a clearer, less error-prone method of escaping and quoting external data than manually escaping it with a separate function call.

See the comparison of SQL extensions.

4. How to delete an element from an array in PHP?

Answer:

There are different ways to delete an array element, where some are more useful for some specific tasks than others.

Delete one array element

If you want to delete just one array element you can use unset() or alternatively \array_splice(). Also if you have the value and don’t know the key to delete the element you can use \array_search() to get the key.

i. unset()

Note that when you use unset() the array keys won’t change/reindex. If you want to reindex the keys you can use \array_values() after unset() which will convert all keys to numerical enumerated keys starting from 0.

Code

<?php

    $array = [0 => "a", 1 => "b", 2 => "c"];
    unset($array[1]);
                //↑ Key which you want to delete

?>
Enter fullscreen mode Exit fullscreen mode

Output

[
    [0] => a
    [2] => c
]
Enter fullscreen mode Exit fullscreen mode

ii. \array_splice() method

If you use \array_splice() the keys will be automatically reindexed, but the associative keys won’t change as opposed to \array_values() which will convert all keys to numerical keys.
Also \array_splice() needs the offset, not the key! as the second parameter.

Code

<?php

    $array = [0 => "a", 1 => "b", 2 => "c"];
    \array_splice($array, 1, 1);
                        //↑ Offset which you want to delete

?>
Enter fullscreen mode Exit fullscreen mode

Output

[
    [0] => a
    [1] => c
]
Enter fullscreen mode Exit fullscreen mode

array_splice() same as unset() take the array by reference, and this means you don’t want to assign the return values of those functions back to the array.

Delete multiple array elements

If you want to delete multiple array elements and don’t want to call unset() or \array_splice() multiple times you can use the functions \array_diff() or \array_diff_key() depending on if you know the values or the keys of the elements which you want to delete.

i. \array_diff() method

If you know the values of the array elements which you want to delete, then you can use \array_diff(). As before with unset() it won’t change/reindex the keys of the array.

Code

<?php

    $array = [0 => "a", 1 => "b", 2 => "c"];
    $array = \array_diff($array, ["a", "c"]);
                               //└────────┘→ Array values which you want to delete

?>
Enter fullscreen mode Exit fullscreen mode

Output

[
    [1] => b
]
Enter fullscreen mode Exit fullscreen mode

ii. \array_diff_key() method

If you know the keys of the elements which you want to delete, then you want to use \array_diff_key(). Here you have to make sure you pass the keys as keys in the second parameter and not as values. Otherwise, you have to flip the array with \array_flip(). And also here the keys won’t change/reindex.

Code

<?php

    $array = [0 => "a", 1 => "b", 2 => "c"];
    $array = \array_diff_key($array, [0 => "xy", "2" => "xy"]);
                                    //↑           ↑ Array keys which you want to delete
?>
Enter fullscreen mode Exit fullscreen mode

Output

[
    [1] => b
]
Enter fullscreen mode Exit fullscreen mode

Also if you want to use unset() or \array_splice() to delete multiple elements with the same value you can use \array_keys() to get all the keys for a specific value and then delete all elements.

5. Is there any way to use PHP and cURL to get the associated thumbnail from the YouTube API?

Answer:

Each YouTube video has four generated images. They are predictably formatted as follows:

https://img.youtube.com/vi/<insert-youtube-video-id-here>/0.jpg
https://img.youtube.com/vi/<insert-youtube-video-id-here>/1.jpg
https://img.youtube.com/vi/<insert-youtube-video-id-here>/2.jpg
https://img.youtube.com/vi/<insert-youtube-video-id-here>/3.jpg
Enter fullscreen mode Exit fullscreen mode

The first one in the list is a full-size image and others are thumbnail images. The default thumbnail image (i.e., one of 1.jpg, 2.jpg, 3.jpg) is:

https://img.youtube.com/vi/<insert-youtube-video-id-here>/default.jpg
Enter fullscreen mode Exit fullscreen mode

For the high-quality version of the thumbnail use a URL similar to this:

https://img.youtube.com/vi/<insert-youtube-video-id-here>/hqdefault.jpg
Enter fullscreen mode Exit fullscreen mode

There is also a medium quality version of the thumbnail, using a URL similar to the HQ:

https://img.youtube.com/vi/<insert-youtube-video-id-here>/mqdefault.jpg
Enter fullscreen mode Exit fullscreen mode

For the standard definition version of the thumbnail, use a URL similar to this:

https://img.youtube.com/vi/<insert-youtube-video-id-here>/sddefault.jpg
Enter fullscreen mode Exit fullscreen mode

For the maximum resolution version of the thumbnail use a URL similar to this:

https://img.youtube.com/vi/<insert-youtube-video-id-here>/maxresdefault.jpg
Enter fullscreen mode Exit fullscreen mode

All of the above URLs are available over HTTP too. Additionally, the slightly shorter hostname i3.ytimg.com works in place of img.youtube.com in the example URLs above.

Alternatively, you can use the YouTube Data API (v3) to get thumbnail images.

Alternative Answer:

You can use YouTube Data API to retrieve video thumbnails, caption, description, rating, statistics, and more. API version 3 requires a key*. Obtain the key and create a videos: list request:

https://www.googleapis.com/youtube/v3/videos?key=YOUR_API_KEY&part=snippet&id=VIDEO_ID
Enter fullscreen mode Exit fullscreen mode

Example PHP Code

$data = file_get_contents("https://www.googleapis.com/youtube/v3/videos?key=YOUR_API_KEY&part=snippet&id=T0Jqdjbed40");
$json = json_decode($data);
var_dump($json->items[0]->snippet->thumbnails);
Enter fullscreen mode Exit fullscreen mode

Output

object(stdClass)#5 (5) {
  ["default"]=>
  object(stdClass)#6 (3) {
    ["url"]=>
    string(46) "https://i.ytimg.com/vi/T0Jqdjbed40/default.jpg"
    ["width"]=>
    int(120)
    ["height"]=>
    int(90)
  }
  ["medium"]=>
  object(stdClass)#7 (3) {
    ["url"]=>
    string(48) "https://i.ytimg.com/vi/T0Jqdjbed40/mqdefault.jpg"
    ["width"]=>
    int(320)
    ["height"]=>
    int(180)
  }
  ["high"]=>
  object(stdClass)#8 (3) {
    ["url"]=>
    string(48) "https://i.ytimg.com/vi/T0Jqdjbed40/hqdefault.jpg"
    ["width"]=>
    int(480)
    ["height"]=>
    int(360)
  }
  ["standard"]=>
  object(stdClass)#9 (3) {
    ["url"]=>
    string(48) "https://i.ytimg.com/vi/T0Jqdjbed40/sddefault.jpg"
    ["width"]=>
    int(640)
    ["height"]=>
    int(480)
  }
  ["maxres"]=>
  object(stdClass)#10 (3) {
    ["url"]=>
    string(52) "https://i.ytimg.com/vi/T0Jqdjbed40/maxresdefault.jpg"
    ["width"]=>
    int(1280)
    ["height"]=>
    int(720)
  }
}
Enter fullscreen mode Exit fullscreen mode

Not only that you need a key, you might be asked for billing information depending on the number of API requests you plan to make. However, a few million requests per day are free.
Source article.

6. When to use self over $this?

Answer:

Use $this to refer to the current object. Use self to refer to the current class. In other words, use $this->member for non-static members, use self::$member for static members.

Here is an example of correct usage of $this and self for non-static and static member variables:

<?php
class X {
    private $non_static_member = 1;
    private static $static_member = 2;

    function __construct() {
        echo $this->non_static_member . ' '
           . self::$static_member;
    }
}

new X();
?>
Enter fullscreen mode Exit fullscreen mode

Here is an example of incorrect usage of $this and self for non-static and static member variables:

<?php
class X {
    private $non_static_member = 1;
    private static $static_member = 2;

    function __construct() {
        echo self::$non_static_member . ' '
           . $this->static_member;
    }
}

new X();
?>
Enter fullscreen mode Exit fullscreen mode

Here is an example of polymorphism with $this for member functions:

<?php
class X {
    function foo() {
        echo 'X::foo()';
    }

    function bar() {
        $this->foo();
    }
}

class Y extends X {
    function foo() {
        echo 'Y::foo()';
    }
}

$x = new Y();
$x->bar();
?>
Enter fullscreen mode Exit fullscreen mode

Here is an example of suppressing polymorphic behavior by using self for member functions:

<?php
class X {
    function foo() {
        echo 'X::foo()';
    }

    function bar() {
        self::foo();
    }
}

class Y extends X {
    function foo() {
        echo 'Y::foo()';
    }
}

$x = new Y();
$x->bar();
?>
Enter fullscreen mode Exit fullscreen mode

The idea is that $this->foo() calls the foo() member function of whatever is the exact type of the current object. If the object is of type X, it thus calls X::foo(). If the object is of type Y, it calls Y::foo(). But with self::foo(), X::foo() is always called.

From http://www.phpbuilder.com/board/showthread.php?t=10354489:
By http://board.phpbuilder.com/member.php?145249-laserlight

Alternative Answer:

The keyword self does NOT refer merely to the ‘current class’, at least not in a way that restricts you to static members. Within the context of a non-static member, self also provides a way of bypassing the vtable (see wiki on vtable) for the current object. Just as you can use parent::methodName() to call the parents version of a function, so you can call self::methodName() to call the current classes implementation of a method.

class Person {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }

    public function getTitle() {
        return $this->getName()." the person";
    }

    public function sayHello() {
        echo "Hello, I'm ".$this->getTitle()."<br/>";
    }

    public function sayGoodbye() {
        echo "Goodbye from ".self::getTitle()."<br/>";
    }
}

class Geek extends Person {
    public function __construct($name) {
        parent::__construct($name);
    }

    public function getTitle() {
        return $this->getName()." the geek";
    }
}

$geekObj = new Geek("Ludwig");
$geekObj->sayHello();
$geekObj->sayGoodbye();
Enter fullscreen mode Exit fullscreen mode

This will output:

Hello, I’m Ludwig the geek Goodbye from Ludwig the person

sayHello() uses the $this pointer, so the vtable is invoked to call Geek::getTitle(). sayGoodbye() uses self::getTitle(), so the vtable is not used and Person::getTitle() is called. In both cases, we are dealing with the method of an instantiated object, and have access to the $this pointer within the called functions.

7. How to get PHP errors to display?

Answer:

You can do as following:

ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
Enter fullscreen mode Exit fullscreen mode

However, this doesn’t make PHP to show parse errors – the only way to show those errors is to modify your php.ini with this line:

display_errors = on
Enter fullscreen mode Exit fullscreen mode

(if you don’t have access to php.ini, then putting this line in .htaccess might work too):

php_flag display_errors 1
Enter fullscreen mode Exit fullscreen mode

8. How to write two functions that would take a string and return if it starts with the specified character/string or ends with it?

Answer:

You can do as given below:

function startsWith($haystack, $needle)
{
     $length = strlen($needle);
     return (substr($haystack, 0, $length) === $needle);
}

function endsWith($haystack, $needle)
{
    $length = strlen($needle);
    if ($length == 0) {
        return true;
    }

    return (substr($haystack, -$length) === $needle);
}
Enter fullscreen mode Exit fullscreen mode

Use this if you don’t want to use a regex.

Alternative Answer:

You can use substr_compare function to check start-with and ends-with:

function startsWith($haystack, $needle) {
    return substr_compare($haystack, $needle, 0, strlen($needle)) === 0;
}
function endsWith($haystack, $needle) {
    return substr_compare($haystack, $needle, -strlen($needle)) === 0;
}
Enter fullscreen mode Exit fullscreen mode

9. How to make a redirect in PHP?

Answer:

i. Basic answer

You can use the header() function to send a new HTTP header, but this must be sent to the browser before any HTML or text (so before the <!DOCTYPE ...> declaration, for example).

header('Location: '.$newURL);
Enter fullscreen mode Exit fullscreen mode

ii. Important details die() or exit()

header("Location: http://example.com/myOtherPage.php");
die();
Enter fullscreen mode Exit fullscreen mode

Why you should use die() or exit(): The Daily WTF

Absolute or relative URL

Since June 2014 both absolute and relative URLs can be used. See RFC 7231 which had replaced the old RFC 2616, where only absolute URLs were allowed.

Status Codes

PHP’s “Location”-header still uses the HTTP 302-redirect code, but this is not the one you should use. You should consider either 301 (permanent redirect) or 303 (other).

Note: W3C mentions that the 303-header is incompatible with “many pre-HTTP/1.1 user agents. Currently used browsers are all HTTP/1.1 user agents. This is not true for many other user agents like spiders and robots.

iii. Documentation

HTTP Headers and the header() function in PHP

iv. Alternatives

You may use the alternative method of http_redirect($url); which needs the PECL package pecl to be installed.

v. Helper Functions

This function doesn’t incorporate the 303 status code:

function Redirect($url, $permanent = false)
{
    header('Location: ' . $url, true, $permanent ? 301 : 302);

    exit();
}

Redirect('http://example.com/', false);
Enter fullscreen mode Exit fullscreen mode

This is more flexible:

function redirect($url, $statusCode = 303)
{
   header('Location: ' . $url, true, $statusCode);
   die();
}
Enter fullscreen mode Exit fullscreen mode

vi. Workaround

As mentioned, header() redirects only work before anything is written out. They usually fail if invoked inmidst HTML output. Then you might use an HTML header workaround (not very professional!) like:

<meta http-equiv="refresh" content="0;url=finalpage.html">
Enter fullscreen mode Exit fullscreen mode

Or a JavaScript redirect even.

window.location.replace("http://example.com/");
Enter fullscreen mode Exit fullscreen mode

Alternative Answer:

Use the header() function to send an HTTP Location header:

header('Location: '.$newURL);
Enter fullscreen mode Exit fullscreen mode

Contrary to what some think, die() has nothing to do with redirection. Use it only if you want to redirect instead of normal execution. File example.php:

<?php
    header('Location: static.html');
    $fh = fopen('/tmp/track.txt', 'a');
    fwrite($fh, $_SERVER['REMOTE_ADDR'] . ' ' . date('c') . "\n");
    fclose($fh);
?>
Enter fullscreen mode Exit fullscreen mode

Result of three executions:

bart@hal9k:~> cat /tmp/track.txt
127.0.0.1 2009-04-21T09:50:02+02:00
127.0.0.1 2009-04-21T09:50:05+02:00
127.0.0.1 2009-04-21T09:50:08+02:00
Enter fullscreen mode Exit fullscreen mode

Resuming — obligatory die()/exit() is some urban legend that has nothing to do with actual PHP. It has nothing to do with the client “respecting” the Location: header. Sending a header does not stop PHP execution, regardless of the client used.

10. How do you use bcrypt for hashing passwords in PHP?

Answer:

bcrypt is a hashing algorithm that is scalable with hardware (via a configurable number of rounds). Its slowness and multiple rounds ensure that an attacker must deploy massive funds and hardware to be able to crack your passwords. Add to that per-password salts (bcrypt REQUIRES salts) and you can be sure that an attack is virtually unfeasible without either ludicrous amount of funds or hardware.

bcrypt uses the Eksblowfish algorithm to hash passwords. While the encryption phase of Eksblowfish and Blowfish are exactly the same, the key schedule phase of Eksblowfish ensures that any subsequent state depends on both salt and key (user password), and no state can be precomputed without the knowledge of both. Because of this key difference, bcrypt is a one-way hashing algorithm. You cannot retrieve the plain text password without already knowing the salt, rounds, and key (password). [Source]

How to use bcrypt:

Using PHP >= 5.5-DEV

Password hashing functions have now been built directly into PHP >= 5.5. You may now use password_hash() to create a bcrypt hash of any password:

<?php
// Usage 1:
echo password_hash('rasmuslerdorf', PASSWORD_DEFAULT)."\n";
// $2y$10$xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// For example:
// $2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a

// Usage 2:
$options = [
  'cost' => 11
];
echo password_hash('rasmuslerdorf', PASSWORD_BCRYPT, $options)."\n";
// $2y$11$6DP.V0nO7YI3iSki4qog6OQI5eiO6Jnjsqg7vdnb.JgGIsxniOn4C
Enter fullscreen mode Exit fullscreen mode

To verify a user-provided password against an existing hash, you may use the password_verify() as such:

<?php
// See the password_hash() example to see where this came from.
$hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';

if (password_verify('rasmuslerdorf', $hash)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}
Enter fullscreen mode Exit fullscreen mode

Using PHP >= 5.3.7, < 5.5-DEV (also RedHat PHP >= 5.3.3)

There is a compatibility library on GitHub created based on the source code of the above functions originally written in C, which provides the same functionality. Once the compatibility library is installed, usage is the same as above (minus the shorthand array notation if you are still on the 5.3.x branch).

Using PHP < 5.3.7 (DEPRECATED)

You can use crypt() function to generate bcrypt hashes of input strings. This class can automatically generate salts and verify existing hashes against an input. If you are using a version of PHP higher or equal to 5.3.7, it is highly recommended you use the built-in function or the compat library. This alternative is provided only for historical purposes.

class Bcrypt{
  private $rounds;

  public function __construct($rounds = 12) {
    if (CRYPT_BLOWFISH != 1) {
      throw new Exception("bcrypt not supported in this installation. See http://php.net/crypt");
    }

    $this->rounds = $rounds;
  }

  public function hash($input){
    $hash = crypt($input, $this->getSalt());

    if (strlen($hash) > 13)
      return $hash;

    return false;
  }

  public function verify($input, $existingHash){
    $hash = crypt($input, $existingHash);

    return $hash === $existingHash;
  }

  private function getSalt(){
    $salt = sprintf('$2a$%02d$', $this->rounds);

    $bytes = $this->getRandomBytes(16);

    $salt .= $this->encodeBytes($bytes);

    return $salt;
  }

  private $randomState;
  private function getRandomBytes($count){
    $bytes = '';

    if (function_exists('openssl_random_pseudo_bytes') &&
        (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')) { // OpenSSL is slow on Windows
      $bytes = openssl_random_pseudo_bytes($count);
    }

    if ($bytes === '' && is_readable('/dev/urandom') &&
       ($hRand = @fopen('/dev/urandom', 'rb')) !== FALSE) {
      $bytes = fread($hRand, $count);
      fclose($hRand);
    }

    if (strlen($bytes) < $count) {
      $bytes = '';

      if ($this->randomState === null) {
        $this->randomState = microtime();
        if (function_exists('getmypid')) {
          $this->randomState .= getmypid();
        }
      }

      for ($i = 0; $i < $count; $i += 16) {
        $this->randomState = md5(microtime() . $this->randomState);

        if (PHP_VERSION >= '5') {
          $bytes .= md5($this->randomState, true);
        } else {
          $bytes .= pack('H*', md5($this->randomState));
        }
      }

      $bytes = substr($bytes, 0, $count);
    }

    return $bytes;
  }

  private function encodeBytes($input){
    // The following is code from the PHP Password Hashing Framework
    $itoa64 = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

    $output = '';
    $i = 0;
    do {
      $c1 = ord($input[$i++]);
      $output .= $itoa64[$c1 >> 2];
      $c1 = ($c1 & 0x03) << 4;
      if ($i >= 16) {
        $output .= $itoa64[$c1];
        break;
      }

      $c2 = ord($input[$i++]);
      $c1 |= $c2 >> 4;
      $output .= $itoa64[$c1];
      $c1 = ($c2 & 0x0f) << 2;

      $c2 = ord($input[$i++]);
      $c1 |= $c2 >> 6;
      $output .= $itoa64[$c1];
      $output .= $itoa64[$c2 & 0x3f];
    } while (true);

    return $output;
  }
}
Enter fullscreen mode Exit fullscreen mode

You can use this code like this:

$bcrypt = new Bcrypt(15);

$hash = $bcrypt->hash('password');
$isGood = $bcrypt->verify('password', $hash);
Enter fullscreen mode Exit fullscreen mode

Alternatively, you may also use the Portable PHP Hashing Framework.

11. How to use PHP to get the current year?

Answer:

You can use either date or strftime. In this case, it doesn’t matter as a year is a year, no matter what (unless there’s a locale that formats the year differently?) For example:

<?php echo date("Y"); ?>
Enter fullscreen mode Exit fullscreen mode

On a side note when formatting dates in PHP it matters when you want to format your date in a different locale than your default. If so, you have to use setlocale and strftime. According to the php manual on date:

To format dates in other languages, you should use the setlocale() and strftime() functions instead of date().

From this point of view, it would be best to use strftime as much as possible, if you even have a remote possibility of having to localize your application. If that’s not an issue, pick the one you like best.

In Conclusion

These are the 11 most commonly asked questions about PHP. If you have any suggestions or any confusion, please comment below. If you need any help, we will be glad to help you.

We, at Truemark, provide services like web and mobile app development, digital marketing, and website development. So, if you need any help and want to work with us, please feel free to contact us.

Hope this article helped you.

Original Source: DevPostbyTruemark

Top comments (4)

Collapse
 
_garybell profile image
Gary Bell

It's also worth mentioning that for "6. When to use self over $this?", that you have to use self as the return type of a class function (PHP 7.4+) when you are declaring the return types, and returning the full class object (for things like method chaining). e.g.

class Person {
  private string $name = '';
  function getName(): string
  {
    return $this->name;
  }

  function setName(string $name): self
  {
    $this->name = $name;
    return $this;
  }
}

This would allow you to do mad stuff like:

$person = new Person();
$person->setName('Bill')->setName('Ben')->setName('Sally')->setName('Betty');
echo $person->getName(); // outputs Betty

If you don't want to do method chaining, you don't have to return $this from setName(), but self is used as the return type, when performing return $this within a function

Collapse
 
mis0u profile image
Mickaël

And soon with php.8 :

str_contains('Hello world', 'world') :bool
str_starts_with('Hello world', 'world') : bool;
str_ends_with('Hello world', 'world') : bool;
Collapse
 
vlasales profile image
Collapse
 
evrtrabajo profile image
Emmanuel Valverde Ramos

To me the most asked questions were about SOLID
dev.to/evrtrabajo/solid-in-php-d8e