Skip to content

Instantly share code, notes, and snippets.

@janbiasi
Created November 11, 2014 11:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save janbiasi/80b7b0a3f66c6b12c8e5 to your computer and use it in GitHub Desktop.
Save janbiasi/80b7b0a3f66c6b12c8e5 to your computer and use it in GitHub Desktop.
A simple PHP helper for working JSON including a short demo
<?php
// Get content from the DB
function readDatabase($path) {
return (array)json_decode(file_get_contents($path));
}
// Save content to the DB
function saveDatabase($path, $content) {
file_put_contents($path, json_encode($content));
}
// Find a user by 'username'
function findUser($username) {
$users = readDatabase('users.json');
foreach($users as $user) {
if($user->username == $username) {
return $user;
}
}
}
function addUser($user) {
$users = readDatabase('users.json');
return array_push($users, $user);
}
<?php
// Create object for user json
$new_user = array(
'username' => 'max-mustermann',
'password' => hashPassword('myPassword!')
);
// Add new user
$users = addUser($new_user);
saveDatabase('users.json', $users);
// Will dump something like 'array(2) [ object(2) => ... ]
var_dump(readDatabase('users.json'));
<?php
// Salt hash for password
define('SALT', 'Fa-N#l3atc3q%^jhgxjgFwwy-!BwR%7(M)Z#N2TA');
// Hash a password (algorhytm)
function hashPassword($pass) {
return sha1($pass . md5(SALT . $pass));
}
[
{
username: "admin",
password: "testpw"
},
{
username: "tanner",
password: "testpw2"
}
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment