Created
November 11, 2014 11:54
-
-
Save janbiasi/80b7b0a3f66c6b12c8e5 to your computer and use it in GitHub Desktop.
A simple PHP helper for working JSON including a short demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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')); | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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)); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[ | |
{ | |
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