Getting API response with authentication

Oftentimes, file_get_contents() function comes really handy when we are trying to pull data from an API. We can simply do it by doing this:

$json_data = file_get_contents('http://theurl.com/api/json');

But what if the API requires authentication? Then, you’ll need a way to communicate with the authenticated server or else the server will give you this response.

Warning: file_get_contents(http://www.yourdomain.com/file.php): failed to open stream: HTTP request failed! 
HTTP/1.1 401 Authorization Required in file.php on line 7

In order to avoid that, first we need a way to add the username and password to the HTTP header in the request. We can simply use the stream_context_create() function.

Next is to use that stream context in the file_get_contents() function as the third parameter. As for the second parameter, just simply use false or 0 to skip it.


$username = 'theusername';
$password = 'thepassword';

$context = stream_context_create(array(
  'http' => array(
    'header' => "Authorization: Basic " . base64_encode("$username:$password")
  )
));

$json_data = file_get_contents('https://theurl.com/api/json', false, $context);

http://www.hashbangcode.com/blog/using-authentication-and-filegetcontents

Dealing with currency, commas and decimals in PHP

If you are dealing with money on your code, you must know how to display comma when it reaches a thousand or million or billion and so on. You also need to handle the decimal places. Money usually have only 2 decimal places. If the money is a whole number, you still need to add 2 zeroes as decimals.

Good news! PHP has a built-in function that can do this for you. All you have to do is to call number_format

Example 1:

$number = 123456789.12345;
echo number_format($number, 2);

Output 1:

123,456,789.12

Example 2:

$number = 9876;
echo number_format($number, 2);

Output 2:

9,876.00

Protocol Relative URLs

As I was developing an audio player and creating its embed code, I learned that you can use 2 forward slashes as a shorthand whether a file could be loaded from either an http or https protocol. This shorthand is commonly known as protocol relative URLs.

The browser appends the right protocol in front of the URL.

For example,

//example.com/mycss.css

As I was telling earlier, it would prepend the right protocol into this https://example.com/mycss.css

So next time, if you want to load up a URL but not quite sure as to what protocol to use, you can just simply use the shorthand — 2 forward slashes.

Lesson Learned! MySQL UPDATE and SELECT

Most SQL servers’ UPDATE and SELECT query statements are like these:

UPDATE
    t1
SET
    t1.column1 = t2.column1
FROM
    table1 AS t1
INNER JOIN table2 AS t2

BUT in MySQL, SET is at the last part of the query.

UPDATE 
     table1 AS t1
INNER JOIN table2 AS t2
     ON t1.id = t2.id
SET 
    t1.column1 = t2.column1