11 Most Asked Questions About PHP
Tags: php
Published: 2020-08-28 07:56:27

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 <a href="https://www.php.net/manual/en/book.pdo.php">PDO</a> (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
}
```

ii. Using <a href="https://www.php.net/manual/en/book.mysqli.php">MySQLi</a> (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
}
```

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);
```

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 `throw`n 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) <a href="https://www.php.net/manual/en/ref.pdo-mysql.connection.php">silently ignored the charset parameter</a> 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 ]);
```

**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';
}
```

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

**Answer:**

You can use the <a href="https://www.php.net/manual/en/function.strpos.php">`strpos()`</a> 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';
}
```

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';
}
```

On the performance side, `strpos` is about three times faster and have in mind, when we did one million compares at once, it took <a href="https://www.php.net/manual/en/function.preg-match.php">`preg_match`</a> 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';
}
```

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 <a href="https://regex101.com/">Regex101</a>.

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.
}
```

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

**Answer:**

The MySQL extension:

- Is not under active development
- Is officially <a href="https://wiki.php.net/rfc/mysql_deprecation">deprecated</a> as of PHP 5.5 (released June 2013).
- Has been <a href="https://wiki.php.net/rfc/remove_deprecated_functionality_in_php7#extmysql">removed</a> entirely as of PHP 7.0 (released December 2015)
   - This means that as of <a href="https://www.php.net/eol.php">31 Dec 2018</a> 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
    - <a href="https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php">Prepared statements</a> 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 <a href="https://www.php.net/manual/en/mysqlinfo.api.choosing.php">the comparison of SQL extensions</a>.

### 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 <a href="https://www.php.net/manual/en/function.unset.php">`unset()`</a> or alternatively <a href="https://www.php.net/manual/en/function.array-splice.php">`\array_splice()`</a>. Also if you have the value and don’t know the key to delete the element you can use <a href="https://www.php.net/manual/en/function.array-search.php">`\array_search()`</a> 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 <a href="https://www.php.net/manual/en/function.array-values.php">`\array_values()`</a> 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

?>
```

**Output**

```
[
    [0] => a
    [2] => c
]
```

**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

?>
```

**Output**

```
[
    [0] => a
    [1] => c
]
```

`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. <a href="https://www.php.net/manual/en/function.array-diff.php">`\array_diff()`</a> 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

?>
```

**Output**

```
[
    [1] => b
]
```

**ii. <a href="https://www.php.net/manual/en/function.array-diff-key.php">`\array_diff_key()`</a> 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 <a href="https://www.php.net/manual/en/function.array-flip.php">`\array_flip()`</a>. 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
?>
```

**Output**

```
[
    [1] => b
]
```

Also if you want to use `unset()` or `\array_splice()` to delete multiple elements with the same value you can use <a href="https://www.php.net/manual/en/function.array-keys.php">`\array_keys()`</a> 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
```

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
```

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
```

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
```

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
```

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
```

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 <a href="https://developers.google.com/youtube/v3/">**YouTube Data API**</a> to retrieve video thumbnails, caption, description, rating, statistics, and more. API version 3 requires a key*. Obtain the key and create a <a href="https://developers.google.com/youtube/v3/docs/videos/list">**videos: list**</a> request:

```
https://www.googleapis.com/youtube/v3/videos?key=YOUR_API_KEY&part=snippet&id=VIDEO_ID
```

**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);
```

**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)
  }
}
```

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.
<a href="https://salman-w.blogspot.com/2010/01/retrieve-youtube-video-title.html">Source article.</a>

### 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();
?>
```

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();
?>
```

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();
?>
```

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();
?>
```

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 (<a href="https://en.wikipedia.org/wiki/Virtual_method_table">see wiki on vtable</a>) 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();
```

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);
```

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
```

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

```
php_flag display_errors 1
```

### 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);
}
```

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

**Alternative Answer:**

You can use <a href="https://www.php.net/manual/en/function.substr-compare.php">`substr_compare`</a> 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;
}
```

### 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);
```

**ii. Important details die() or exit()**

```
header("Location: http://example.com/myOtherPage.php");
die();
```

Why you should use die() or exit(): <a href="http://thedailywtf.com/articles/WellIntentioned-Destruction">The Daily WTF</a>

**Absolute or relative URL**

Since June 2014 both absolute and relative URLs can be used. See <a href="https://greenbytes.de/tech/webdav/rfc7231.html#header.location">RFC 7231</a> which had replaced the old <a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.30">RFC 2616</a>, where only absolute URLs were allowed.

**Status Codes**

PHP’s “Location”-header still uses the <a href="https://en.wikipedia.org/wiki/HTTP_302">HTTP 302</a>-redirect code, but this is not the one you should use. You should consider either <a href="https://en.wikipedia.org/wiki/HTTP_301">301</a> (permanent redirect) or <a href="https://en.wikipedia.org/wiki/HTTP_303">303</a> (other).

Note: <a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4">W3C mentions</a> 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

- <a href="https://www.php.net/manual/en/function.header.php">What the PHP manual says</a>
- <a href="https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Responses">What Wikipedia says</a>
- <a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.30">What the W3C says</a>

**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);
```

This is more flexible:

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

**vi. Workaround**

As mentioned, `header()` redirects only work before anything is written out. They usually fail if <a href="https://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php">invoked inmidst HTML</a> output. Then you might use an HTML header workaround (not very professional!) like:

```
<meta http-equiv="refresh" content="0;url=finalpage.html">
```

Or a JavaScript redirect even.

```
window.location.replace("http://example.com/");
```

**Alternative Answer:**

Use the `header()` function to send an <a href="https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Responses">HTTP `Location` header</a>:

```
header('Location: '.$newURL);
```

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);
?>
```

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
```

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 <a href="https://en.wikipedia.org/wiki/Salt_%28cryptography%29">salts</a> (`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). [<a href="https://www.usenix.org/legacy/events/usenix99/provos/provos_html/node4.html">Source</a>]

**How to use bcrypt:**

**Using PHP >= 5.5-DEV**

Password hashing functions <a href="https://www.php.net/password_hash">have now been built directly into PHP >= 5.5</a>. You may now use <a href="https://www.php.net/password_hash">`password_hash()`</a> 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
```

To verify a user-provided password against an existing hash, you may use the <a href="https://www.php.net/password_verify">`password_verify()`</a> 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.';
}
```

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

There is a <a href="https://github.com/ircmaxell/password_compat">compatibility library</a> on <a href="https://en.wikipedia.org/wiki/GitHub">GitHub</a> 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;
  }
}
```

You can use this code like this:

```
$bcrypt = new Bcrypt(15);

$hash = $bcrypt->hash('password');
$isGood = $bcrypt->verify('password', $hash);
```

Alternatively, you may also use the <a href="https://www.openwall.com/phpass/">Portable PHP Hashing Framework</a>.

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

**Answer:**

You can use either <a href="https://www.php.net/manual/en/function.date.php">date</a> or <a href="https://www.php.net/manual/en/function.strftime.php">strftime</a>. 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"); ?>
```

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 <a href="https://www.truemark.dev/">Truemark</a>, 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: <a href="https://thedevpost.com/blog/11-most-asked-questions-about-php/">DevPostbyTruemark</a>