Tag Archives: tip

PHP read POST json data

Imagine you have a webhook on your server and someone sends a JSON body POST to it.

The data is not available in the global $_REQUEST or $_POST variables as you’d expect.

To access the JSON data you’ll need to get the POST’s RAW DATA:

1
2
3
<?php
$postData = file_get_contents("php://input"); // <-- eg: {"key":1, "key2":2}
$arr_data = json_decode($postData, true); // <-- array('key1' => 1, 'key2' => 2)

More on this: http://us.php.net/manual/en/wrappers.php.php#wrappers.php.input

Validate emails the PHP 5 way

Forget the numerous regex’s, if you’re using PHP5 (i hope 99% of you do…), just use PHP’s native filter_var function:

1
2
3
4
5
6
7
8
9
function is_email_valid($email) {
  return filter_var(filter_var($email, FILTER_SANITIZE_EMAIL), FILTER_VALIDATE_EMAIL);
}

if (is_email_valid('email@example.com')) {
  /* yeah! we've got a valid email address */
} else {
  /* oh noes! invalid email */
}