PHP file_get_contents with HTTP Basic Auth

Today I needed to figure out how to read some data from a URL that required HTTP Basic Auth. The solution was pretty simple, use file_get_contents and pass in a configured stream context. I found the following code on the stream_context_create documentation:

$cred = sprintf( 'Authorization: Basic %s',
  base64_encode( 'username:password' )
);
$opts = array(
  'http' => array(
    'method' => 'GET',
    'header' => $cred
  )
);
$ctx = stream_context_create( $opts );
$data = file_get_contents( $url, false, $ctx );

Easy-peasy!

PHP Traits and Grafts

Reading about traits and grafts in PHP: Request for Comments: Horizontal Reuse for PHP, PHP Traits, Using Traits in PHP 5.4 and PHP Traits: Good or Bad?. They mentioned the Diamond Problem.

I learned some new syntax too! E.g.:

 return $_instance ?: $_instance = new $class;

The ternary operator as a ‘binary’ operator! Cool! See here for details: Since PHP 5.3, it is possible to leave out the middle part of the ternary operator.

PHP PDO MySQL Blob

Read PHP MySQL BLOB today to learn how to work with BLOBs. Basically:

public function insertBlob($filePath,$mime){
    $blob = fopen($filePath,'rb');
 
    $sql = "INSERT INTO files(mime,data) VALUES(:mime,:data)";
    $stmt = $this->conn->prepare($sql);
 
    $stmt->bindParam(':mime',$mime);
    $stmt->bindParam(':data',$blob,PDO::PARAM_LOB);
 
    return $stmt->execute();
}

function updateBlob($id,$filePath,$mime) {
 
    $blob = fopen($filePath,'rb');
 
    $sql = "UPDATE files
            SET mime = :mime,
            data = :data
            WHERE id = :id";
 
    $stmt = $this->conn->prepare($sql);
 
    $stmt->bindParam(':mime',$mime);
    $stmt->bindParam(':data',$blob,PDO::PARAM_LOB);
    $stmt->bindParam(':id',$id);
 
    return $stmt->execute();
 
}

public function selectBlob($id) {
 
    $sql = "SELECT mime,
            data
        FROM files
        WHERE id = :id";
 
    $stmt = $this->conn->prepare($sql);
    $stmt->execute(array(":id" => $id));
    $stmt->bindColumn(1, $mime);
    $stmt->bindColumn(2, $data, PDO::PARAM_LOB);
 
    $stmt->fetch(PDO::FETCH_BOUND);
 
    return array("mime" => $mime,
             "data" => $data);
 
}