What Should Be the Index Name While Uploading Something in Php

The Heat Alphabetize Of Questions Almost PHP

image

Kiran HackerNoon profile picture

@ Kiran

Kiran

Content Writer at Truemark Engineering. Company Website Link - https://world wide web.truemark.dev/

PHP (Hypertext Pre-processor) is a pop server-side scripting linguistic communication mainly used for developing websites and web applications. It tin can be used to build either static or dynamic websites. It is very elementary and easy to learn. And then, today we volition be checking out the 11 near frequently asked questions most PHP.

11 Most Asked Questions About PHP

1. How to forestall 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 whatsoever parameters. This way it is impossible for an attacker to inject malicious SQL.

You basically have ii options to achieve this:

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

                $stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');  $stmt->execute([                  'name'                  => $proper name ]);  foreach ($stmt                  equally                  $row) {                  // Practise something with $row                  }              

ii. Using MySQLi (for MySQL):

                $stmt = $dbConnection->set('SELECT * FROM employees WHERE proper noun = ?'); $stmt->bind_param('s', $name);                  // 's' specifies the variable type => 'string'                  $stmt->execute();  $event = $stmt->get_result();                  while                  ($row = $result->fetch_assoc()) {                  // Do something with $row                  }              

If you're connecting to a database other than MySQL, at that place is a driver-specific second selection that you tin can refer to (for example,

              pg_prepare()            

and

              pg_execute()            

for PostgreSQL). PDO is the universal option.

Correctly setting up the connectedness

Annotation that when using

              PDO            

to admission a MySQL database real prepared statements are not used by default. To fix this yous have to disable the emulation of prepared statements. An case of creating a connectedness 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 higher up example the mistake manner isn't strictly necessary, but information technology is brash to add information technology. This way the script will non stop with a

              Fatal Error            

when something goes incorrect. And it gives the developer the chance to

              catch            

whatever error(s) which are

              thrown            

every bit

              PDOExceptions.            

What is mandatory, however, is the kickoff

              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 earlier sending information technology to the MySQL server (giving a possible attacker no hazard to inject malicious SQL).

Although you can set up the

              charset            

in the options of the constructor, it'south important to note that 'older' versions of PHP (before 5.three.6) silently ignored the charset parameter in the DSN.

Caption

The SQL statement you pass to

              set up            

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 y'all want to filter on. Then when you phone call

              execute            

, the prepared statement is combined with the parameter values you specify.

The important thing hither is that the parameter values are combined with the compiled argument, not an SQL string. SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database. Then by sending the actual SQL separately from the parameters, you limit the take a chance of ending upwardly with something yous didn't intend.

Any parameters you ship when using a prepared statement will but be treated equally strings (although the database engine may practise some optimization and so parameters may terminate up as numbers too, of course). In the example above, if the

              $name            

variable contains

              'Sarah'; DELETE FROM employees            

the outcome would simply exist a search for the string

              "'Sarah'; DELETE FROM employees"            

, and you volition not terminate up with an empty table.

Some other benefit of using prepared statements is that if you execute the same statement many times in the same session information technology will only be parsed and compiled once, giving you some speed gains. Oh, and almost how to practice information technology for an insert, here'southward an example (using PDO):

                $preparedStatement = $db->gear up('INSERT INTO table (cavalcade) VALUES (:column)');  $preparedStatement->execute([                  'column'                  => $unsafeValue ]);              

Can prepared statements be used for dynamic queries?

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

For these specific scenarios, the all-time affair to practice is use a whitelist filter that restricts the possible values.

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

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

Respond:

Y'all can apply the

              strpos()            
                                        

function which is used to notice the occurrence of one string within some other one:

                $a =                  'How are y'all?';                  if                  (strpos($a,                  'are') !==                  simulated) {     echo                  'true'; }              

Annotation that the use of

              !==            

imitation is deliberate (neither

              != false            

nor

              === truthful            

will return the desired effect);

              strpos()            

returns either the offset at which the needle string begins in the haystack cord, or the boolean

              faux            

if the needle isn't found. Since 0 is a valid offset and 0 is "falsey", we can't use simpler constructs similar

              !strpos($a, 'are')            

.

Alternative Answer:

You could use regular expressions, it'southward better for give-and-take matching compared to strpos as it volition as well return true for strings such as fare, care, stare, etc. This can simply be avoided in regular expression by using word boundaries. A simple friction match for are could look something similar this:

                $a =                  'How are you lot?';                  if                  (preg_match('/\bare\b/', $a)) {     repeat                  'true'; }              

On the performance side,

              strpos            

is well-nigh iii times faster and have in listen, when we did i one thousand thousand compares at once, it took

              preg_match            

1.five seconds to finish and for

              strpos            

it took 0.5 seconds.

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

                $a =                  'How are you?'; $search =                  'are y';                  if(preg_match("/{$search}/i", $a)) {     echo                  'truthful'; }              

The

              i            

at the end of regular expression changes regular expression to exist case-insensitive, if you do not want that, you can leave information technology 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 cord that might behave similar 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 instance insensitive                  if                  (strtoupper($word)=="Due west")     {                  // if $word is "W" then word search instead of cord in cord search.                  if                  (preg_match("/\b{$needle}\b/{$i}", $haystack))          {                  render                  truthful;         }     }                  else                  {                  if(preg_match("/{$needle}/{$i}", $haystack))          {                  return                  true;         }     }                  return                  fake;                  // Put quotes around true and imitation to a higher place to return them as strings instead of as bools/ints.                  }              

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

Answer:

The MySQL extension:

1. Is not under agile development

two. Is officially deprecated as of PHP 5.5 (released June 2013).

three. Has been removed entirely as of PHP 7.0 (released Dec 2015)

  • This ways that equally of 31 Dec 2018 information technology does not exist in whatsoever supported version of PHP. If y'all are using a version of PHP which supports it, you are using a version that doesn't
    become security bug stock-still.

four. Lacks an OO interface

5. 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 v.6; required in 5.7)
  • Any of the new functionality in MySQL v.1 or later

Since it is deprecated, using it makes your lawmaking less futurity proof. Lack of support for prepared statements is especially important as they provide a clearer, less error-decumbent method of escaping and quoting external information than manually escaping information technology with a separate office phone call.

See the comparison of SQL extensions.

four. How to delete an chemical element from an array in PHP?

Respond:

At that place are unlike ways to delete an array element, where some are more than useful for some specific tasks than others.

Delete one array element

If you desire to delete just one assortment element you can use

              unset()            

or alternatively

              \array_splice()            

. Too if you have the value and don't know the key to delete the chemical element y'all can use

              \array_search()            

to get the fundamental.

i.

                              unset()                          

Note that when you use

              unset()            

the array keys won't change/reindex. If you desire to reindex the keys you tin can use

              \array_values()            

after

              unset()            

which volition catechumen all keys to numerical enumerated keys starting from 0.

Code

                                  <?php                  $array = [0                  =>                  "a",                  i                  =>                  "b",                  2                  =>                  "c"];                  unset($array[ane]);                  //↑ Key which yous want to delete                  ?>                              

Output

ii.

                              \array_splice()                          

method

If you use

              \array_splice()            

the keys will be automatically reindexed, simply the associative keys won't modify as opposed to

              \array_values()            

which will convert all keys to numerical keys.Too

              \array_splice()            

needs the offset, not the key! as the second parameter.

Lawmaking

                <?php      $array = [0                  =>                  "a",                  i                  =>                  "b",                  2                  =>                  "c"];     \array_splice($assortment,                  ane,                  1);                  //↑ Offset which y'all want to delete                  ?>              

Output

              array_splice()            

same every bit

              unset()            

have the array by reference, and this ways you don't desire to assign the return values of those functions back to the array.

Delete multiple array elements

If you desire to delete multiple array elements and don't want to phone call

              unset()            

or

              \array_splice()            

multiple times you can use the functions

              \array_diff()            

or

              \array_diff_key()            

depending on if you lot know the values or the keys of the elements which you lot want to delete.

i.

                              \array_diff()                          

