Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class Database extends PDO {
- /* Show error messages */ public $debug = true;
- /* Die on error */ public $doe = true;
- /* Sleep on error */ public $soe = false;
- /* Default credentials ( if you just wanna go $x = new Database; ) [ it can be overrided by providing the creds ] { The array keys Must be present } */
- public $creds = array( /* If you want to remove these from here, set them as NULL */
- "host" => 'database_host',
- "user" => 'database_user',
- "pass" => 'database_pass',
- "name" => 'database_name',
- );
- /* Initiate the connection */
- /* EG: $pdo = new myPDO('127.0.0.1', 'root', null, 'xxxx'); */
- public function __construct($host = false, $user = false, $pass = false, $name = false) {
- foreach($this->creds as $i => $u)
- if(${$i} !== false) $this->creds[$i] = ${$i};
- try { parent::__construct("mysql:host={$this->creds["host"]};dbname={$this->creds["name"]};charset=utf8", $this->creds["user"], $this->creds["pass"]); }
- catch (PDOException $e) { $this->exception("Error connecting to database" . ( $this->debug ? ": {$e->getMessage()}" : ".") ); };
- $this->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
- $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
- }
- /* Insert data derp */
- /* EG: $link->insert("users", array("username" => "nigel_finch", "password" => $link->hash("cunningham1"))); */
- public function insert($table = "users", $values = array()) {
- $query = "insert into `{$table}`(`" . implode("`, `", array_keys($values)) . "`) values(:" . implode(", :", array_keys($values)) . ");";
- $this->query($query, $values);
- }
- /* Execute a query ( with the ability to use prepared statements */
- /* EG: $link->query("select * from `users`;"); */
- /* EG: $link->query("select * from `users` where `x`=:furrypowa;", array(":furrypowa" => "y")); */
- public function query($query, $bind = array(), $force = false) {
- if(empty($bind) && $force == false) {
- try { $result = parent::query($query); } catch (PDOException $e)
- { $this->exception("Error in SQL query: {$e->getMessage()}"); };
- } else {
- try {
- $result = $this->prepare($query);
- foreach($bind as $key => &$val)
- $result->bindParam($key, $val);
- $result->execute();
- } catch (PDOException $e) {
- $this->exception("Error in SQL query: {$e->getMessage()}");
- };
- };
- return $result;
- }
- /* As the name states, fetch an array of values */
- /* EG: $link->fetch_array("select * from `users`;"); */
- /* EG: $link->fetch_array("select * from `users` where `x`=:furrypowa;", array(":furrypowa" => "y")); */
- public function fetch_array($query, $bind = array(), $return = array()) {
- $query = $this->query($query, $bind);
- if(method_exists($query, "fetch"))
- while($row = $query->fetch(PDO::FETCH_ASSOC))
- $return[] = $row;
- return $return;
- }
- /* Get a certain column from a query */
- /* EG: $link->get("count(*)", "select count(*) from `users`;"); */
- /* EG: $link->get("username", "select `username` from `users` where `x`=:furrypowa;", array(":furrypowa" => "y")); */
- public function get($col, $query, $bind = array()) {
- $return = $this->fetch_array($query, $bind);
- return isset($return[0][$col]) ? $return[0][$col] : false;
- }
- /* Cause some kids just can't work it out */
- public function insert_id() { return $this->lastInsertId(); }
- /* For the people who like to go old school */
- /* EG: $link->query("select * from `users` where `x`='{$link->sanatize('NIG\'":E<<')}';"); */
- public function sanatize($data) {
- if(is_array($data)) return array_map(array($this, "sanatize"), $data);
- if(function_exists("mb_convert_encoding"))
- $data = @mb_convert_encoding($data, "UTF-8", "auto");
- return substr($this->quote($data), 1, -1);
- }
- public function xss($data) {
- if(is_array($data)) return array_map(array($this, "sanatize"), $data);
- if(function_exists("mb_convert_encoding"))
- $data = @mb_convert_encoding($data, "UTF-8", "auto");
- return htmlentities($data);
- }
- /* Encryption / Decryption with randomly generated salting */
- public function encrypt($string) {
- $key = array( 0 => strlen($string), 1 => time() );
- $salt = hash("SHA256", implode(chr(0), $key), true);
- srand(str_shuffle(time() . rand(1000000, 9999999)));
- $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND);
- if(strlen($iv_base64 = rtrim(base64_encode($iv), '=')) != 22) return false;
- $crypt = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $salt, $string . md5($string), MCRYPT_MODE_CBC, $iv) . ';=;=;=' . base64_encode(implode(chr(0), $key)));
- return $iv_base64 . $crypt;
- }
- public function decrypt($string) {
- $str = array( 0 => substr($string, 0, 22) );
- $sub = base64_decode(substr($string, 22));
- $sub = explode(';=;=;=', $sub);
- $string = array_merge($str, $sub);
- $key = hash("SHA256", base64_decode(@$string[2]), true);
- $iv = base64_decode($str[0] . '==');
- $decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, @$string[1], MCRYPT_MODE_CBC, $iv), "\0\4");
- return md5(substr($decrypted, 0, -32)) == substr($decrypted, -32) ? substr($decrypted, 0, -32) : false;
- }
- /* Custom string hashing + randomly generated salt && hash authentication */
- public function hash($data = null, $salt = null, $hash = "whirlpool") {
- if(!is_string($data) || is_null($data)) return false;
- if(!@hash($hash, chr(0))) $hash = "whirlpool";
- if(is_null($salt)) {
- $chars = array_merge(range('a', 'z'), range('A', 'Z'), range(0, 9));
- for($salt = ""; strlen($salt) < strlen($data); $salt .= $chars[array_rand($chars)]);
- };
- $salt = array($salt, hash("sha1", $salt));
- $data = array(hash("sha1", $data), "");
- foreach(str_split($salt[1], 1) as $i => $u)
- $data[1] .= $u . $data[0][$i];
- $data[1] = hash($hash, $data[1]);
- return substr_replace($data[1], $salt[0], strlen($salt[0]), 0);
- }
- public function validate($input = null, $hash = null, $engine = "whirlpool") {
- if(is_null($hash) ||is_null($input)) return false;
- $location = strlen($input) >= strlen(hash($engine, chr(0))) ? strlen(hash($engine, chr(0))) : strlen($input);
- $salt = substr($hash, $location, strlen($input));
- return $this->hash($input, $salt, $engine) === $hash ? true : false;
- }
- /* Random generated string <3 */
- public function rand($length = 32, $low = true, $upp = true, $num = true, $indent = false) {
- $chars = array_merge(
- $low ? range('a', 'z') : array(),
- $upp ? range('A', 'Z') : array(),
- $num ? range('0', '9') : array()
- );
- for($rand = ""; strlen($rand) < $length; $rand .= $chars[ array_rand($chars) ]);
- if($indent != false) $rand = implode('-', str_split($rand, $indent));
- return $rand;
- }
- /* Show errors / exit accordingly */
- public function exception($msg = null) {
- if($this->debug) print $msg . PHP_EOL and ($this->soe ? sleep(3) : null);
- if($this->doe == true) exit;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment