Download the PHP package omarelgabry/miniphp without Composer
On this page you can find all versions of the php package omarelgabry/miniphp. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download omarelgabry/miniphp
More information about omarelgabry/miniphp
Files in omarelgabry/miniphp
Package miniphp
Short Description A small, simple PHP MVC framework skeleton that encapsulates a lot of features surrounded with powerful security layers.
License MIT
Homepage https://github.com/OmarElGabry/miniPHP
Informations about the package miniphp
miniPHP
A small, simple PHP MVC framework skeleton that encapsulates a lot of features surrounded with powerful security layers.
miniPHP is a very simple application, useful for small projects, helps to understand the PHP MVC skeleton, know how to authenticate and authorize, encrypt data and apply security concepts, sanitization and validation, make ajax calls and more.
It's not a full framework, nor a very basic one but it's not complicated. You can easily install, understand, and use it in any of your projects.
It's indented to remove the complexity of the frameworks. Things like routing, authentication, authorization, manage user session and cookies, and so on are not something I've invented from the scratch, however, they are aggregation of concepts already implemented in other frameworks, but, built in a much simpler way, So, you can understand it, and take it further.
If you need to build bigger application, and take the advantage of most of the features available in frameworks, you can see CakePHP, Laravel, Symphony.
Either way, It's important to understand the PHP MVC skeleton, and know how to authenticate and authorize, learn about security issues and how can you defeat against, and how to build you own application using the framework.
Documentation
Full Documentation can be also found here — created by GitHub automatic page generator.
Index
- Demo
- Installation
- Routing
- Controller
- Components(Middlewares)
- Authentication
- Session
- Cookies
- Authorization
- Security
- HTTP Methods
- Domain Validation
- Form Tampering
- CSRF
- htaccess
- Turn on/off Components
- Authentication
- Views
- Models
- Login
- User Verification
- Forgotten Password
- Brute-Force attack
- Captcha
- Block IP Addresses
- Database
- Encryption
- Validation
- Errors & Exceptions
- Logger
- Configurations
- JavaScript & Ajax
- Application(Demo)
- Intro
- Installation
- User Profile
- Files
- News Feed & Posts & Comments
- Admin
- Notifications
- Report Bugs
- Backups
- ToDo Application(Step By Step Implementation)
- Support
- Contribute
- Dependencies
- License
Demo
A live demo is available here. The live demo is for the demo application built on top of this framework in this @Everterstraat.
Some features mighn't work in the demo.
Installation
Install via Composer
Routing
Whenever you make a request to the application, it wil be directed to index.php inside public folder. So, if you make a request: . This will be splitted and translated into
- Controller: User
- Action Method: update
- Arguemtns to action method: 412
In fact, htaccess splits everything comes after and adds it to the URL as querystring argument. So, this request will be converted to: .
Then Class, Inside , will split the query string into controller, action method, and any passed arguments to action method.
In Class, Inside , it will instantiate an object from controller class, and make a call to action method, passing any arguments if exist.
Controller
After the Class intantiates controller object, It will call method, which in turn will trigger 3 consecutive events/methods:
- : Use it to load components
- : Perform any logic actions before calling controller's action method
- : Trigger startup() method of loaded components
The constructor of Class shouldn't be overridden, instead you can override the & methods in the extending classes.
After the startup process of the constrcutor finishes it's job, Then, the requested action method will be called, and arguments will be passed(if any).
Components(Middlewares)
Components are the middlewares. They provide reusable logic to be used as part of the controller. Authentication, Authorization, Form Tampering, and Validate CSRF Tokens are implemented inside Components.
It's better to pull these pieces of logic out of controller class, and keep all various tasks and validations inside these Components.
Every component inherits from the base/super class called . Each has a defined task. There are two components, one for called Auth for Authentication and Authorization, and the other one called Security for other Security Issues.
They are very simple to deal with, and they will be called inside controller constructor.
Authentication
Is user has right credentials?
Session
The AuthComponent takes care of user session.
- Prevent Session Concurrency
- There can't be 2 users logged in with same user credentials.
- Defeat against Session Hijacking & Fixation
- HTTP Only with session cookies
- Whenever it's possible, It's Highly Recommended to use Secured connection(SSL).
- Regenerate session periodically and after actions like login, forgot password, ...etc.
- Validate user's IP Address and User agent(initially will be stored in session). Although they can be faked, It's better to keep them as part of validation methods.
- Session Expiration
- Session will expire after certain duration(>= 1 day)
- Session cookie in browser is also configured to be expired after (>= 1 week)
- Session accessible only through the HTTP protocol
- This is important so sessions won't be accessible by JS.
Cookies
- Remember Me Tokens
- User can keep himself logged in using cookies
- HTTP Only with cookies
- Whenever it's possible, It's Highly Recommended to use Secured connection(SSL).
- Cookies stored in browser are attached with tokens and Encrypted data
- Cookies in browser are also configured to be expired after (>= 2 weeks)
Authorization
Do you have the right to access or to perform X action?. The Auth Component takes care of authorization for each controller. Thus, each controller should implement method. What you need to do is to return value.
So, for example, in order to check if current user is admin or not, you would do something like this:
If you want to take it further and apply some permission rules, There is a powerful class called responsible for defining permission rules. This class allows you to define "Who is allowed to perform specific action method on current controller".
So, for example, in order to allow admins to perform any action on notes, while normal users can only edit their notes:
Now, you can check authorization based on user's role, resource, and for each action method.
Security
The SecurityComponent takes care of various security tasks and validation.
HTTP Method
It's important to restrict the request methods. As an example, if you have an action method that accepts form values, So, ONLY POST request will be accepted. The same idea for Ajax, GET, ..etc. You can do this inside method.
Also if you require all requests to be through secured connection, you can configure the whole controller, or specific actions to redirect all requests to HTTPS instead of HTTP.
Domain Validation
It checks & validates if request is coming from the same domain. Although they can be faked, It's good to keep them as part of our security layers.
Form Tampering
Validate submitted form coming from POST request. The pitfall of this method is you need to define the expected form fields, or data that will be sent with POST request.
By default, the framework will validate for form tampering when POST request is made, and it will make sure the CSRF token is passed with the form fields. In this situation, if you didn't pass the CSRF token, it will be considered as a Security thread.
- Unknown fields cannot be added to the form.
- Fields cannot be removed from the form.
CSRF Tokens
CSRF Tokens are important to validate the submitted forms, and to make sure they aren't faked. A hacker can trick the user to make a request to a website, or click on a link, and so on.
They are valid for a certain duration(>= 1 day), then it will be regenerated and stored in user's session.
CSRF validation is disabled by default. If you want to validate the CSRF token, then assign to as shown in the example below. CSRF validation will be forced when request is POST and form tampering is enabled.
Now, You do not need to manually verify the CSRF token on every requests. The Security Component will verify token in the request versus the token stored in the session.
CSRF tokens are generated per session. You can either add a hidden form field, or in the URL as query parameter.
Form
URL
JavaScript
You can also assign the CSRF token to a javascript variable.
htacess
- All requests will be redirected to in public root folder.
- Block directory traversal/browsing
- Deny access to app directory(Althought it's not needed if you setup the application correctly)
Turn on/off Components(Middlewares)
Sometimes you need to have a control on these components, such as when want to have a Controller without Authentication or Authorization, or a Security component is enabled. This can be done by override method inside your Controller class, and load only needed Components.
Example 1: Don't load any component, no authentication or authorization, or security validations.
Example 2: Load Security, & Auth component, but don't authenticate and authorize, just in case you want to use the Auth component inside the action methods. LoginController is an example on how to access a page without require a logged-in user.
Example 3: Load Security, & Auth component, and authenticate user & authorize for the current controller. This is the default behavior in the core/Controller Class
Views
Inside the action method you can make a call to model to get some data, and/or render pages inside views folder
Models
In MVC, the model represents the information (the data) and the business rules; the view contains elements of the user interface such as text, form inputs; and the controller manages the communication between the model and the view. Source
All operations like create, delete, update, and validation are implemented in model classes.
In Notes Model
Login
Using the framework, you would probably do login, register, and logout. These actions are implemented in app/models/Login & app/controllers/LoginController. In most situations, you won't need to modify anything related to login actions, just understand the behaviour of the framework.
NOTE If you don't have SSL, you would better want to encrypt data manually at Client Side, If So, read this and also this.
User Verification
Whenever the user registers, An email will be sent with token concatenated with encrypted user id. This token will be expired after 24 hour. It's much better to expire these tokens, and re-use the registered email if they are expired.
Passwords are hashed using the latest algorithms in PHP v5.5
Forgotten Password
If user forgot his password, he can restore it. The same idea of expired tokens goes here.
In addition, block user for certain duration(>= 10min) if he exceeded number of forgotten passwords attempts(5) during a certain duration(>= 10min).
Brute Force Attack
Throttling brute-force attacks is when a hacker tries all possible input combination until he finds the correct password.
Solution:
- Block failed logins, So, if a user exceeded number of failed logins(5) during certain duration(>= 10min), the email will be blocked for duration(>= 10min).
- Blocking will be for emails even these emails aren't stored in our database, meaning for non-registered users.
- Require Strong passwords
- At least one lowercase character
- At least one uppercase character
- At least one special character
- At least one number
- Min Length is 8 characters
Captcha
CAPTCHAs are particularly effective in preventing automated logins. Using Captcha an awesome PHP Captcha library.
Block IP Address
Blocking IP Addresses is the last solution to think about. IP Address will be blocked if the same IP failed to login multiple times using different credentials(>=10).
Database
PHP Data Objects (PDO) is used for preparing and executing database queries. Inside Class, there are various methods that hides complexity and let's you instantiate database object, prepare, bind, and execute in few lines.
- SQL Injection
- Using prepared statements will prevent SQL Injection.
- Limit Privileges
- Don't use root user, Create a new one instead.
- Always assign limited privileges to current database user
- are enough for users
- For backups, It's recommended to use another database user with more privileges. These privileges needed for mysqldump are mentioned in Class.
- UTF-8
- For complete UTF-8 support, you need to use on database level.
- MySQL’s charset only store UTF-8 encoded symbols that consist of one to three bytes. But, It can't for symbols with four bytes.
- Here, charset is . But, if you want to upgrade to follow these links:
Encryption
Class is responsible for encrypting and decryption of data. Encryption is applied to things like cookies, User ID, Post ID, ..etc. Encrypted strings are authenticated and they are different every time you encrypt.
Validation
Validation is a small library for validating user inputs. All validation rules are inside Class.
Usage
Errors and Exceptions
Class is responsible for handling all exceptions and errors. It will use Logger to log errors. Error reporting is turned off by default, because every error will be logged and saved in app/logs/log.txt.
If error encountered or exception was thrown, the application will show System Internal Error(500).
Configurations(php.ini)
- Turn Off display errors
- Turn Off log errors if not needed
Logger
A place where you can log anything and save it to app/log/log.txt. You can write any failures, errors, exceptions, or any other malicious actions or attacks.
Emails are sent using PHPMailer via SMTP, another library for sending emails. You shouldn't use function of PHP.
Configurations
In app/config, there are two files, one called config.php for main application configurations, and another one for javascript called javascript.php. The javascript configurations will be then assigned to a javascript variable in your footer.php.
JavaScript
In order to send request and recieve a respond, you may depend on Ajax calls to do so. This framework is heavily depends on ajax requests to perform actions, but, you still can do the same thing for normal requests with just small tweaks.
In public/main.js
config object is assigned to key-value pairs in footer.php. These key-value pairs can be added in server-side code using , which will be assigned then to config object.
ajax A namespace that has two main functions for sending ajax request. One for normal ajax calls, and another for for uploading files.
helpers A namespace that has variety of functions display errors, serialize, redirect, encodeHTML, and so on
app A namespace that's used to initalize the whole javascript events for the current page
events A namespace that's used to declare all of events that may occure, like when user clicks on a link to create, delete or update.
Application(Demo)
Intro
In order to show how to use the framework in a real-life situation, the framework comes with implementation for features like Manage User Profile Management, Dashboard, News Feed, Upload & Download Files, Posts & Comments, Pagination, Admin panel, Manage System Backups, Notificatons, Report Bugs, ...etc.
Installation
Steps:
-
Edit configuration file in app/config/config.php with your credentials
-
Execute SQL queries in _installation directory in order
- Login
- Admin:
- Email: [email protected]
- Password: 12345
- Normal User:
- Email: [email protected]
- Password: 12345
- Admin:
EMAIL SETUP
You need to configure your SMTP account data in app/config/config.php. But, If you don't have SMTP account, then you save emails in app/logs/log.txt using Logger.
To do that, In core/Email, comment & uncomment
User Profile
Every user can change his name, email, password. Also upload profile picture (i.e. initially assigned to default.png).
Update & Revoke User Email
Whenever user asks to change his email, a notification will be sent to user's old email, and the new one.
The notification sent to old email is giving the user the chance to revoke email change, while the notification sent to new email is asking for confirmation. User can still login with his old email until he confirms the change.
This is done in , In methods , , & . In most situations, you won't need to modify the behavior of these methods.
Files
You can upload and download files.
Upload
- All uploaded files are out of root public, so, they aren't accessible by anyone
- Validate against HTTP POST uploads, MIME, Size, Image dimension
- Setting file permission to avoid executable files
- Sanitizing file names
- Progress bar(no-plugins)
Download
- Every file will have hashed version of it's name, this hashed name will be exposed to users.
- The hashed name = hash(original filename . extension). So, download link will look something like this: http://miniPHP/downloads/download/b989f733f948e8a4b8b700e1
Configurations(php.ini)
- Set to true
- Set
- Check documentation to know how to assign proper values for each.
News Feeds, Posts & Comments
Think of News Feed as tweets in twitter, and in Posts like when you open an Issue in Github.
They are implemented on the top of this framework.
- They are useful to show & apply some concepts like Pagination,
- How can you edit & delete in place(secured way),
- How can you manage permissions for who can create, edit, update and delete, and so forth.
Admin
Admins can perform actions where normal users can't. They can delete, edit, create any newsfeed, post, or comment. Also they have control over all user profiles, create & restore backups.
Users
Only admins have access to see all registered users. They can delete, edit their info.
Backups
In most of the situations, you will need to create backups for the system, and restore them whenever you want.
This is done by using mysqldump to create and restore backups. All backups will be stored in app/backups.
Notifications
Did you see the red notifications on facebook, or the blue one on twitter?. The same idea is here. But, It's implemented using triggers instead. Triggers are defined in _installation/triggers.sql.
So, whenever user creates a new newsfeed, post, or upload a file, this will increment the count for all other users, and will display a red notification in navigation bar.
Report Bugs
Users can report Bugs, Features & Enhancements. Once they submitted the form, an email will be sent to defined in app/config/config.php
ToDo Application
Let's say you want to build a simple ToDo Application. Here, I will go step by step on how to create a ToDo App using the framework with & without Ajax calls.
(1) If you followed the installtion setup steps above, you shouldn't have any problem with creating initial user accounts.
(2) Create a table with id as INT, content VARCHAR, user_id as Foreign Key to table
(3) Create TodoController
Create a file called inside app/controllers
(4) Create Note Model Class called in app/models
(5) Inside views/
(a) Create & inside views/layout/todo
(b) Inside views/ Create todo folder that will have , which will contain our todo list.
(6) JavaScript code to send ajax calls, and handle respond
Support
I've written this script in my free time during my studies. This is for free, unpaid. I am saying this because I've seen many developers acts very rude towards any software, and their behavior is really frustrating. I don't know why?! Everyone tends to complain, and saying harsh words. I do accept the feedback, but, in a good and respectful manner.
There are many other scripts online for purchase that does the same thing(if not less), and their authors are earning good money from it, but, I choose to keep it public, available for everyone.
If you learnt something, or I saved your time, please support the project by spreading the word.
Contribute
Contribute by creating new issues, sending pull requests on Github or you can send an email at: [email protected]
Dependencies
License
Built under MIT license.