BLOG CODE COMPLETE
Hii ni FULL CODE ya blog inayofanya kazi kwenye file moja.
Ihifadhi kama:
blog.php
Kwanza tengeneza database:
CREATE DATABASE blog_system;
Kisha badilisha settings za database juu ya code kama inavyofaa.
<?php
session_start();
/* =====================================================
DATABASE CONNECTION
===================================================== */
$host = "localhost";
$username = "root";
$password = "";
$database = "blog_system";
$conn = new mysqli($host, $username, $password, $database);
if ($conn->connect_error) {
die("Database connection failed: " . $conn->connect_error);
}
/* =====================================================
CREATE TABLES AUTOMATICALLY
===================================================== */
$conn->query("
CREATE TABLE IF NOT EXISTS admins (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(100) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
");
$conn->query("
CREATE TABLE IF NOT EXISTS posts (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
category VARCHAR(150),
author VARCHAR(150),
content LONGTEXT NOT NULL,
image VARCHAR(255),
file_upload VARCHAR(255),
video_link TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
");
$conn->query("
CREATE TABLE IF NOT EXISTS comments (
id INT AUTO_INCREMENT PRIMARY KEY,
post_id INT NOT NULL,
visitor_name VARCHAR(150) NOT NULL,
comment TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
");
/* =====================================================
DEFAULT ADMIN
Username: admin
Password: admin123
===================================================== */
$checkAdmin = $conn->query("SELECT id FROM admins LIMIT 1");
if ($checkAdmin->num_rows == 0) {
$passHash = password_hash("admin123", PASSWORD_DEFAULT);
$conn->query("INSERT INTO admins(username, password) VALUES('admin', '$passHash')");
}
/* =====================================================
FUNCTIONS
===================================================== */
function e($text) {
return htmlspecialchars($text ?? '', ENT_QUOTES, 'UTF-8');
}
function uploadFile($inputName, $folder, $allowedTypes = []) {
if (!isset($_FILES[$inputName]) || $_FILES[$inputName]['error'] !== 0) {
return "";
}
if (!is_dir($folder)) {
mkdir($folder, 0777, true);
}
$fileName = $_FILES[$inputName]['name'];
$tmpName = $_FILES[$inputName]['tmp_name'];
$fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
if (!empty($allowedTypes) && !in_array($fileExt, $allowedTypes)) {
return "";
}
$newName = time() . "_" . rand(1000, 9999) . "." . $fileExt;
$target = $folder . "/" . $newName;
if (move_uploaded_file($tmpName, $target)) {
return $target;
}
return "";
}
function youtubeID($url) {
if (!$url) return "";
preg_match('/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([A-Za-z0-9_-]+)/', $url, $matches);
return $matches[1] ?? "";
}
/* =====================================================
LOGIN
===================================================== */
if (isset($_POST['login'])) {
$user = trim($_POST['username']);
$pass = $_POST['password'];
$stmt = $conn->prepare("SELECT * FROM admins WHERE username=?");
$stmt->bind_param("s", $user);
$stmt->execute();
$admin = $stmt->get_result()->fetch_assoc();
if ($admin && password_verify($pass, $admin['password'])) {
$_SESSION['admin_id'] = $admin['id'];
$_SESSION['admin_name'] = $admin['username'];
header("Location: blog.php?page=dashboard");
exit;
} else {
$login_error = "Username au password si sahihi.";
}
}
/* =====================================================
LOGOUT
===================================================== */
if (isset($_GET['logout'])) {
session_destroy();
header("Location: blog.php");
exit;
}
/* =====================================================
ADD POST
===================================================== */
if (isset($_POST['add_post']) && isset($_SESSION['admin_id'])) {
$title = trim($_POST['title']);
$category = trim($_POST['category']);
$author = trim($_POST['author']);
$content = $_POST['content'];
$video_link = trim($_POST['video_link']);
$image = uploadFile("image", "uploads/images", ["jpg", "jpeg", "png", "gif", "webp"]);
$file = uploadFile("file_upload", "uploads/files", ["pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "zip", "rar", "txt"]);
$stmt = $conn->prepare("
INSERT INTO posts(title, category, author, content, image, file_upload, video_link)
VALUES(?,?,?,?,?,?,?)
");
$stmt->bind_param("sssssss", $title, $category, $author, $content, $image, $file, $video_link);
$stmt->execute();
header("Location: blog.php?page=dashboard&success=post_added");
exit;
}
/* =====================================================
UPDATE POST
===================================================== */
if (isset($_POST['update_post']) && isset($_SESSION['admin_id'])) {
$id = intval($_POST['post_id']);
$oldPost = $conn->query("SELECT * FROM posts WHERE id=$id")->fetch_assoc();
$title = trim($_POST['title']);
$category = trim($_POST['category']);
$author = trim($_POST['author']);
$content = $_POST['content'];
$video_link = trim($_POST['video_link']);
$image = uploadFile("image", "uploads/images", ["jpg", "jpeg", "png", "gif", "webp"]);
$file = uploadFile("file_upload", "uploads/files", ["pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "zip", "rar", "txt"]);
if (!$image) {
$image = $oldPost['image'];
}
if (!$file) {
$file = $oldPost['file_upload'];
}
$stmt = $conn->prepare("
UPDATE posts
SET title=?, category=?, author=?, content=?, image=?, file_upload=?, video_link=?
WHERE id=?
");
$stmt->bind_param("sssssssi", $title, $category, $author, $content, $image, $file, $video_link, $id);
$stmt->execute();
header("Location: blog.php?page=dashboard&success=post_updated");
exit;
}
/* =====================================================
DELETE POST
===================================================== */
if (isset($_GET['delete_post']) && isset($_SESSION['admin_id'])) {
$id = intval($_GET['delete_post']);
$conn->query("DELETE FROM comments WHERE post_id=$id");
$conn->query("DELETE FROM posts WHERE id=$id");
header("Location: blog.php?page=dashboard&success=post_deleted");
exit;
}
/* =====================================================
ADD COMMENT
===================================================== */
if (isset($_POST['add_comment'])) {
$post_id = intval($_POST['post_id']);
$name = trim($_POST['visitor_name']);
$comment = trim($_POST['comment']);
$stmt = $conn->prepare("
INSERT INTO comments(post_id, visitor_name, comment)
VALUES(?,?,?)
");
$stmt->bind_param("iss", $post_id, $name, $comment);
$stmt->execute();
header("Location: blog.php?post=$post_id#comments");
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Professional Blog System</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Professional blog with posts, images, videos, downloadable files and comments.">
<meta name="keywords" content="blog, news, education, technology, Tanzania, articles, downloads, videos">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css" rel="stylesheet">
<style>
body {
background: #f4f7fb;
font-family: Arial, sans-serif;
color: #172033;
}
.navbar {
background: linear-gradient(135deg, #062b66, #0d6efd);
box-shadow: 0 10px 30px rgba(0,0,0,.15);
}
.navbar-brand,
.nav-link {
color: #fff !important;
font-weight: 700;
}
.hero {
background: linear-gradient(135deg, rgba(13,110,253,.95), rgba(4,20,50,.95)),
url('https://images.unsplash.com/photo-1499750310107-5fef28a66643?auto=format&fit=crop&w=1400&q=80');
background-size: cover;
background-position: center;
padding: 90px 0;
color: white;
border-radius: 0 0 40px 40px;
}
.card {
border: 0;
border-radius: 22px;
box-shadow: 0 12px 35px rgba(0,0,0,.08);
}
.post-card {
transition: .3s;
overflow: hidden;
}
.post-card:hover {
transform: translateY(-6px);
box-shadow: 0 18px 45px rgba(0,0,0,.14);
}
.post-img {
width: 100%;
height: 240px;
object-fit: cover;
}
.single-img {
width: 100%;
max-height: 520px;
object-fit: cover;
border-radius: 22px;
}
.category-badge {
background: #e7f0ff;
color: #0d6efd;
padding: 7px 14px;
border-radius: 50px;
font-size: 13px;
font-weight: bold;
}
.content-box {
font-size: 17px;
line-height: 1.9;
text-align: justify;
white-space: pre-wrap;
}
.dashboard-box {
background: white;
border-radius: 22px;
padding: 25px;
box-shadow: 0 12px 35px rgba(0,0,0,.08);
}
textarea {
min-height: 220px;
}
.footer {
background: #07152e;
color: white;
padding: 40px 0;
margin-top: 60px;
}
.btn-rounded {
border-radius: 50px;
padding: 10px 22px;
font-weight: bold;
}
.comment-box {
background: #f8fbff;
border-radius: 16px;
padding: 15px;
margin-bottom: 12px;
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-lg sticky-top">
<div class="container">
<a class="navbar-brand" href="blog.php">
<i class="fa-solid fa-blog"></i> My Blog
</a>
<button class="navbar-toggler bg-light" data-bs-toggle="collapse" data-bs-target="#navMenu">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navMenu">
<ul class="navbar-nav ms-auto">
<li class="nav-item"><a href="blog.php" class="nav-link">Home</a></li>
<?php if(isset($_SESSION['admin_id'])): ?>
<li class="nav-item"><a href="blog.php?page=dashboard" class="nav-link">Dashboard</a></li>
<li class="nav-item"><a href="blog.php?logout=true" class="nav-link">Logout</a></li>
<?php else: ?>
<li class="nav-item"><a href="blog.php?page=login" class="nav-link">Admin Login</a></li>
<?php endif; ?>
</ul>
</div>
</div>
</nav>
<?php if(!isset($_GET['page']) && !isset($_GET['post'])): ?>
<section class="hero text-center">
<div class="container">
<h1 class="display-4 fw-bold">Welcome to Our Professional Blog</h1>
<p class="lead">Read beautiful posts, watch videos, download files and share your thoughts.</p>
<form method="GET" class="row justify-content-center mt-4">
<div class="col-md-6">
<input type="text" name="search" class="form-control form-control-lg rounded-pill" placeholder="Search blog posts...">
</div>
</form>
</div>
</section>
<?php endif; ?>
<div class="container my-5">
<?php
/* =====================================================
LOGIN PAGE
===================================================== */
if (isset($_GET['page']) && $_GET['page'] == "login" && !isset($_SESSION['admin_id'])):
?>
<div class="row justify-content-center">
<div class="col-md-5">
<div class="card p-4">
<h3 class="text-center fw-bold mb-4">
<i class="fa-solid fa-user-lock"></i> Admin Login
</h3>
<?php if(isset($login_error)): ?>
<div class="alert alert-danger"><?= e($login_error) ?></div>
<?php endif; ?>
<form method="POST">
<label>Username</label>
<input type="text" name="username" class="form-control mb-3" required>
<label>Password</label>
<input type="password" name="password" class="form-control mb-3" required>
<button type="submit" name="login" class="btn btn-primary w-100 btn-rounded">
Login
</button>
</form>
<div class="alert alert-info mt-4 mb-0">
Default Login:<br>
Username: <b>admin</b><br>
Password: <b>admin123</b>
</div>
</div>
</div>
</div>
<?php
/* =====================================================
DASHBOARD
===================================================== */
elseif (isset($_GET['page']) && $_GET['page'] == "dashboard" && isset($_SESSION['admin_id'])):
?>
<div class="row">
<div class="col-md-12 mb-4">
<div class="dashboard-box">
<h2 class="fw-bold">
<i class="fa-solid fa-gauge"></i> Admin Dashboard
</h2>
<p class="text-muted">Karibu admin. Unaweza kuongeza blog post, picha, video link na downloadable file.</p>
</div>
</div>
<div class="col-md-5 mb-4">
<div class="dashboard-box">
<h4 class="fw-bold mb-3">Add New Blog Post</h4>
<form method="POST" enctype="multipart/form-data">
<label>Post Title</label>
<input type="text" name="title" class="form-control mb-3" required>
<label>Category</label>
<input type="text" name="category" class="form-control mb-3" placeholder="Education, News, Technology">
<label>Author</label>
<input type="text" name="author" class="form-control mb-3" value="<?= e($_SESSION['admin_name']) ?>">
<label>Blog Content</label>
<textarea name="content" class="form-control mb-3" required></textarea>
<label>YouTube Video Link</label>
<input type="url" name="video_link" class="form-control mb-3" placeholder="
<label>Upload Image</label>
<input type="file" name="image" class="form-control mb-3" accept="image/*">
<label>Upload File</label>
<input type="file" name="file_upload" class="form-control mb-3">
<button type="submit" name="add_post" class="btn btn-success btn-rounded">
<i class="fa-solid fa-paper-plane"></i> Publish Post
</button>
</form>
</div>
</div>
<div class="col-md-7">
<div class="dashboard-box">
<h4 class="fw-bold mb-3">All Blog Posts</h4>
<div class="table-responsive">
<table class="table table-bordered align-middle">
<tr class="table-primary">
<th>Title</th>
<th>Category</th>
<th>Date</th>
<th>Action</th>
</tr>
<?php
$posts = $conn->query("SELECT * FROM posts ORDER BY id DESC");
if ($posts->num_rows == 0):
?>
<tr>
<td colspan="4" class="text-center">No posts yet.</td>
</tr>
<?php endif; ?>
<?php while($p = $posts->fetch_assoc()): ?>
<tr>
<td><?= e($p['title']) ?></td>
<td><?= e($p['category']) ?></td>
<td><?= e($p['created_at']) ?></td>
<td>
<a href="blog.php?post=<?= $p['id'] ?>" class="btn btn-sm btn-info">View</a>
<a href="blog.php?page=edit&id=<?= $p['id'] ?>" class="btn btn-sm btn-warning">Edit</a>
<a href="blog.php?delete_post=<?= $p['id'] ?>" onclick="return confirm('Una uhakika unataka kufuta post hii?')" class="btn btn-sm btn-danger">Delete</a>
</td>
</tr>
<?php endwhile; ?>
</table>
</div>
</div>
</div>
</div>
<?php
/* =====================================================
EDIT POST
===================================================== */
elseif (isset($_GET['page']) && $_GET['page'] == "edit" && isset($_SESSION['admin_id'])):
$id = intval($_GET['id']);
$post = $conn->query("SELECT * FROM posts WHERE id=$id")->fetch_assoc();
if (!$post):
echo "<div class='alert alert-danger'>Post haijapatikana.</div>";
else:
?>
<div class="card p-4">
<h3 class="fw-bold mb-3">Edit Blog Post</h3>
<form method="POST" enctype="multipart/form-data">
<input type="hidden" name="post_id" value="<?= $post['id'] ?>">
<label>Post Title</label>
<input type="text" name="title" class="form-control mb-3" value="<?= e($post['title']) ?>" required>
<label>Category</label>
<input type="text" name="category" class="form-control mb-3" value="<?= e($post['category']) ?>">
<label>Author</label>
<input type="text" name="author" class="form-control mb-3" value="<?= e($post['author']) ?>">
<label>Blog Content</label>
<textarea name="content" class="form-control mb-3" required><?= e($post['content']) ?></textarea>
<label>YouTube Video Link</label>
<input type="url" name="video_link" class="form-control mb-3" value="<?= e($post['video_link']) ?>">
<label>Change Image</label>
<input type="file" name="image" class="form-control mb-3" accept="image/*">
<?php if($post['image']): ?>
<img src="<?= e($post['image']) ?>" width="160" class="rounded mb-3">
<?php endif; ?>
<label>Change File</label>
<input type="file" name="file_upload" class="form-control mb-3">
<?php if($post['file_upload']): ?>
<p>Current file: <a href="<?= e($post['file_upload']) ?>" download>Download</a></p>
<?php endif; ?>
<button type="submit" name="update_post" class="btn btn-primary btn-rounded">
Update Post
</button>
<a href="blog.php?page=dashboard" class="btn btn-secondary btn-rounded">Back</a>
</form>
</div>
<?php endif; ?>
<?php
/* =====================================================
SINGLE POST VIEW
===================================================== */
elseif (isset($_GET['post'])):
$id = intval($_GET['post']);
$post = $conn->query("SELECT * FROM posts WHERE id=$id")->fetch_assoc();
if (!$post):
echo "<div class='alert alert-danger'>Blog post haijapatikana.</div>";
else:
$video_id = youtubeID($post['video_link']);
?>
<div class="row justify-content-center">
<div class="col-md-10">
<div class="card p-4">
<span class="category-badge mb-3 d-inline-block"><?= e($post['category']) ?></span>
<h1 class="fw-bold"><?= e($post['title']) ?></h1>
<p class="text-muted">
<i class="fa-solid fa-user"></i> <?= e($post['author']) ?>
|
<i class="fa-solid fa-calendar"></i> <?= e($post['created_at']) ?>
</p>
<?php if($post['image']): ?>
<img src="<?= e($post['image']) ?>" class="single-img my-4">
<?php endif; ?>
<div class="content-box">
<?= nl2br(e($post['content'])) ?>
</div>
<?php if($video_id): ?>
<h4 class="mt-5 mb-3">Watch Video</h4>
<div class="ratio ratio-16x9">
<iframe src="https://www.youtube.com/embed/<?= e($video_id) ?>" allowfullscreen></iframe>
</div>
<?php endif; ?>
<?php if($post['file_upload']): ?>
<div class="mt-4">
<a href="<?= e($post['file_upload']) ?>" class="btn btn-success btn-rounded" download>
<i class="fa-solid fa-download"></i> Download Attached File
</a>
</div>
<?php endif; ?>
<div class="mt-4">
<a href="blog.php" class="btn btn-outline-primary btn-rounded">
<i class="fa-solid fa-arrow-left"></i> Back to Blog
</a>
</div>
</div>
<div class="card p-4 mt-4" id="comments">
<h4 class="fw-bold">Visitor Comments</h4>
<?php
$comments = $conn->query("SELECT * FROM comments WHERE post_id=$id ORDER BY id DESC");
if ($comments->num_rows == 0):
?>
<p class="text-muted">No comments yet. Be the first to comment.</p>
<?php endif; ?>
<?php while($c = $comments->fetch_assoc()): ?>
<div class="comment-box">
<strong><?= e($c['visitor_name']) ?></strong>
<p class="mb-1"><?= e($c['comment']) ?></p>
<small class="text-muted"><?= e($c['created_at']) ?></small>
</div>
<?php endwhile; ?>
<hr>
<h5>Add Comment</h5>
<form method="POST">
<input type="hidden" name="post_id" value="<?= $id ?>">
<input type="text" name="visitor_name" class="form-control mb-3" placeholder="Your name" required>
<textarea name="comment" class="form-control mb-3" placeholder="Write your comment..." required></textarea>
<button type="submit" name="add_comment" class="btn btn-primary btn-rounded">
Submit Comment
</button>
</form>
</div>
</div>
</div>
<?php endif; ?>
<?php
/* =====================================================
HOME / VISITOR BLOG PAGE
===================================================== */
else:
?>
<div class="row mb-4">
<div class="col-md-8">
<h2 class="fw-bold">Latest Blog Posts</h2>
<p class="text-muted">Explore latest articles, videos, images and downloadable resources.</p>
</div>
<div class="col-md-4">
<form method="GET">
<input type="text" name="search" class="form-control rounded-pill" placeholder="Search posts..." value="<?= e($_GET['search'] ?? '') ?>">
</form>
</div>
</div>
<div class="row">
<?php
$search = $_GET['search'] ?? "";
if ($search) {
$like = "%$search%";
$stmt = $conn->prepare("SELECT * FROM posts WHERE title LIKE ? OR category LIKE ? OR content LIKE ? ORDER BY id DESC");
$stmt->bind_param("sss", $like, $like, $like);
$stmt->execute();
$posts = $stmt->get_result();
} else {
$posts = $conn->query("SELECT * FROM posts ORDER BY id DESC");
}
if ($posts->num_rows == 0):
?>
<div class="col-md-12">
<div class="alert alert-info">No blog posts found.</div>
</div>
<?php endif; ?>
<?php while($p = $posts->fetch_assoc()): ?>
<div class="col-md-4 mb-4">
<div class="card post-card h-100">
<?php if($p['image']): ?>
<img src="<?= e($p['image']) ?>" class="post-img">
<?php else: ?>
<div style="height:240px;background:linear-gradient(135deg,#0d6efd,#07152e);color:white;display:flex;align-items:center;justify-content:center;">
<i class="fa-solid fa-image fa-4x"></i>
</div>
<?php endif; ?>
<div class="card-body d-flex flex-column">
<span class="category-badge mb-2"><?= e($p['category']) ?></span>
<h4 class="fw-bold"><?= e($p['title']) ?></h4>
<p class="text-muted small">
<i class="fa-solid fa-user"></i> <?= e($p['author']) ?> |
<i class="fa-solid fa-calendar"></i> <?= date("d M Y", strtotime($p['created_at'])) ?>
</p>
<p>
<?= e(substr(strip_tags($p['content']), 0, 140)) ?>...
</p>
<div class="mt-auto">
<a href="blog.php?post=<?= $p['id'] ?>" class="btn btn-primary btn-rounded">
Read More
</a>
<?php if($p['video_link']): ?>
<span class="badge bg-danger">
<i class="fa-brands fa-youtube"></i> Video
</span>
<?php endif; ?>
<?php if($p['file_upload']): ?>
<span class="badge bg-success">
<i class="fa-solid fa-file"></i> File
</span>
<?php endif; ?>
</div>
</div>
</div>
</div>
<?php endwhile; ?>
</div>
<?php endif; ?>
</div>
<footer class="footer text-center">
<div class="container">
<h4 class="fw-bold">My Professional Blog</h4>
<p>News • Education • Technology • Videos • Downloads</p>
<p>
<i class="fa-brands fa-facebook"></i> Facebook |
<i class="fa-brands fa-whatsapp"></i> WhatsApp |
<i class="fa-brands fa-youtube"></i> YouTube |
<i class="fa-brands fa-instagram"></i> Instagram
</p>
<p class="mb-0">© <?= date("Y") ?> All Rights Reserved.</p>
</div>
</footer>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
Admin login:
Username: admin
Password: admin123
Baada ya ku-run, folder hizi zitatengenezwa automatically ukianza ku-upload:
uploads/images
uploads/files
🚀 Unahitaji mfumo au website ya biashara?
Chagua huduma hapa chini kisha mteja bofya moja kwa moja kwenda kwenye ukurasa wa huduma au kuwasiliana nasi kwa WhatsApp.