method

If you know the values of the assortment elements which you want to delete, then you can utilise

              \array_diff()            

. Every bit before with

              unset()            

it won't alter/reindex the keys of the array.

Code

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

Output

2.

                              \array_diff_key()                          

method

If yous know the keys of the elements which you desire to delete, and then you want to use

              \array_diff_key()            

. Here you have to make sure you pass the keys as keys in the 2d parameter and not as values. Otherwise, y'all take to flip the array with

              \array_flip()            

. And also here the keys won't change/reindex.

Lawmaking

                                  <?php                  $array = [0                  =>                  "a",                  ane                  =>                  "b",                  2                  =>                  "c"];     $assortment = \array_diff_key($array, [0                  =>                  "xy",                  "two"                  =>                  "xy"]);                  //↑           ↑ Array keys which you lot want to delete                  ?>                              

Output

Also if yous desire to utilise

              unset()            

or

              \array_splice()            

to delete multiple elements with the aforementioned value you tin can use

              \array_keys()            

to get all the keys for a specific value then delete all elements.

five. Is there any mode 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/6/<insert-youtube-video-id-here>/0.jpg                  https://img.youtube.com/six/<insert-youtube-video-id-here>/1.jpg                  https://img.youtube.com/6/<insert-youtube-video-id-here>/2.jpg                  https://img.youtube.com/vi/<insert-youtube-video-id-hither>/3.jpg                              

The first 1 in the listing is a full-size image and others are thumbnail images. The default thumbnail image (i.eastward., one of

              1.jpg            

,

              2.jpg            

,

              three.jpg            

) is:

                https://img.youtube.com/half dozen/<insert-youtube-video-id-hither>/default.jpg                              

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

                https://img.youtube.com/vi/<insert-youtube-video-id-hither>/hqdefault.jpg                              

At that place is also a medium quality version of the thumbnail, using a URL like to the HQ:

                https://img.youtube.com/six/<insert-youtube-video-id-here>/mqdefault.jpg                              

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

                https://img.youtube.com/vi/<insert-youtube-video-id-here>/mqdefault.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 as well. Additionally, the slightly shorter hostname

              i3.ytimg.com            

works in place of

              img.youtube.com            

in the example URLs above.

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

Culling Answer:

You tin utilise YouTube Data API to remember video thumbnails, explanation, clarification, rating, statistics, and more. API version 3 requires a key*. Obtain the key and create a videos: listing request:

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

Case PHP Code

                $data = file_get_contents("https://world wide web.googleapis.com/youtube/v3/videos?primal=YOUR_API_KEY&part=snippet&id=T0Jqdjbed40"); $json = json_decode($information); var_dump($json->items[0]->snippet->thumbnails);              

Output

                object(stdClass)#five                  (5) {   ["default"]=>   object(stdClass)#6                  (3) {     ["url"]=>     string(46)                  "https://i.ytimg.com/vi/T0Jqdjbed40/default.jpg"                  ["width"]=>     int(120)     ["summit"]=>     int(ninety)   }   ["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)#viii                  (3) {     ["url"]=>     string(48)                  "https://i.ytimg.com/vi/T0Jqdjbed40/hqdefault.jpg"                  ["width"]=>     int(480)     ["tiptop"]=>     int(360)   }   ["standard"]=>   object(stdClass)#9                  (3) {     ["url"]=>     cord(48)                  "https://i.ytimg.com/vi/T0Jqdjbed40/sddefault.jpg"                  ["width"]=>     int(640)     ["superlative"]=>     int(480)   }   ["maxres"]=>   object(stdClass)#ten                  (3) {     ["url"]=>     string(52)                  "https://i.ytimg.com/vi/T0Jqdjbed40/maxresdefault.jpg"                  ["width"]=>     int(1280)     ["acme"]=>     int(720)   } }              

Not only that you need a key, you might be asked for billing data depending on the number of API requests you program to make. However, a few meg requests per day are free.

Source commodity.

6. When to apply self over $this?

Answer:

Use

              $this            

to refer to the current object. Employ

              cocky            

to refer to the current class. In other words, use

              $this->member            

for non-static members, use

              self::$fellow member            

for static members.

Here is an example of right usage of

              $this            

and

              self            

for not-static and static fellow member variables:

                <?php                                      grade                    X                  {     private $non_static_member =                  one;     private                  static                  $static_member =                  ii;                                      part                    __construct()                  {         echo $this->non_static_member .                  ' '                  . self::$static_member;     } }                  new                  X(); ?>              

Hither is an instance of wrong usage of

              $this            

and

              cocky            

for not-static and static fellow member variables:

                <?php                                      class                    10                  {     private $non_static_member =                  1;     private                  static                  $static_member =                  2;                                      office                    __construct()                  {         echo self::$non_static_member .                  ' '                  . $this->static_member;     } }                  new                  X(); ?>              

Here is an example of polymorphism with

              $this            

for member functions:

                <?php                                      form                    X                  {                                      role                    foo()                  {         echo                  'X::foo()';     }                                      function                    bar()                  {         $this->foo();     } }                                      class                    Y                    extends                    X                  {                                      part                    foo()                  {         echo                  'Y::foo()';     } }  $x =                  new                  Y(); $10->bar(); ?>              

Here is an case of suppressing polymorphic behavior past using

              cocky            

for fellow member functions:

                <?php                                      class                    10                  {                                      office                    foo()                  {         echo                  'X::foo()';     }                                      part                    bar()                  {         self::foo();     } }                                      form                    Y                    extends                    Ten                  {                                      part                    foo()                  {         echo                  'Y::foo()';     } }  $10 =                  new                  Y(); $x->bar(); ?>              

The idea is that

              $this->foo()            

calls the

              foo()            

member function of whatsoever is the verbal blazon of the current object. If the object is of

              type X            

, it thus calls

              X::foo()            

. If the object is of

              blazon 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/fellow member.php?145249-laserlight

Alternative Answer:

The keyword self does Non refer simply to the 'electric current class', at to the lowest degree not in a way that restricts you to static members. Within the context of a not-static member,

              cocky            

too provides a way of bypassing the vtable (see wiki on vtable) for the current object. But as you can use

              parent::methodName()            

to call the parents version of a office, so yous can call

              self::methodName()            

to call the current classes implementation of a method.

                                                      class                    Person                  {     private $name;      public                                      function                    __construct($proper name)                  {         $this->name = $proper name;     }      public                                      function                    getName()                  {                  return                  $this->proper name;     }      public                                      function                    getTitle()                  {                  render                  $this->getName()." the person";     }      public                                      function                    sayHello()                  {         echo                  "Hello, I'm ".$this->getTitle()."<br/>";     }      public                                      function                    sayGoodbye()                  {         echo                  "Goodbye from ".self::getTitle()."<br/>";     } }                                      course                    Geek                    extends                    Person                  {     public                                      function                    __construct($proper noun)                  {         parent::__construct($name);     }      public                                      part                    getTitle()                  {                  render                  $this->getName()." the geek";     } }  $geekObj =                  new                  Geek("Ludwig"); $geekObj->sayHello(); $geekObj->sayGoodbye();              

This will output:

Hello, I'm Ludwig the geek Cheerio from Ludwig the person
              sayHello()            

uses the

              $this            

pointer, and so the vtable is invoked to call

              Geek::getTitle()            

.

              sayGoodbye()            

uses

              self::getTitle()            

, and 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?

Respond:

Y'all can do equally following:

                ini_set('display_errors',                  '1'); ini_set('display_startup_errors',                  'ane'); error_reporting(E_ALL);              

However, this doesn't make PHP to show parse errors – the merely manner to prove those errors is to alter your php.ini with this line:

(if you don't have access to

              php.ini            

, and so putting this line in

              .htaccess            

might work as well):

                php_flag display_errors                  1                              

eight. How to write two functions that would accept a string and render if it starts with the specified character/string or ends with it?

Answer:

You can practise as given below:

                                                      function                    startsWith($haystack, $needle)                  {      $length = strlen($needle);                  return                  (substr($haystack,                  0, $length) === $needle); }                                      role                    endsWith($haystack, $needle)                  {     $length = strlen($needle);                  if                  ($length ==                  0) {                  return                  truthful;     }                  return                  (substr($haystack, -$length) === $needle); }              

Use this if you don't desire to use a regex.

Alternative Answer:

You lot can use

              substr_compare            

function to check start-with and ends-with:

                                                      role                    startsWith($haystack, $needle)                  {                  return                  substr_compare($haystack, $needle,                  0, strlen($needle)) ===                  0; }                                      office                    endsWith($haystack, $needle)                  {                  render                  substr_compare($haystack, $needle, -strlen($needle)) ===                  0; }              

9. How to make a redirect in PHP?

Answer:

i. Basic answer

Yous can utilize the

              header()            

function to send a new HTTP header, merely this must be sent to the browser before any HTML or text (then before the

              <!DOCTYPE ...>            

declaration, for case).

                header('Location: '.$newURL);              

2. Important details die() or exit()

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

Why you should use

              dice()            

or

              get out()            

: 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 onetime RFC 2616, where only absolute URLs were allowed.

Status Codes

PHP's "Location"-header still uses the HTTP 302-redirect code, just this is non the one you lot should utilise. You should consider either 301 (permanent redirect) or 303 (other).

Note: W3C mentions that the 303-header is incompatible with "many pre-HTTP/i.1 user agents. Currently used browsers are all HTTP/ane.1 user agents. This is not truthful for many other user agents similar spiders and robots.

3. Documentation

HTTP Headers and the

              header()            

function in PHP

  • What the PHP manual says
  • What Wikipedia says
  • What the W3C says

iv. Alternatives

You lot may use the culling 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);    dice(); }              

half dozen. Workaround

Every bit mentioned,

              header()            

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

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

Or a JavaScript redirect even.

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

Culling Answer:

Utilize the

              header()            

function to ship an

                                        
HTTP
              Location                          
header

:

                header('Location: '.$newURL);              

Contrary to what some call back,

              die()            

has nothing to practice with redirection. Use it only if you desire 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:

                [email protected]:~> true cat /tmp/rail.txt                  127.0                  .0                  .one                  2009                  -04                  -21T09:fifty:02+02:00                  127.0                  .0                  .one                  2009                  -04                  -21T09:50:05+02:00                  127.0                  .0                  .1                  2009                  -04                  -21T09:50:08+02:00                              

Resuming — obligatory

              dice()/exit()            

is some urban fable that has cypher to exercise with actual PHP. It has nil to practice with the client "respecting" the

              Location:            

header. Sending a header does not stop PHP execution, regardless of the client used.

x. How do you lot 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 cleft your passwords. Add to that per-password salts (

              bcrypt                          

REQUIRES salts) and you lot can exist sure that an attack is nigh 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 fundamental schedule phase of Eksblowfish ensures that any subsequent state depends on both salt and cardinal (user password), and no land can be precomputed without the knowledge of both. Considering of this key departure,

                              bcrypt                          

is a one-way hashing algorithm. You cannot think the plainly text password without already knowing the common salt, rounds, and key (password). [Source]

How to use bcrypt:

Using PHP >= 5.5-DEV

Password hashing functions have now been congenital directly into PHP >= five.5. You may now utilize

              password_hash()            

to create a

              bcrypt            

hash of whatever password:

                <?php                  // Usage 1:                  echo password_hash('rasmuslerdorf', PASSWORD_DEFAULT)."\north";                  // $2y$10$xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx                  // For example:                  // $2y$x$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a                  // Usage 2:                  $options = [                  'cost'                  =>                  eleven                  ]; echo password_hash('rasmuslerdorf', PASSWORD_BCRYPT, $options)."\n";                  // $2y$11$6DP.V0nO7YI3iSki4qog6OQI5eiO6Jnjsqg7vdnb.JgGIsxniOn4C                              

To verify a user-provided countersign against an existing hash, you may use the

              password_verify()            

as such:

                <?php                  // See the password_hash() example to run into where this came from.                  $hash =                  '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';                  if                  (password_verify('rasmuslerdorf', $hash)) {     repeat                  'Password is valid!'; }                  else                  {     repeat                  'Invalid countersign.'; }              

Using PHP >= v.3.7, < 5.5-DEV (also RedHat PHP >= 5.3.3)

There is a compatibility library on GitHub created based on the source lawmaking of the above functions originally written in C, which provides the same functionality. One time the compatibility library is installed, usage is the same every bit above (minus the shorthand assortment notation if you are nevertheless on the 5.three.x branch).

Using PHP < 5.3.7 (DEPRECATED)

You tin utilise

              crypt()            

office to generate bcrypt hashes of input strings. This class can automatically generate salts and verify existing hashes confronting an input. If you lot are using a version of PHP higher or equal to 5.3.vii, information technology is highly recommended you use the built-in part or the compat library. This culling is provided only for historical purposes.

                                                      form                    Bcrypt                  {   private $rounds;    public                                      function                    __construct($rounds =                      12                    )                  {                  if                  (CRYPT_BLOWFISH !=                  i) {                  throw                  new                  Exception("bcrypt not supported in this installation. See http://php.net/crypt");     }      $this->rounds = $rounds;   }    public                                      function                    hash($input){     $hash = catacomb($input, $this->getSalt());                  if                  (strlen($hash) >                  13)                  render                  $hash;                  return                  false;   }    public                                      role                    verify($input, $existingHash){     $hash = crypt($input, $existingHash);                  return                  $hash === $existingHash;   }    private                                      office                    getSalt(){     $salt = sprintf('$2a$%02d$', $this->rounds);      $bytes = $this->getRandomBytes(16);      $salt .= $this->encodeBytes($bytes);                  return                  $salt;   }    private $randomState;   individual                                      part                    getRandomBytes($count){     $bytes =                  '';                  if                  (function_exists('openssl_random_pseudo_bytes') &&         (strtoupper(substr(PHP_OS,                  0,                  iii)) !==                  'WIN')) {                  // OpenSSL is boring 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 >=                  'five') {           $bytes .= md5($this->randomState,                  truthful);         }                  else                  {           $bytes .= pack('H*', md5($this->randomState));         }       }        $bytes = substr($bytes,                  0, $count);     }                  return                  $bytes;   }    individual                                      office                    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) <<                  iv;                  if                  ($i >=                  16) {         $output .= $itoa64[$c1];                  break;       }        $c2 = ord($input[$i++]);       $c1 |= $c2 >>                  4;       $output .= $itoa64[$c1];       $c1 = ($c2 &                  0x0f) <<                  two;        $c2 = ord($input[$i++]);       $c1 |= $c2 >>                  half-dozen;       $output .= $itoa64[$c1];       $output .= $itoa64[$c2 &                  0x3f];     }                  while                  (true);                  return                  $output;   } }              

You tin can use this code like this:

                $bcrypt =                  new                  Bcrypt(xv);  $hash = $bcrypt->hash('countersign'); $isGood = $bcrypt->verify('countersign', $hash);              

Alternatively, you lot may too use the Portable PHP Hashing Framework.

eleven. How to use PHP to go the current year?

Respond:

You can apply either date or strftime. In this case, it doesn't matter as a twelvemonth is a year, no thing what (unless in that location'south a locale that formats the twelvemonth differently?) For example:

On a side note when formatting dates in PHP it matters when you desire to format your date in a different locale than your default. If so, you take to use setlocale and strftime. Co-ordinate to the php manual on appointment:

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

From this point of view, it would be best to utilise strftime as much as possible, if you even have a remote possibility of having to localize your application. If that'due south not an outcome, pick the i you similar best.

In Conclusion

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

This mail was start published on DevPost past Truemark .

Tags

# php# programming# coding# software-development# recruiting# hiring# interview-questions# php-is-expressionless# web-monetization

Related Stories

williamsgracep.blogspot.com

Source: https://hackernoon.com/the-heat-index-of-questions-about-php-nr1r34qx

0 Response to "What Should Be the Index Name While Uploading Something in Php"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel