PHP简单的密码库系统


main();

function main(){
	$url = 'https://www.baidu.com/';
	$host = getHost($url);

	if (empty($host)) {
		echo respone(100, 'URL Formatting error');
		exit();
	}

	$pass = getPass($host);

	if (empty($pass)) {
		$pass = createPass();
		$db = getDB();
		$db->$host = $pass;
		updateDB($db);
	}

	echo respone(0, 'Get Password Success', ['Password' => $pass]);
}

function getHost($url){
	$parse = parse_url($url);
	if (isset($parse['host'])) {
		return $parse['host'];
	} else {
		return '';
	}
}

function createPass(){
	$pass = array_merge(
		array_rand(array_flip(range(1, 9)), 2), 
		array_rand(array_flip(range('a', 'z')), 4), 
		array_rand(array_flip(range('A', 'Z')), 4), 
		array_rand(array_flip(array('@', '#', '$', '%', '+', '-')), 2)
	);
	shuffle($pass);
	return implode('', $pass);
}

function getPass($host){
	$db = getDB();
	if (isset($db->$host)) {
		return $db->$host;
	} else {
		return '';
	}
}

function getDB(){
	try {
		return json_decode(substr(file_get_contents('db.php'), 16));
	} catch (Exception $e) {
		return [];
	}
}

function updateDB($db){
	file_put_contents('db.php', "<?php exit();\n//" . json_encode($db)); 
} 

function respone($code = 0, $message = '', $data = []){ $respone = array( 'code' => intval($code),
		'data' => $data,
		'message' => $message
	);
	return json_encode($respone);
}