Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /*
- todo: delete this step-by-step and any other todos in this document. Use PHP storm 'TODO' panel on the bottom to locate the todos in this document to make sure theyre all gone before pasting it to ralph
- ******************
- 1. html finishes loading
- 2. $.getJSON called
- 3. request is made to this file parsing $_GET['f'] (e.g. database.php?f=[function name])
- 4. the $_GET['f'] parameter is used to call the specified function
- 5. sql statements are executed and directories read and put into array form
- 6. array and code of succession is then parsed into JSON format using json_encode()
- 7. response json is then set as the contents of this file
- 8. once this file is loaded, the jquery $.getJSON().success(response) function is called parsing the response as the contents of this file
- 9. jquery then interprets the response and gives a client response such as an alert message or creates html based on the json data
- ******************
- */
- /*
- todo: this is the sql to create the user table that stores...
- CREATE TABLE `users` (
- `user_id` int(11) NOT NULL AUTO_INCREMENT,
- `user_email` varchar(200) NOT NULL,
- `user_name` varchar(200) NOT NULL,
- `user_password` varchar(200) NOT NULL,
- PRIMARY KEY (`user_id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=13 ;
- --
- -- Dumping data for table `users`
- --
- INSERT INTO `users` VALUES(10, 'michael@cloud.com', 'michael', 'pass');
- INSERT INTO `users` VALUES(11, 'craig@cloud.com', 'craig', 'pass');
- INSERT INTO `users` VALUES(12, 'lois@cloud.com', 'lois', 'pass');
- */
- /******todo:this is the sql server configuration used to connect with mysql database hosted online.*****/
- define("DB_TYPE","mysql");
- define("DB_HOST","StudentCloud.db.11698469.hostedresource.com");//todo: used an existing database provided by friend so i wouldnt have to use sign up for free hosting
- define("DB_NAME","StudentCloud");
- define("DB_USER","StudentCloud");
- define("DB_PWD","CMT3313db!");
- class DB extends PDO {
- //todo:this class was from an example found online to allow me to use PDO connection object without having to set the user and login credentials everytime i instantiate the object.
- public function __construct() {//TODO: Possibly allow argument to state the connection type
- parent::__construct(DB_TYPE.':host='.DB_HOST.';charset=utf8;dbname='.DB_NAME, DB_USER, DB_PWD);
- }
- public function prepare($stmt,$options=array()) {
- return parent::prepare($stmt,$options);
- }
- }
- session_start();//todo:start session to allow user detail variables to be set and accessed
- /***************************library**********************************/
- //todo: created this object to make sure that my code was kept clean and i could set private functions that could only be accessed by functions within the class
- class CloudSystem
- {
- public function __construct() {
- }
- public function respondJSON($code = 1, $data = array())
- {
- //todo: used this function to give a json formatted response that could be easily read using $.getJSON function in my jquery script
- $r = array();
- $r['code'] = $code;//todo: code for identifying the response
- $r['data'] = $data;//todo: data for holding the file list and any other detail that can be read by my html page
- throw new Exception(json_encode($r));//todo: used a thrown exception to make sure that other code isnt ran because i couldnt get PHP's 'exit' to work
- }
- public function setUserDetails($user_id, $user_name)
- {
- //todo: this function is to set and store the users credentials in http cookies. This is so the users login status is saved and they dont have to login everytime the page is refreshed.
- //throw new Exception("userid: {$user_id} name: {$user_name}");
- setcookie('user_id',$user_id,null,'/');
- setcookie('user_name',$user_name,null,'/');
- ////
- //throw new Exception(print_r($_COOKIE,true));
- }
- private function getUserDetails()
- {
- $details = array();
- $details['user_id'] = isset($_COOKIE['user_id']) ? $_COOKIE['user_id'] : 0;
- $details['user_name'] = isset($_COOKIE['user_name']) ? $_COOKIE['user_name'] : 0;
- if (empty($details['user_id']) || empty($details['user_name'])) return false;else return $details;//todo: this function is for grabbing the user details from cookies and then put them in readable array
- }
- /***************************library**********************************/
- public function uploadFile()
- {
- $userDetail = $this->getUserDetails();
- $valid_file = false;
- $code = 0;
- if (!isset($_FILES['myFile'])) $this->respondJSON(77);else {//todo: make sure user specified a file
- if (!file_exists('files/' . $userDetail['user_id'] . "/")) mkdir('files/' . $userDetail['user_id'] . "/");//todo: create user's folder if it doesnt exist yet
- move_uploaded_file($_FILES['myFile']['tmp_name'], 'files/' . $userDetail['user_id'] . "/" . $_FILES['myFile']['name']);
- //todo: when the user selects a file to be uploaded, it is first moved to their temporary folder on their own computer.
- //todo: This function then accesses that file in the temporary directory and transfers
- $code = 1;
- }
- //$this->respondJSON($code);
- if ($code) echo "Upload success!"; else echo "File not specified";
- }
- public function loginUser()
- {
- $db = new DB();//todo: create an instance of the database PDO object to be used with manipulating mysql database
- //todo: setup sql query ready to be executed, which obtains the users details based on the email and password specified from the users login form
- $query = $db->prepare("SELECT COUNT(*) as count,user_id,user_email,user_name FROM users WHERE user_email=:user_email AND user_password=:user_password");
- //todo: make sure the email and password forms have submitted their values
- if (!isset($_POST['user_email'], $_POST['user_password'])) $this->respondJSON(44);
- //todo: parse in the values from the users login post and bind it with the values within the prepared sql statement
- if (!$query->execute(array('user_email' => $_POST['user_email'], "user_password" => $_POST['user_password']))) {
- $this->respondJSON(118,array("error"=>$query->errorInfo()));
- }
- $data=$query->fetchAll(PDO::FETCH_ASSOC);//todo: get the entire array of results into one variable
- $count = $data[0]['count'];//todo: get the number of entries that the sql found
- //todo: get the user id and name of the user that just signed in
- $user_id=$data[0]['user_id'];
- $user_name=$data[0]['user_name'];
- if ($count <= 0) $this->respondJSON(888);//todo: if (NO USERS FOUND WITH SPECIFIED EMAIL AND PASSWORD IN TABLE) respond with code 888
- $this->setUserDetails($user_id, $user_name);//todo: call this method to store the user details as cookies
- $this->respondJSON(1);//todo: respond with code 1 to say the user has been successfully logged in
- }
- public function logout() {
- //todo: clear the stored user details (set the cookie to an empty string to delete it)
- setcookie('user_id','',null,'/');
- setcookie('user_name','',null,'/');
- }
- public function registerUser()
- {
- $this->logout();//todo: ensure that there is no stored user details before registering
- $db = new DB();
- $query = $db->prepare("INSERT INTO users (user_email,user_name,user_password) VALUES (:user_email,:user_name,:user_password)");
- if (!isset($_POST['user_email'], $_POST['user_name'],$_POST['user_password'])) $this->respondJSON(44);
- //todo: respond with json and data entry that details the invalid field to tell the user what to change
- if (strlen($_POST['user_email'])<3||!filter_var($_POST['user_email'], FILTER_VALIDATE_EMAIL)) $this->respondJSON(78,array("invalid"=>"Invalid Email specified"));//todo: ensure the posted email is a valid email
- if (strlen($_POST['user_name'])<3) $this->respondJSON(78,array("invalid"=>"Invalid name specified"));
- if (strlen($_POST['user_password'])<3||strlen($_POST['user_password'])>25) $this->respondJSON(78,array("invalid"=>"Invalid password specified"));
- if ($_POST['user_password']!=$_POST['user_confirm_password']) $this->respondJSON(78,array("invalid"=>"Passwords dont match love"));//todo: check if password and confirm password values match
- //todo: bing in the required values into the sql statement for insertion into the table
- if (!$query->execute(array(
- 'user_email' => $_POST['user_email'],
- "user_name" => $_POST['user_name'],
- "user_password" => $_POST['user_password']
- ))
- ) {
- $this->respondJSON(118);//todo: respond with code 118 that represents a registration success
- }
- $this->setUserDetails($db->lastInsertId(),$_POST['user_name']);//todo: login the user by storing their credentials in cookie
- $this->respondJSON(1, array('user_id' => $db->lastInsertId()));//todo: respond with a success code and include the user id of user registered for future developments
- }
- public function getFileList()
- {
- $userDetail = $this->getUserDetails();
- if ($userDetail==false) $this->respondJSON(999);
- if (!file_exists('files/' . $userDetail['user_id'] . "/")) {//todo: check if the user has a dedicated directory
- mkdir('files/'. $userDetail['user_id']);//todo: if they dont, create one for the user
- $this->respondJSON(333);//
- }
- $dir_list = scandir('files/' . $userDetail['user_id'] . "/");///todo: get an array of files that resides in the users dedicated directory
- $this->respondJSON(1, array("user_id"=>$userDetail['user_id'],"file_list"=>$dir_list));//todo: respond with the file list in json format
- }
- public function deleteFile() {
- $userDetail = $this->getUserDetails();
- if ($userDetail==false) $this->respondJSON(999);//todo: if user is not logged in, return and respond with 999 code
- if (!isset($_GET['file'])) $this->respondJSON(0);//todo: if the file has not been specified correctly, return and respond with 0 code
- if (file_exists('files/' . $userDetail['user_id'] . "/".$_GET['file'])) {//todo: check if the file exists first before attempting to delete
- if (unlink('files/' . $userDetail['user_id'] . "/".$_GET['file'])) $this->respondJSON(1);else $this->respondJSON(956);//todo: delete file
- }
- }
- }
- try {
- $s = new CloudSystem();//todo: create an instance of the cloud system to be able to access the methods inside
- if (isset($_GET['f'])) {//todo: make sure f query string has been set
- $s->{$_GET['f']}();//todo: call the method within the CloudSystem object
- }
- }catch(Exception $e) {
- header("Content-type: application/json");//todo:set the return type
- print $e->getMessage();//todo: get the message that was parsed through exception (i.e. new Exception([message])...this gets the [message])
- exit;//todo: make sure no other php code is executed
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement