Skip to content
Create a gist now

Instantly share code, notes, and snippets.

Embed URL


Subversion checkout URL

You can clone with
Download ZIP
Useful PHP Techniques
* An example CORS-compliant method. It will allow any GET, POST, or OPTIONS requests from any
* origin.
* In a production environment, you probably want to be more restrictive, but this gives you
* the general idea of what is involved. For the nitty-gritty low-down, read:
* -
* -
function cors() {
// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
// Access-Control headers are received during OPTIONS requests
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
echo "You have CORS!";
* This demonstrates a handy way to process a CSV file.
* - The first line of the CSV file is assumed to be a header line, which defines the name and order of the fields
* - Each subsequent line of the file will be turned into an array
* - Lines that are improperly formatted (ie: a different number of items than the header) are ignored.
* - Each line of data is converted into an associative array. The name of each field is taken from the header line.
* - The names of the fields are significant, but the order is not.
function processCsvFile($input, $callable) {
$columns = fgetcsv($input);
if ($columns === false)
while( ($line = fgetcsv($input)) !== false ) {
$line = @array_combine($columns, $line);
if ($line !== false)
// You could consume STDIN as a CSV file and output each line as an array like so.
processCsvFile(STDIN, function ($ar) { print_r($ar); });
class Docreader extends CI_Controller {
private $secret = 'aADFj98333(*&9jfa;';
* This controller will share documents, but only with people who hold a temporary URL that
* grants them access. The format of the url is:
* Example:
* @param string $docid The id of the document to server (very application-specific)
* @param int $expiration When the templink will expire
* @param string $signature The HMAC-MD5 signature
public function templink($docid, $expiration, $signature) {
$computedSignature = $this->generateSignature($docid, $expiration);
if ($expiration <= time() && $signature == $computedSignature) {
// serve the document
} else {
// send an error
* The signature is simply an HMAC of $docid '/' $expiration
* @param string $docid The identifier you are using for the serveable document
* @param int $expiration The unix time at which the link will expire
private function generateSignature($docid, $expiration) {
return hash_hmac("md5", "$docid/$expiration", $this->secret);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.