A comprehensive social media platform built with PHP implementing a custom MVC architecture. This platform provides a complete social networking experience with modern web development practices.
- Posts Creation & Management: Create, edit, update, and delete posts with rich content
- Multiple Image Upload: Support for uploading multiple images per post with dedicated image manager
- Image Management:
- Upload multiple images to posts
- Update attached images
- Delete images when posts are removed
- Preview images before upload
- Tagging System: Organize posts with custom tags for better categorization and discovery
- Content Validation: Built-in validation for post titles and content to ensure quality
- Post Filtering: Browse posts by tags and categories
- User Registration & Authentication:
- Secure user registration with profile picture upload
- Login system with email and password
- Session-based authentication
- User Profiles:
- Customizable user profiles with avatars
- Editable bio section
- First name and last name fields
- Profile picture management
- User Roles:
- Regular user role with standard permissions
- Admin role with full platform access
- Profile Settings:
- Edit personal information (username, name, bio)
- Upload/change profile pictures
- Account status management (public/private profiles)
- Profile Privacy:
- Public Profiles: Anyone can follow without approval
- Private Profiles: Follow requests require acceptance
- Follow System:
- Follow and unfollow other users
- Follower and following lists
- Follower/following count display
- View user followers and following
- Private Account Support:
- Send follow requests to private accounts
- Pending follow request status
- Accept/reject follow requests
- Likes System:
- Like posts with one-click
- Like comments and replies
- Unlike functionality (toggle)
- Like count display
- Comment System:
- Comment on posts
- Reply to comments (nested comments)
- Edit own comments
- Delete own comments
- Full CRUD operations on comments
- Social Feed:
- View posts from followed users
- Discover new content from all users
- Browse posts by user profile
- Tag-based content discovery
- Real-time Notifications: Advanced notification system for social interactions
- Notification Types:
- Post likes notifications
- Comment likes notifications
- New follow notifications
- Follow request notifications (for private accounts)
- Comment and reply notifications
- Notification Features:
- Actor-based system (who performed the action)
- Object-type tracking (post, comment, user)
- Context awareness (parent post/comment reference)
- Group key system to prevent duplicate notifications
- Notification recipients management
- Notification Management:
- View all notifications in user dashboard
- Notification count display
- Mark notifications as read
- Navigate directly to related content
- CSRF Protection:
- Built-in CSRF token validation on all state-changing operations
- Token regeneration per session
- Middleware-based validation
- Password Security:
- Secure password storage using PHP's
password_hash() - Password verification with
password_verify() - No plain-text password storage
- Secure password storage using PHP's
- JWT Authentication:
- API authentication using JSON Web Tokens
- Secure token generation and validation
- Token-based API access control
- Input Validation:
- Comprehensive input validation system
- Sanitization of user inputs
- Validation rules engine
- Role-based Access Control:
- Middleware-based permission system
- Route-level access control
- Admin-only protected routes
- Authentication-required routes
- Guest-only routes
- SQL Injection Prevention: Using PDO prepared statements
- File Upload Security:
- File type validation
- File size restrictions
- Secure file naming and storage
- Admin Dashboard:
- Comprehensive admin control panel
- Platform statistics overview
- Quick access to management sections
- User Management:
- View all users
- Edit user information
- Manage user roles (promote to admin/demote to user)
- Update user bio and profile details
- Admin-only user editing capabilities
- Content Moderation:
- View all posts
- Manage posts (edit/delete)
- Moderate comments
- Update comment content
- Tag management (create, view, edit tags)
- System Statistics:
- Total user count
- Total posts count
- Total comments count
- Platform engagement metrics
- RESTful API: Complete API endpoints for mobile/frontend applications
- API Version Management: v1 API with versioned endpoints
- API Authentication:
- JWT-based authentication
- Bearer token support
- Secure API access
- JSON Responses: Standardized JSON API responses
- API Endpoints:
- User registration via API
- User login via API
- User logout via API
- Get all posts
- Create new posts (authenticated)
- JWT middleware protection for authenticated endpoints
This project implements a custom PHP MVC framework from scratch with the following components:
- App.php: Application container for dependency injection
- Router.php: Advanced routing system with:
- RESTful route support (GET, POST, PATCH, DELETE)
- Dynamic route parameters (e.g.,
/user/{id}) - Middleware support per route
- Route grouping capabilities
- Database.php: PDO-based database abstraction layer with:
- Prepared statements
- Query builder
- Fetch methods (fetch, fetchAll, fetchCol)
- Last insert ID support
- Container.php: Dependency injection container for service management
- Validator.php: Comprehensive validation system with custom rules
- Jwt.php: JSON Web Token implementation for API authentication
- FileUploader.php:
- Secure file upload handling
- Multiple file upload support
- Image validation and processing
- File organization by type
- Request.php: HTTP request handler for input data
- Config.php: Configuration management system
- AuthMiddleware:
- Protects authenticated-only routes
- Session verification
- Redirects to login if not authenticated
- AdminMiddleware:
- Admin role verification
- Protects admin panel routes
- Role-based access control
- GuestMiddleware:
- Guest-only access (login/register pages)
- Redirects authenticated users away from guest pages
- CsrfMiddleware:
- CSRF token validation
- Protects against cross-site request forgery
- Token verification on POST/PATCH/DELETE requests
- JwtMiddleware:
- JWT token validation for API requests
- Bearer token extraction and verification
- API authentication enforcement
Main Controllers:
- HomeController: Landing page, about, and contact pages
- AuthController: User registration, login, and logout
- UserController:
- User profiles display
- Profile editing
- View user posts
- View followers/following
- Notifications management
- PostController:
- Create, read, update, delete posts
- Post listing and browsing
- Image handling
- CommentController: Comment CRUD operations
- LikeController:
- Post likes
- Comment likes
- Notification triggers
- FollowController:
- Follow/unfollow users
- Handle private account follow requests
- Follow status management
- TagController: Tag browsing and filtering
Admin Controllers:
- Admin\AdminController: Admin dashboard and statistics
- Admin\UserController: User management (edit, update roles)
- Admin\PostController: Post moderation and management
- Admin\CommentController: Comment moderation and updates
- Admin\TagController: Tag management (create, index, store)
API Controllers:
- Api\AuthController: API authentication (register, login, logout)
- Api\PostController: API post endpoints (list, create)
- Api\ApiController: Base API controller
- Api\SystemController: System-level API operations
- User:
- User CRUD operations
- Authentication methods
- Role checking (admin verification)
- Profile updates
- Avatar management
- Public/private status handling
- Post:
- Post creation and management
- Post relationships (user, comments, likes)
- Image associations
- Comment:
- Comment CRUD
- Nested comment support (parent-child relationships)
- Comment ownership verification
- Tag:
- Tag management
- Post-tag relationships
- Tag slugs for URLs
- Follow:
- Follow/unfollow operations
- Follower and following lists
- Follow status tracking (accepted/pending)
- Follow state determination (self, can_follow, following, pending)
- Follower/following count methods
- LikePost: Post like management with toggle functionality
- LikeComment: Comment like management with toggle functionality
- Notification:
- Create notifications for various actions
- Actor and object tracking
- Context management
- Group key system for notification grouping
- NotificationRecipient:
- Manage notification recipients
- Send notifications to specific users
- Track notification delivery
- PostImageManager:
- Multiple image upload handling
- Image attachment to posts
- Image update operations
- Image deletion with file cleanup
- Get images by post ID
- validationRules.php: Centralized validation rules for:
- User registration
- User login
- Post creation/updates
- Comment validation
- Custom validation logic
- PHP: 7.4 or higher
- MySQL: 5.7 or higher
- Web Server: Apache or Nginx
- Composer: For PSR-4 autoloading
- PHP Extensions:
- PDO extension
- PDO_MySQL driver
- GD extension (for image processing)
- JSON extension (for API responses)
git clone <repository-url>
cd reservationcomposer install- Create a new MySQL database named
small_social - Import the database schema (SQL file should be provided)
- Configure database connection
Database Tables:
users- User accounts and profilesposts- User postspost_images- Post image attachmentscomments- Comments and repliestags- Content tagspost_tags- Post-tag relationships (many-to-many)follows- User follow relationships with statuslike_posts- Post likeslike_comments- Comment likesnotifications- Notification recordsnotification_recipients- Notification delivery tracking
Update the database configuration in config.php:
'database' => [
'host' => 'localhost',
'dbname' => 'small_social',
'charset' => 'utf8mb4',
'username' => 'your_username', // Add your DB username
'password' => 'your_password' // Add your DB password
]Ensure the following directories are writable:
chmod 755 public/assets/uploads/
chmod 755 public/assets/uploads/posts/
chmod 755 public/assets/uploads/users/
chmod 755 app/view/Create .htaccess in project root:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ public/index.php [QSA,L]location / {
try_files $uri $uri/ /public/index.php?$query_string;
}- Navigate to
/register - Fill in the registration form:
- Username
- First name and last name
- Email address
- Password
- Upload a profile picture (optional)
- Submit to create account
- Automatically logged in after registration
- Navigate to
/login - Enter email and password
- Submit to access your account
- Log in to your account
- Navigate to
/post/create - Write your post content
- Upload images (optional, multiple images supported)
- Select relevant tags
- Publish your post
Following Users:
- Visit a user's profile
- Click "Follow" button
- If profile is private, wait for acceptance
- If profile is public, follow immediately
Liking Content:
- Click heart icon on posts or comments
- Click again to unlike
Commenting:
- Write comments on posts
- Reply to existing comments
- Edit or delete your own comments
Notifications:
- Click notification icon to view all notifications
- View who liked, commented, or followed you
- See follow requests for private accounts
- Navigate to
/user/{your-username} - View your profile, posts, followers, and following
- Click "Edit Profile" to update:
- Profile information
- Avatar
- Bio
- Account status (public/private)
- Ensure your user account has
role = 'admin'in database - Navigate to
/admin - Access admin dashboard with:
- User management
- Post moderation
- Comment management
- Tag administration
- Platform statistics
/api/v1
POST /api/v1/auth/register
Content-Type: application/json
{
"username": "string",
"first_name": "string",
"last_name": "string",
"email": "string",
"password": "string",
"avatar": "file" (optional)
}
Response: JWT tokenPOST /api/v1/auth/login
Content-Type: application/json
{
"email": "string",
"password": "string"
}
Response: JWT tokenDELETE /api/v1/auth/logout
Authorization: Bearer <jwt-token>
Response: Success messageGET /api/v1/posts
Response: Array of posts with user data, images, likes, and commentsPOST /api/v1/posts
Authorization: Bearer <jwt-token>
Content-Type: application/json
{
"title": "string",
"content": "string",
"images": "files[]" (optional),
"tags": "array" (optional)
}
Response: Created post objectFor API requests requiring authentication, include JWT token in header:
Authorization: Bearer <your-jwt-token>- Responsive Design: Mobile-first design that works on all devices
- Clean UI: Intuitive user interface with modern design
- Real-time Form Validation: Client-side validation before submission
- Image Preview: Preview images before uploading
- CSRF Protection: All forms include CSRF tokens
- Flash Messages: Success and error message notifications
- AdminLTE: Professional admin panel design using AdminLTE template
- Interactive Elements: Like buttons, follow buttons with instant feedback
- Profile Cards: User profile display cards
- Notification Badge: Unread notification count indicator
-
Password Security:
- All passwords hashed using
password_hash()with bcrypt - Passwords never stored in plain text
- Secure password verification
- All passwords hashed using
-
CSRF Protection:
- All state-changing operations protected with CSRF tokens
- Token validation via middleware
- Tokens regenerated per session
-
Input Validation:
- All user inputs validated server-side
- Sanitization to prevent XSS attacks
- Type checking and length restrictions
-
SQL Injection Prevention:
- Using PDO prepared statements exclusively
- Parameter binding for all queries
- No raw SQL with user input
-
File Upload Security:
- Strict file type validation (images only)
- File size limitations
- Secure file naming (preventing overwrites)
- Files stored outside public access where appropriate
-
Session Management:
- Secure session handling
- Session fixation prevention
- Proper session destruction on logout
-
Authentication Security:
- JWT tokens for API
- Session-based auth for web
- Token expiration
- Secure token storage
-
Authorization:
- Role-based access control
- Ownership verification (users can only edit their own content)
- Admin privilege verification
- Route-level middleware protection
reservation/
βββ Core/ # Custom MVC framework core
β βββ App.php # Application container (DI)
β βββ Router.php # Routing system with middleware
β βββ Database.php # PDO database abstraction
β βββ Validator.php # Validation system
β βββ Jwt.php # JWT authentication handler
β βββ FileUploader.php # File upload manager
β βββ Request.php # HTTP request handler
β βββ Config.php # Configuration loader
β βββ Container.php # Dependency injection container
β
βββ app/ # Application logic
β βββ Controllers/ # Controller classes
β β βββ Admin/ # Admin panel controllers
β β β βββ AdminController.php
β β β βββ UserController.php
β β β βββ PostController.php
β β β βββ CommentController.php
β β β βββ TagController.php
β β βββ Api/ # API controllers
β β β βββ ApiController.php
β β β βββ AuthController.php
β β β βββ PostController.php
β β β βββ SystemController.php
β β βββ AuthController.php
β β βββ HomeController.php
β β βββ UserController.php
β β βββ PostController.php
β β βββ CommentController.php
β β βββ LikeController.php
β β βββ FollowController.php
β β βββ TagController.php
β β
β βββ Model/ # Model classes
β β βββ User.php # User model
β β βββ Post.php # Post model
β β βββ Comment.php # Comment model
β β βββ Tag.php # Tag model
β β βββ Follow.php # Follow relationship model
β β βββ LikePost.php # Post like model
β β βββ LikeComment.php # Comment like model
β β βββ Notification.php # Notification model
β β βββ NotificationRecipient.php # Notification delivery
β β βββ PostImageManager.php # Image management
β β
β βββ Middleware/ # Middleware classes
β β βββ AuthMiddleware.php # Authentication guard
β β βββ AdminMiddleware.php # Admin role guard
β β βββ GuestMiddleware.php # Guest-only guard
β β βββ CsrfMiddleware.php # CSRF protection
β β βββ JwtMiddleware.php # JWT validation
β β
β βββ Contract/ # Interface contracts
β β βββ MiddlewareInterface.php
β β
β βββ Validations/ # Validation rules
β β βββ validationRules.php
β β
β βββ view/ # View templates
β βββ admin/ # Admin panel views
β βββ auth/ # Login/register views
β βββ posts/ # Post views
β βββ users/ # User profile views
β βββ comments/ # Comment views
β βββ partials/ # Reusable components
β βββ errors/ # Error pages (404, etc.)
β
βββ routes/ # Route definitions
β βββ routes.php # Web routes
β βββ api.php # API routes
β
βββ public/ # Public assets and entry point
β βββ index.php # Application entry point
β βββ assets/
β β βββ admin/ # AdminLTE assets
β β βββ img/ # Public images
β β βββ uploads/ # User uploaded files
β β βββ posts/ # Post images
β β βββ users/ # User avatars
β βββ fake_user_data.php # Test data generator (dev)
β βββ login_data.php # Login testing (dev)
β
βββ helpers/ # Helper functions
β βββ helpers.php # Global helper functions
β
βββ vendor/ # Composer dependencies
βββ .git/ # Git repository
βββ .gitignore # Git ignore rules
βββ bootstrap.php # Application bootstrap
βββ composer.json # Composer configuration
βββ composer.lock # Dependency lock file
βββ config.php # Application configuration
βββ PROJECT_DOCUMENTATION.html # Project documentation
βββ README.md # This file
The application uses a custom router with the following features:
Route Methods:
GET- Retrieve resourcesPOST- Create resourcesPATCH- Update resourcesDELETE- Delete resources
Route Protection:
Routes can be protected with middleware using ->only():
$router->get('/admin', 'AdminController@dashboard')->only('admin');
$router->post('/post/create', 'PostController@store')->only(['auth', 'csrf']);Available Middleware:
auth- Requires authenticationguest- Guests only (not authenticated)admin- Admin role requiredcsrf- CSRF token validationjwt- JWT authentication (API)
- User accesses
/post/create(AuthMiddleware checks authentication) - Form displays with CSRF token
- User fills form and uploads images
- PostController validates input
- Post saved to database
- Images uploaded via PostImageManager
- Images attached to post in
post_imagestable - User redirected to post view
- User A clicks follow on User B's profile
- System checks if User B has private profile
- Follow record created with
status = 'pending' - Notification created with type
follow_requested - User B sees notification
- User B can accept or reject request
- Status updated to
acceptedor record deleted
- User performs action (like, comment, follow)
- System identifies affected users (post owner, comment owner, etc.)
- Notification created with actor, type, object, and context
- NotificationRecipient records created for recipients
- Recipients see notification count badge
- Clicking notification navigates to related content
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
- This project uses PSR-4 autoloading via Composer
- All database queries use prepared statements for security
- The framework follows MVC pattern strictly
- Dependency Injection is handled through the Container class
- All middleware implements MiddlewareInterface
- File uploads are organized by type (posts, users)
- The project includes test data generators in
public/for development
- Database credentials need to be added to
config.php - SQL schema file needs to be provided for installation
- Notification "mark as read" functionality may need implementation
- Follow request accept/reject UI needs to be confirmed
- API documentation could be expanded with response examples
This project is a self-project for learning purposes.
DevBrave - devbrave/smc_mvc
Built with β€οΈ using Custom PHP MVC Architecture