search
HomeBackend DevelopmentPHP TutorialPHP imitation blog park, personal blog (1)_PHP tutorial

PHP imitation blog park, personal blog (1)_PHP tutorial

Jul 13, 2016 pm 05:51 PM
phppersonalbutblogBlog GardenlandMore than half a yearEducational qualificationsoff and onSelf-studystill

I have a bachelor's degree and have been self-taught PHP for more than half a year, intermittently, but finally firmed up my mind and continued PHP, so I wrote this PHP blog to find a stable PHP job, without asking for a high salary, but Seeking a place of refuge. I can understand most English documents. I am not stupid and I love learning. If you are interested, please contact me! Come if you are sincere! qq:240382473
I will release all key codes and documentation instructions in 3-5 times, and all styles in the blog backend will be applied to Blog Park!
Description:
1. It does not completely adopt the MVC architecture, but the concept is like this. Because it is not possible to write a very stable MVC architecture.
2. JQUERY AJAX is almost never used because I am not very familiar with it and can’t use it freely. You can use AJAX for guestbooks, no problem.
3. There are several public classes, and other codes are all handwritten. Please point out any shortcomings. Thank you very much.
4. Criticism and guidance are welcome, but please give your reasons.

Closer to home: Let’s look at the database architecture first




The engines of these tables are MYISAM, which is convenient for access. (The yellow key represents the primary key; the blue diamond represents a non-empty field; the white diamond represents a null field) The links in the picture only represent a potential relationship between them and cannot be associated during operation. Because the search engine is MyISAM . Therefore, joint queries and multi-table operations are required.
I will select the most important special fields in the post and category tables to explain in detail, and the others will be mentioned as important.
post:
post_id
category_id varchar(10) This is the category used to index blog posts. The category_id here is also a string type, so multiple categories can be set for each blog post.
type varchar(20) This field is used to distinguish between post, article, and diary; it can also be set to postDraft, articleDraft;
visiable Whether the blog post is visible
Other commonly used fields include title, content, creation time, last modification time, number of views, number of comments, tags, allowed comments, and some reserved fields.
category:
parent, count_child_number, count_parent_number for future expansion
type can set the categories of photo albums, blog posts, and diaries respectively
Other common fields such as name, description, creation time, visibility
comment:
address user IP
user_agent User browser type

Other fields are omitted...
Server Architecture
PHP5.4.2 + MYSQL 5.523 + APACHE 2.2.22 + Windows NT ARIST-PC 6.1 build 7600 (Windows 7 Home Basic Edition) i586 (local)
Blog architecture
Backend directory:



Backend directory description:
assert stores various resources js, css, image
class stores our classes, commonly used classes such as database operation classes, paging classes, and most of our models. . .
extention stores extensions such as mce’s rich editor
config stores our configuration information
templates stores all templates (smarty is not used)
upload stores photos and other files
There will be some similar controllers in the admin root directory, such as index.php, post.php, article.php, photo.php

Let’s take a look at admin/config/config.php

ini_set( "display_errors", true );
date_default_timezone_set( "Asia/Shanghai" );
// root and direcotry separate
define('DS', DIRECTORY_SEPARATOR);
define('ROOT', dirname(dirname(__FILE__)));

// database information
// need hash
define( "DB_USERNAME", "****" );
define( "DB_PASSWORD", '*****' );
define( "DB_NAME", "blog" );

// important directory
define( "CLASS_PATH", "classes" );
define( "TEMPLATE_PATH", "templates" );

// user imformation
define( "ADMIN_USERNAME", "admin" );
define( "ADMIN_PASSWORD", '$2a$08$wim8kpwHhAKa6MBSsGUMGOYfjkU1xvRKd4Fxwal.wj8dqFboCVSFawim8kpwHhAKa6MBSsGUMGO');
 // hash and verified the password
function hasher($info, $encdata = false){
  $strength = "08";
  //if encrypted data is passed, check it against input ($info)
  if ($encdata) {
    if (substr($encdata, 0, 60) == crypt($info, "$2a$".$strength."$".substr($encdata, 60))) {
      return true;
    }else {
      return false;
    }
  } else {
  //make a salt and hash it with input, and add salt to end
  $salt = "";
  for ($i = 0; $i     $salt .= substr("./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", mt_rand(0, 63), 1);
  }
  //return 82 char string (60 char hash & 22 char salt)
    return crypt($info, "$2a$".$strength."$".$salt).$salt;
    }
}
 
function __autoload($className) {
    if (file_exists(ROOT . DS . 'classes' . DS . strtolower($className) . '.class.php')) {
        require_once(ROOT . DS . 'classes' . DS . strtolower($className) . '.class.php');
    } else {
        /* Error Generation Code Here */
    }
}
 
这里我们定义了一些基本常量,和几个函数。
__autoload() 函数加载 admin/class/ 中的所有类
用 hasher() 函数加密了一个 88位的 不可逆密码, 登录过程就是用config.php 中的常量和 hasher( ) 函数来进行验证。
来看我们的 admin/index.php 后台控制器 这个控制器主页 显示一些博客的相关数据
 
 
require_once( "config/config.php" );
session_start( );
$action = isset( $_GET['action'] ) ? $_GET['action'] : "";
$username = isset( $_SESSION['username'] ) ? $_SESSION['username'] : "";
 
if ( $action != "login" && $action != "logout" && !$username ) {
  login();
  exit;
}

switch( $action ){
    case "login" :
        login( ) ;
    break;
   
    case "logout";
        logout( );
    break;
   
    default :    
        admin( );
    break;
}

function login( ){
    $results['pageTitle'] = "Login Form";
    // handle login
    if( isset( $_POST['login'] ) ){
        // we simple verify it from constant variable
        // if we need to verify the user from database , do this later
        // $user = new User ;
        // $user->isValidateUser( $name, $password );
       
        if ( $_POST['username'] == ADMIN_USERNAME &&  $_POST['password'] == hasher($_POST['password'], ADMIN_PASSWORD ) ){
            // register a session data
            $_SESSION['username'] = ADMIN_USERNAME ;
            // location to admin page
            header( "Location:  index.php");
        } else {
             // Login failed: display an error message to the user
              $results['errorMessage'] = "Incorrect username or password. Please try again.";
              require( TEMPLATE_PATH . "/loginForm.php" );
        }
    } else {
             require( TEMPLATE_PATH . "/loginForm.php" );
    }
}

function admin( ){
    $results['pageTitle'] = "Administrator Page";
     require( TEMPLATE_PATH . "/admin.php" );
}

function logout( ){
    $results['pageTitle'] = "Login Page";
    unset( $_SESSION['username'] );
    header( "Location: index.php ");
}
 
 
 
这个设计模式是从一个老外那里学的!
原理就是:
首先我们加载我们的config.php, 初始化session变量,获得 $action 这个重要变量的值;
然后我们判断 $action 和 $username 的值, 如果用户没有登录以及用户名为空,返回登录页面;
如果用户正确输入了用户名和密码,则注册一个session 变量 $username,然后跳转到主页面 index.php, 这时我们会调用默认的 $action  admin( ), 这个函数会加载一个模版admin.php;里面有个数组变量 $results['pageTitle'],以及我们的后台博客样式框架。
如果用户输入错了,则给出提示信息。
 
这个设计理念的核心就是, give {action} then {do something}
我们会在后面的代码中反复看到。
 
 
这个就是博客后台的框架样式,从博客园copy 来的,采用表格布局的,兼容的,可自定义其他样式的,简单的,实用的,可扩展的,完美后台框架。



 

这个样式在其他的浏览器中表现同样兼容,写这篇博文的时候,我已完成了部分功能。 下一篇:实现随笔,文章,日记 以及他们分类的CRUD。
ps:这些操作还没有使用ajax,因为我对ajax还不熟悉。

 


摘自 warcraft



www.bkjia.comtruehttp://www.bkjia.com/PHPjc/478183.htmlTechArticle本人本科学历,自学PHP大半年多了,断断续续地,但是最终还是坚定了我的想法,将PHP继续下去,所以写这个PHP的博客是为了找个稳定的...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools