Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Wednesday, 16 August 2017

How to use Use isset() Instead of strlen()

How to use Use isset() Instead of strlen()


This is truly a neat trick, though the previous article utterly fails to clarify it. Here is that the missing example:

<?php

if (isset($username[5])) {
    // The username is at least six characters long.
}

?>

When you treat strings as arrays, every character within the string is a component within the array. By determinant whether or not a selected component exists, you'll confirm whether or not the string is a minimum of that several characters long. (Note that the primary character is component zero, therefore $username[5] is that the sixth character in $username.)

The reason this is often slightly quicker than strlen() is difficult. the easy clarification is that strlen() may be a operate, and isset() may be a language construct. usually speaking, business a operate is dearer than employing a language construct.

Tuesday, 15 August 2017

How to use the Suppression Operator Correctly

How to use the Suppression Operator Correctly

Always try to avoid using the error suppression operator. In the previous article, the author states:

The @ operator is rather slow and can be costly if you need to write code with performance in mind.

Error suppression is slow. this is often as a result of PHP dynamically changes error_reporting to zero before corporal punishment the suppressed statement, then like a shot changes it back. this is often costly.

Worse, exploitation the error suppression operator makes it tough to trace down the basis reason for a haul.

The previous article uses the subsequent example to support the apply of assignment a variable by reference once it's unknown if $albus is set:

<?php

$albert =& $albus;

?>

Although this works — for now — relying on strange, unsupported behavior while not a really smart understanding of why it works may be a great way to introduce bugs. as a result of $albert is appointed to $albus by reference, future modifications to $albus will modify $albert.

A much higher resolution is to use isset(), with braces:

<?php

if (!isset($albus)) {
    $albert = NULL;
}

?>

Assigning $albert to NULL is that the same as assignment it to a nonexistent reference, however being specific greatly improves the clarity of the code and avoids the denotative  relationship between the 2 variables.

If you inherit code that uses the error suppression operator too, we’ve got a bonus tip for you. there's a replacement PECL extension known as Scream that disables error suppression.

Friday, 11 August 2017

How to use Shortcut of else

How to use Shortcut of else

This tip accidentally stumbles upon a helpful apply, that is to continually initialize variables before you utilize them. take into account a conditional statement that determines whether or not a user is Associate in Nursing administrator supported the username:

<?php

if (auth($username) == 'admin') {
    $admin = TRUE;
} else {
    $admin = FALSE;
}

?>

This appears safe enough, as a result of it’s straightforward to grasp at a look. Imagine a rather additional elaborate example that sets variables for name and email moreover, for convenience:

<?php

if (auth($username) == 'admin') {
    $name = 'Administrator';
    $email = 'admin@example.org';
    $admin = TRUE;
} else {
    /* Get the name and email from the database. */
    $query = $db->prepare('SELECT name, email
                           FROM   users
                           WHERE  username = :username');
    $query->execute(array('username' => $clean['username']));
    $result = $query->fetch(PDO::FETCH_ASSOC);
    $name = $result['name'];
    $email = $result['email']; 
    $admin = FALSE;
}


?>

Because $admin remains continually expressly set to either TRUE or FALSE, all is well, however if a developer later adds associate elseif, there’s a chance to forget:

<?php

if (auth($username) == 'admin') {
    $name = 'Administrator';
    $email = 'admin@example.org';
    $admin = TRUE;
} elseif (auth($username) == 'mod') {
    $name = 'Moderator';
    $email = 'mod@example.org';
    $moderator = TRUE;
} else {
    /* Get the name and email. */
    $query = $db->prepare('SELECT name, email
                           FROM   users
                           WHERE  username = :username');
    $query->execute(array('username' => $clean['username']));
    $result = $query->fetch(PDO::FETCH_ASSOC);
    $name = $result['name'];
    $email = $result['email']; 
    $admin = FALSE;
    $moderator = FALSE;
}

?>

If a user provides a username that triggers the elseif condition, $admin is not initialized. This can lead to unwanted behavior, or worse, a security vulnerability. Additionally, a similar situation now exists for $moderator, which is not initialized in the first condition.


By first initializing $admin and $moderator, it’s easy to avoid this scenario altogether:

<?php

$admin = FALSE;
$moderator = FALSE;

if (auth($username) == 'admin') {
    $name = 'Administrator';
    $email = 'admin@example.org';
    $admin = TRUE;
} elseif (auth($username) == 'mod') {
    $name = 'Moderator';
    $email = 'mod@example.org';
    $moderator = TRUE;
} else {
    /* Get the name and email. */
    $query = $db->prepare('SELECT name, email
                           FROM   users
                           WHERE  username = :username');
    $query->execute(array('username' => $clean['username']));
    $result = $query->fetch(PDO::FETCH_ASSOC);
    $name = $result['name'];
    $email = $result['email'];
}

?>

Regardless of what the remainder of the code will, it’s currently clear that $admin is fake unless it's expressly set to one thing else, and also the same is true for $moderator. This conjointly hints at another smart security apply, that is to fail safely. The worst that may happen as a results of not modifying $admin or $moderator in associate degreey of the conditions is that somebody United Nations agency is an administrator or moderator isn't treated mutually.

If you wish to route one thing, associate degreed you’re feeling to a small degree thwarted that our example includes an else, we've a bonus tip which may interest you. We’re not sure it will be thought-about a route, however we have a tendency to hope it’s useful notwithstanding.

Consider a operate that determines whether or not a user is allowed to look at a selected page:

<?php
 
function authorized($username, $page) {
    if (!isBlacklisted($username)) {
        if (isAdmin($username)) {
            return TRUE;
        } elseif (isAllowed($username, $page)) {
            return TRUE;
        } else {
            return FALSE;
        }
    } else {
        return FALSE;
    }
}
 
?>

This example is really pretty easy, as a result of there area unit solely 3 rules to consider: directors area unit forever allowed access; people who area unit blacklisted area unit ne'er allowed access; and isAllowed() determines whether or not anyone else has access. (A special case exists once associate administrator is blacklisted, however that's associate unlikely chance, therefore we’re ignoring it here.) we have a tendency to use functions for the foundations to stay the code easy and to specialise in the logical structure.

There area unit varied ways in which this instance will be improved. If you wish to scale back the amount of lines, a compound conditional will help:

<?php
 
function authorized($username, $page) {
    if (!isBlacklisted($username)) {
        if (isAdmin($username) || isAllowed($username, $page)) {
            return TRUE;
        } else {
            return FALSE;
        }
    } else {
        return FALSE;
    }
}
 
?>

In fact, you can reduce the entire function to a single compound conditional:

<?php
 
function authorized($username, $page) {
    if (!isBlacklisted($username) && (isAdmin($username) || isAllowed($username, $page)) {
        return TRUE;
    } else {
        return FALSE;
    }
}
 
?>

Finally, this can be reduced to a single return:

<?php
 
function authorized($username, $page) {
    return (!isBlacklisted($username) && (isAdmin($username) || isAllowed($username, $page));
}
 
?>

If your goal is to reduce the number of lines, you’re done. However, note that we’re using isBlacklisted(), isAdmin(), and isAllowed() as placeholders. Depending on what’s involved in making these determinations, reducing everything to a compound conditional may not be as attractive.

This brings us to our tip. A return immediately exits the function, so if you return as soon as possible, you can express these rules very simply:

<?php
 
function authorized($username, $page) {
 
    if (isBlacklisted($username)) {
        return FALSE;
    }
 
    if (isAdmin($username)) {
        return TRUE;
    }
 
    return isAllowed($username, $page);
}
 
?>

This uses a lot of lines of code, however it’s terribly straightforward and unimposing (we’re proudest of our code once it’s the smallest amount impressive). a lot of significantly, this approach reduces the quantity of context you want to continue with. for instance, as presently as you’ve determined whether or not the user is blacklisted, you'll be able to safely ignore it. this can be significantly useful once your logic is a lot of difficult.

Thursday, 10 August 2017

Know the Difference Between Comparison Operators

Know the Difference Between Comparison Operators

This is a decent tip, however it's missing a sensible example that demonstrates once a non-strict comparison will cause issues.

If you employ strpos() to see whether or not a substring exists at intervals a string (it returns FALSE if the substring isn't found), the results may be misleading:

<?php

$authors = 'Chris & Sean';

if (strpos($authors, 'Chris')) {
    echo 'Chris is an author.';
} else {
    echo 'Chris is not an author.';
}

?>

Because the substring Chris happens at the terribly starting of Chris &amp; Sean, strpos() properly returns zero, indicating the primary position within the string. as a result of the conditional statement treats this as a Boolean, it evaluates to FALSE, and also the condition fails. In alternative words, it's like Chris isn't associate degree author, but he is!


This can be corrected with a strict comparison:


<?php

if (strpos($authors, 'Chris') !== FALSE) {
    echo 'Chris is an author.';
} else {
    echo 'Chris is not an author.';
}


?>


Tuesday, 8 August 2017

How to Use an SQL Injection

How to Use an SQL Injection

This tip is just a link to a useful resource with no discussion on how to use it. Studying several permutations of a specific attack can be useful, but your time is spent better learning to protect against it. In addition, there is much more in Web application security than in SQL injection. XSS (Cross-Site Scripting) and CSRF (Cross-Site Request Forgeries), for example, are at least as common and at least as dangerous.We can provide a much needed context, but because we do not want to focus too much on an attack, we will first take a step back. Every developer should be familiar with good security practices, and applications should be designed with these practices in mind. A fundamental rule is to never trust the data you get from somewhere else. Another rule is to escape data before sending it to another location. Combined, these rules can be simplified to form a basic safety principle: filter inlet, exhaust outlet (FIEO).The root cause of SQL injection is a failure to exit the output. More specifically, it is when the distinction between the format of an SQL query and the data used by the SQL query is not carefully maintained. This is common in PHP applications that construct queries as follows:


<?php

$query = "SELECT *
          FROM   users
          WHERE  name = '{$_GET['name']}'";
         
?>


In this case, the value of $_GET[‘name’] is provided by another source, the user, but it is neither filtered nor escaped.

Escaping preserves data in a new context. The emphasis on escaping output is a reminder that data used outside of your Web app needs to be escaped, else it might be misinterpreted. By contrast, filtering ensures that data is valid before it’s used. The emphasis on filtering input is a reminder that data originating outside of your Web app needs to be filtered, because it cannot be trusted.

Assuming we’re using MySQL, the SQL injection vulnerability can be mitigated by escaping the name with mysql_real_escape_string(). If the name is also filtered, there is an additional layer of security. (Implementing multiple layers of security is called “defense in depth” and is a very good security practice.) The following example demonstrates filtering input and escaping output, with naming conventions used for code clarity:

<?php

// Initialize arrays for filtered and escaped data, respectively.
$clean = array();
$sql = array();

// Filter the name. (For simplicity, we require alphabetic names.)
if (ctype_alpha($_GET['name'])) {
    $clean['name'] = $_GET['name'];
} else {
    // The name is invalid. Do something here.
}

// Escape the name.
$sql['name'] = mysql_real_escape_string($clean['name']);

// Construct the query.
$query = "SELECT *
          FROM   users
          WHERE  name = '{$sql['name']}'";

?>

Although the use of naming conventions can help you keep up with what has and hasn’t been filtered, as well as what has and hasn’t been escaped, a much better approach is to use prepared statements. Luckily, with PDO, PHP developers have a universal API for data access that supports prepared statements, even if the underlying database does not.

Remember, SQL injection vulnerabilities exist when the distinction between the format of an SQL query and the data used by the SQL query is not carefully maintained. With prepared statements, you can push this responsibility to the database by providing the query format and data in distinct steps:

<?php

// Provide the query format.
$query = $db->prepare('SELECT *
                       FROM   users
                       WHERE  name = :name');

// Provide the query data and execute the query.
$query->execute(array('name' => $clean['name']));

?>

The PDO manual page provides more information and examples. Prepared statements offer the strongest protection against SQL injection.

Wednesday, 8 March 2017

How to import excel file into mysql using php

With the help of php we can easily import our excel or csv file data in our Mysql database.
So i am going to show you some methods doing this easily

How to import excel file into mysql using php

To import excel data into php-mysql records first create a table with required fields. Make database connection. Open excel file and read columns one by one and store in variables.


Method-1: Import excel data using php script

$handle = fopen("BooksList.csv", "r");
while (($data = fgetcsv($handle)) !== FALSE) {
$num = count($data);
$row;
echo "INSERT into importing(text,number)values('$data[0]','$data[1]')";
echo "<br>";
}


Method-2:

$handle = fopen("BooksList.csv", "r");
$fields=array('category','datatype','date','value');
$table='test';
$sql_query = "INSERT INTO $table(". implode(',',$fields) .") VALUES(";
while (($data = fgetcsv($handle)) !== FALSE) {
    foreach($data as $key=>$value) {
            $data[$key] = "'" . addslashes($value) . "'";
        }
           $rows[] = implode(",",$data);
  }
$sql_query .= implode("),(", $rows);
$sql_query .= ")";
echo $sql_query;


Method:3 Using third party library like php-excel-reader

Download form http://code.google.com/p/php-excel-reader/downloads/list

require_once 'Excel/reader.php'; 
$data = new Spreadsheet_Excel_Reader();
$data->setOutputEncoding('CP1251');
$data->read('BooksList.xls');
for ($x = 2; $x<=count($data->sheets[0]["cells"]); $x++) {
    $name = $data->sheets[0]["cells"][$x][1];
    $extension = $data->sheets[0]["cells"][$x][2];
    $email = $data->sheets[0]["cells"][$x][3];
    $sql = "INSERT INTO mytable (name,extension,email) VALUES ('$name',$extension,'$email')";
    echo $sql."\n";
    echo "<br>";
 }

Hope this will help you to import your excel file into mysql db.
Thanks :)

Tuesday, 7 March 2017

How to upload file in cakephp without refersh page

Change image without refresh page in php and jquery, Upload file without refresh page in cakephp and jquery


Here we are going discuss about how to upload image or file without refresh page in cakephp and jquery.

Create controller in cakephp

ProfilesController.php

class ProfilesController extends AppController {
var $name = 'Profiles';
public $uses = array('Profile');
function changeprofilephoto() {
$profile_id = “14”; //
$path = "../../app/webroot/profilepic/";//set path
$valid_formats = array(".jpg", ".png", ".gif", ".bmp", ".jpeg");//
if($this->data)
{
$this->Profile->set( $this->data );
$name = $this->data["Profile"]['profile_pic']['name'];
$size = $this->data["Profile"]['profile_pic']['size'];
if(strlen($name))
{
$fileExt = substr(strrchr($name, '.'), 0);
if(in_array($fileExt,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = strtotime(date('Y-m-d H:i:s')).$fileExt;
$tmp = $this->data["Profile"]['profile_pic']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
$this->Profile->set($this->data);
$this->Profile->id=$profile_id;
$this->Profile->saveField('uploadfoldername',$actual_image_name);
echo "<img src='/profilepic/".$actual_image_name."' class='preview'>";
$this->Session->write('suc','1');
$this->redirect($_SERVER['HTTP_REFERER']);
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
} else
echo "Please select image..!";
exit;
}
}
}


Create view file

Views/Profiles/changeprofilephoto.ctp

 <?php
echo $this->Html->script('jquery.min.js');
echo $this->Html->script('jquery.form.js');
?>

<script type="text/javascript" >
$(document).ready(function() {
$('#profile_pic').live('change', function(){
$("#preview").html('');
$("#preview").html('<img src="../img/loader.gif" alt="Uploading...."/>');//download loding image
$("#Profile").ajaxForm({
target: '#preview'
}).submit();
});
});
</script>
<style>
.preview
{
width:200px;
border:solid 1px #dedede;
padding:10px;
}
#preview
{
color:#cc0000;
font-size:12px
}
</style>
<div class="layout-popup f-left">
<?php
echo $this->Form->create('Profile',array('id'=>'Profile', 'controller'=>'Profiles','action'=>'changeprofilephoto', 'type'=>'file'));
?>


<!-- start id-form -->
<table class="frm-tbl" id="id-form" >
<tr>
<td colspan="2" class="align-t-r" >
<div class="f-left popup-title">Change profile image</div>
</td>
</tr>
<tr>
<td>Upload your image</td>
<td align="left" >
<!-- <input type="file" name="[Profile][photoimg]" id="profile_pic" /> -->
<?php echo $form->file('profile_pic', array('id'=>'profile_pic', "label" => false, "div"=>false, 'class'=>'styled-input-big'))?>
</td>
</tr>
<tr>
<td colspan="2">
<div id='preview'>
</div>
</td>
</tr>
</table>
<?php
echo $this->Form->end();
?>
</div>

Thanks cheers :)

Monday, 6 March 2017

How to create dynamic XML sitemap and submit to google web master for indexing


In this tutorial I’ll tell you very important method to generate dynamic xml sitemap for your website and how can we indexed all our dynamic url in google search.

Every body wants to create website now days and generate some traffic fast. So this is the trick for smart geeks, The below script is tested by me and worked great for me.

Let me tell you my experience, I had aprox 2 lakh dynamic urls which i created from my database rocords and i want to index all urls in google search, So i have created a php script which pull records from database and create a dynamic url for each records.

Suppose we have a books table with their name and auther.

ID NAME                 AUTHOR
1 Book Name-1 Book Author-1
2 Book Name-2 Book Author-2
3 Book Name-3 Book Author-3

My task is to index all my books url with their author name in google search, so that if anybody is looking for same books then he can find me in google search. Google automatically crawl urls but if you want fast result then give it try.

Create file sitemap.php and paste below script after that upload your sitemap.php file in your project root directory, Your sitemap url will be http://www.example.com/sitemap.php

You can make changes in below script according to your need this is just for demonstration purpose.

sitemap.php

<?php
  header('Content-type: application/xml');
  $baseurl = "http://example.com/books/";
  $hostname = "localhost";
$username = "username";
$password = "password";
$dbname = "booksdb";
$con = mysqli_connect($hostname, $username, $password, $dbname);

 function clean($string) {
   $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.

   return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
}

  $output = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
  $output .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
  echo $output;
?>
  <?php $query = "SELECT name, author, id FROM books WHERE  status=1 LIMIT 0, 50000";
    $result = mysqli_query($con, $query);
    $res = array();

    while($resultSet = mysqli_fetch_assoc($result)) { 

 if(!empty($resultSet['name'])) { ?>

<url>
  <loc><?php echo $baseurl.clean(trim($resultSet['name'])).'/'. clean(trim($resultSet['author'])).'/'.$resultSet['id']; ?></loc>
</url>
<?php }  } ?>
</urlset>

Now time to submit your xml sitemap to google web master.

Login into your google web master account and submit your site map.


How to create dynamic XML sitemap and submit to google web master for indexing


If you don’t know how to submit sitemap in google web master please follow this tutorial.




Thursday, 2 March 2017

How to Quickly Extract Domain Name & it’s components from URL in PHP


In this quick tutorial, I am going to show you How to Quickly Extract Domain Name & it’s components from URL in PHP, In some cases of development you need to extract host name and it’s parameter individually, For parsing domain name you can simply use php parse_url function to extract domain name, It’ll not only return domain but also Parse the whole URL and return its components in associative array format.

See example below

$url =  'http://html-css-designing-tips.blogspot.com/page/?id=1&name=php';
var_dump(parse_url($url));

OutPut:

array(4) { ["scheme"]=> string(4) "http" ["host"]=> string(15) "html-css-designing-tips.blogspot.com" ["path"]=> string(13) "/page/" ["query"]=> string(15) "id=1&name=php" }

Extract Domain Name

$url =  'http://html-css-designing-tips.blogspot.com/page/?id=1&name=php';
$result = parse_url($url);
echo $result['host']; // output: html-css-designing-tips.blogspot.com


How to parse XML in PHP – simpleXML

How to parse XML in PHP – simpleXML

Many websites on internet like to share their feed in XML format so that other website owner can show that feed on his/her website / blog. In PHP there is a function called simpleXML can simplify the process of reading the feeds into something useful for your web pages.

If You have wordpress installed in your server you can also on Rss feed of your blog and share your news/ articles with other websites. this will increase your blog visibility and good for SEO also.
See tutorial: Read RSS feed of website (blog) using php


Here is sample xml file.

companydb.xml

<?xml version='1.0'?>
<companydb>
  <company>
        <name>IAMROHIT</name>
        <city>Dellhi</city>
        <phone>0000000</phone>
  </company>
    <company>
        <name>IAMROHIT</name>
        <city>Dellhi</city>
        <phone>0000000</phone>
  </company>
</companydb>


With simpleXML, it’s as easy reading the XML file and then accessing it’s contents by an easy to read object. Suppose we have our XML file above saved as a file called comopanydb.xml with all the company details in the same folder as our php file, we can read the whole xml feed by following php function.

 $companydb = simplexml_load_file('companydb.xml');

Now we have created file object, go next for accessing it’s content. like if you want to display the name of the all companies then use below code.

<?php
    $companydb = simplexml_load_file('companydb.xml');
    foreach ($companydb as $company) {
        echo $title=$company->name." - ".$company->city." - ".$company->phone."<br/>";      
  } 
?>

Above is the quick example for parsing xaml data in php, you can store you data in xml file and access with this method.

Wednesday, 1 March 2017

How to create custom component in cakephp

How to create custom component in cakephp



In this tutorial we are going to write our own hello world component (plugin) in CakePHP.

The component is a logic container in CakePHP (ex. plugin in WordPress). All just needed is, include it and utilize those functions in that component. If some CakePHP developers want share their programming logic or functionality with fellow CakePHP developers, they will write as a component and share it with their programming community.

Once your Cakephp installation, database connections and security salt setting everything done. We are now able write our first hello world CakePHP component.


Step 1:

I am going to create component in the name of muni i.e. MuniComponent

To create your CakePHP component all you needed is to create php file in the follwoing directory. That’s app/controller/component/MuniComponent.php

Every component class we are creating must extends base component class that’s in the CakePHP library folder (lib/Cake/Controller/Component.php). So first in the component import component class.

App::uses('Component', 'Controller');

Where Controller – Indicates folder name
Component — Indicates class name we are including in the file.


Now create Component class, and write hello() function that returns ‘hello world’ string.

<?php 

App::uses('Component', 'Controller');

class MuniComponent extends Component {

    // hello world function
public function hello() {
return 'hello world';
}
}

?>

That’s it you successfully created your first hello world compnont in CakePHP, so any one use your component in their application .i.e. controller.

Step 2:


Now we are going to use the componenet(MuniComponent) just we written now. So I am going use this component in my UsersController. Before use any component in a controller, we must include it in a controller.

public $components = array('Muni');

Now I am going use hello() function of the component in the Controller, which going to return ‘hello world’ string.

<?php

App::uses('Controller', 'Controller');

class UsersController extends Controller{

//include component you want to use
public $components = array('Muni');

public function index()
{
$this->layout = 'common';
//calling component function we written
$data = $this->Muni->hello();
$this->set( 'data', $data);
}
}
?>


I have added one more function in the MuniComponent, that’s passwordGenerator() function which going to return random password when we are going to call it.

// password generator function
public function passwordGenerator( $length = 10){
    $letters ="@#$%^&*()_-+<>':,.1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    return substr(str_shuffle($letters), 0, $length);
}

In controller

//calling password generator function of component
$pass = $this->Muni->passwordGenerator(20);
$this->set( 'pass', $pass);

Tuesday, 28 February 2017

Date Format Validation in PHP

How can you validate date format in php using Regex and without Regex using simple php date function. If you are working on any application where right data format is mandatory then you must have to apply right data format validation on server side so that you can easily calculate taken duration for any task.


Date Format Validation in PHP



Going to validate this format YYYY-MM-DD

Date Format Validation using Regex


function validateDate($data) {
if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/",$date))
    {
        return true;
    }else{
        return false;
    }
}

var_dump(validateDate("2017-02-27")) // true
var_dump(validateDate("27-02-2017")) // false
var_dump(validateDate("2017-14-27")) // false



Date Format Validation using PHP Date object


function validateDate($date)
{
    $dt = DateTime::createFromFormat('Y-m-d', $date);
    return $dt && $dt->format('Y-m-d') === $date;
}
var_dump(validateDate("2017-02-27")) // true
var_dump(validateDate("27-02-2017")) // false
var_dump(validateDate("2017-14-27")) // false

HTML APIs: What They Are And How To Design A Good One

As JavaScript developers, we regularly forget that not everybody has a similar data as USA. It’s referred to as the curse of knowledge:...