PHP code example of omarelgabry / miniphp

1. Go to this page and download the library: Download omarelgabry/miniphp library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

omarelgabry / miniphp example snippets


    // AdminController

    public function isAuthorized(){

        $role = Session::getUserRole();
        if(isset($role) && $role === "admin"){
            return true;
        }
        return false;
    }


   // NotesController
   
   public function isAuthorized(){

        $action = $this->request->param('action');
        $role 	= Session::getUserRole();
        $resource = "notes";

		// only for admins
		// they are allowed to perform all actions on $resource
        Permission::allow('admin', $resource, ['*']);

		// for normal users, they can edit only if the current user is the owner
		Permission::allow('user', $resource, ['edit'], 'owner');

        $noteId = $this->request->data("note_id");
        $config = [
            "user_id" => Session::getUserId(),
            "table" => "notes",
            "id" => $noteId
        ];

		// providing the current user's role, $resource, action method, and some configuration data
		// Permission class will check based on rules defined above and return boolean value
		return Permission::check($role, $resource, $action, $config);
    }

    // NotesController

    public function beforeAction(){

        parent::beforeAction();

        $actions = ['create', 'delete'];

        $this->Security->

    // NotesController

    public function beforeAction(){

        parent::beforeAction();

        $actions = ['create', 'delete'];	// specific action methods	
        $actions = ['*'];		        	// all action methods

        $this->Security->

    // NotesController

    public function beforeAction(){

        parent::beforeAction();

        $action = $this->request->param('action');
        $actions = ['create', 'delete'];

        $this->Security->    case "delete":
            	// If you want to disable validation for form tampering
            	// $this->Security->config("validateForm", false);
                $this->Security->config("form", [ 'fields' => ['note_id']]);
                break;
        }
    }

    // NotesController

    public function beforeAction(){

        parent::beforeAction();

		$action = $this->request->param('action');
		$actions = ['index'];

        $this->Security->

public function initialize(){

	$this->loadComponents([]);
}

public function initialize(){
	$this->loadComponents([ 
	    	'Auth',
	    	'Security'
	    ]);
}
 

public function initialize(){
	$this->loadComponents([
		'Auth' => [
			'authenticate' => ['User'],
			'authorize' => ['Controller']
		],
		'Security'
	    ]);
}

  //  NotesController
  
  public function index(){
 
	// render full page with layout(header and footer)
	$this->view->renderWithLayouts(Config::get('VIEWS_PATH') . "layout/default/", Config::get('VIEWS_PATH') . 'notes/index.php');
	
	// render page without layout
	$this->view->render(Config::get('VIEWS_PATH') . 'notes/note.php');
	
	// get the rendered page
	$html = $this->view->render(Config::get('VIEWS_PATH') . 'notes/note.php');
	
	// render a json view
	$this->view->renderJson(array("data" => $html));
  }

   // NotesController

    public function create(){
    
		// get content of note submitted to a form
		// then pass the content along with the current user to Note class
		$content  = $this->request->data("note_text");
		$note     = $this->note->create(Session::getUserId(), $content);
        
        if(!$note){
            $this->view->renderErrors($this->note->errors());
        }else{
            return $this->redirector->root("Notes");
        }
    }

   // Notes Model

    public function create($userId, $content){
    
    	// using validation class(see below)
        $validation = new Validation();
        if(!$validation->validate(['Content'   => [$content, " "INSERT INTO notes (user_id, content) VALUES (:user_id, :content)";
        $database->prepare($query);
        $database->bindValue(':user_id', $userId);
        $database->bindValue(':content', $content);
        $database->execute();
        
        if($database->countRows() !== 1){
            throw new Exception("Couldn't create note");
        }
        
        return true;
     }

$hashedPassword = password_hash($password, PASSWORD_DEFAULT, array('cost' => Config::get('HASH_COST_FACTOR')));


$validation = new Validation();

// there are default error messages for each rule
// but, you still can define your custom error message
$validation->addRuleMessage("emailUnique", "The email you entered is already exists");

if(!$validation->validate([
    "User Name" => [$name, "

Logger::log("COOKIE", self::$userId . " is trying to login using invalid cookie", __FILE__, __LINE__);


class TodoController extends Controller{

    // override this method to perform any logic before calling action method as explained above
    public function beforeAction(){

        parent::beforeAction();

        // define the actions in this Controller
        $action = $this->request->param('action');

        // restrict the request to action methods
        // $this->Security->
            case "delete":
				// If you want to disable validation for form tampering
				// $this->Security->config("validateForm", false);
                $this->Security->config("form", [ 'fields' => ['todo_id']]);
                break;
        }
    }

    public function index(){

        $this->view->renderWithLayouts(Config::get('VIEWS_PATH') . "layout/todo/", Config::get('VIEWS_PATH') . 'todo/index.php');
    }

    public function create(){

        $content  = $this->request->data("content");
        $todo     = $this->todo->create(Session::getUserId(), $content);

        if(!$todo){

            // in case of normal post request
            Session::set('errors', $this->todo->errors());
            return $this->redirector->root("Todo");

            // in case of ajax
            // $this->view->renderErrors($this->todo->errors());

        }else{

            // in case of normal post request
            Session::set('success', "Todo has been created");
            return $this->redirector->root("Todo");

            // in case of ajax
            // $this->view->renderJson(array("success" => "Todo has been created"));
        }
    }

    public function delete(){

        $todoId = Encryption::decryptIdWithDash($this->request->data("todo_id"));
        $this->todo->delete($todoId);

        // in case of normal post request
        Session::set('success', "Todo has been deleted");
        return $this->redirector->root("Todo");

        // in case of ajax
        // $this->view->renderJson(array("success" => "Todo has been deleted"));
    }

    public function isAuthorized(){

        $action = $this->request->param('action');
        $role = Session::getUserRole();
        $resource = "todo";

        // only for admins
        Permission::allow('admin', $resource, ['*']);

        // only for normal users
        Permission::allow('user', $resource, ['delete'], 'owner');

        $todoId = $this->request->data("todo_id");

        if(!empty($todoId)){
            $todoId = Encryption::decryptIdWithDash($todoId);
        }

        $config = [
            "user_id" => Session::getUserId(),
            "table" => "todo",
            "id" => $todoId];

        return Permission::check($role, $resource, $action, $config);
    }
}

class Todo extends Model{

    public function getAll(){

        $database = Database::openConnection();
        $query  = "SELECT todo.id AS id, users.id AS user_id, users.name AS user_name, todo.content ";
        $query .= "FROM users, todo ";
        $query .= "WHERE users.id = todo.user_id ";

        $database->prepare($query);
        $database->execute();
        $todo = $database->fetchAllAssociative();

        return $todo;
     }

    public function create($userId, $content){
    
    	// using validation class
        $validation = new Validation();
        if(!$validation->validate(['Content'   => [$content, "ete($id){

        $database = Database::openConnection();
        $database->deleteById("todo", $id);

        if($database->countRows() !== 1){
            throw new Exception ("Couldn't delete todo");
        }
    }
 }

<!DOCTYPE html>
<html lang="en">

<head>
		
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="mini PHP">
    <meta name="author" content="mini PHP">

    <title>mini PHP</title>

    <!-- Stylesheets -->
    <link rel="stylesheet" href="<?= PUBLIC_ROOT;

	<!-- footer -->

	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
	<!--<script src="<?= PUBLIC_ROOT; 

<div class="todo_container">

<h2>TODO Application</h2>

<!-- in case of normal post request  -->
<form action= "<?= PUBLIC_ROOT . "Todo/create" 
$this->controller->startupProcess()
 <a href="<?= PUBLIC_ROOT . "?csrf_token=" . urlencode(Session::generateCsrfToken()); 
<script>config = <?= json_encode(Session::generateCsrfToken()); 
index.php
file_uploads
TodoController.php
Todo.php
header.php
footer.php
index.php