search
HomePHP FrameworkThinkPHPHow to configure routing in ThinkPHP to hide the background!

ThinkPHPHow to hide the background? The following article will introduce to you how ThinkPHP cleverly uses routing rules to hide the background, making your website more secure!

How to configure routing in ThinkPHP to hide the background!

As we all know, if the backend module of the thinkphp framework is named admin, you can directly use http://domain name/admin This access method is very convenient, but it also has great security risks. Hackers can easily guess your backend and then brute force the backend. So is there any way to solve this hidden danger? Let's discuss how to use routing rules to modify the backend path to prevent hackers from knowing our backend entrance. There are many tutorials on hiding the background admin on the Internet, but the really useful one is this routing rule method.

How to configure routing in ThinkPHP to hide the background!

The first step is to add setting parameters in the background that can modify the name of the background module

1,

How to configure routing in ThinkPHP to hide the background!

2. The key code to save the settings is as follows:

if(request()->isPost()) {
	$data=input('post.');
	//获取系统全部模块名
	$system_module = [];
	foreach (scandir(APP_PATH) as $dir) {
		if($dir == '.' || $dir == '..') {
			continue;
		}
		if(is_dir(APP_PATH.$dir)) {
			array_push($system_module, $dir);
		}
	}
	foreach ($data as $key => $vo) {
		if($key == 'admin_module' && $vo != 'admin' && in_array($vo, $system_module)) {
			$this->error('后台地址不能与现有系统模块名同名');
		}
	}
}

Notes:

  • admin_module is my database The key
  • APP_PATH that saves the background module name is a constant of thinkphp5.0 version. If it is other versions, please modify it yourself.

The second step is to read the configuration information of the website in application/common.php

1. The main structure of the config data table is as follows:

DROP TABLE IF EXISTS `config`;
CREATE TABLE `config` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `key` varchar(255) DEFAULT NULL,
  `val` text,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

2. sysconfig($name) method: Get the corresponding value based on the key name

<?php
use think\Cache;
use app\common\model\Config;

/**
 * 获取或配置系统参数
 * @param string $name  参数名称
 * @return string
 */
function sysconfig($name) {
	$config = Cache::get(&#39;config&#39;);
    if (empty($config)) {
        $config = Config::column(&#39;key,val&#39;);
		Cache::set(&#39;config&#39;,$config,1800);//缓存30分钟 
    }
    return isset($config[$name]) ? $config[$name] : &#39;&#39;;
}

Supplement:

1. If it is only a system for personal use, If you don’t want to be so troublesome, you can also add the following configuration directly to config.php:

return [
    // +----------------------------------------------------------------------
    // | 应用设置
    // +----------------------------------------------------------------------
	// 后台模块名
    &#39;admin_module&#39;           => &#39;myadmin&#39;,
]

2, and then call it directly in the project:

$admin_module = Config(&#39;admin_module&#39;);

The third step, route setting application/route.php

<?php
use think\route;

$route_config = [
	&#39;index&#39;=>&#39;index/index&#39;,
];
//1.获取后台模块
$admin_module = sysconfig(&#39;admin_module&#39;);
if ($admin_module == &#39;&#39;) {
    $admin_module = &#39;admin&#39;;
}
//2.设置后台路由
if ($admin_module != &#39;admin&#39;) {
    $admin_route_config = [
		//路由禁止:原理是把它指到非登陆地址,在没有登陆情况下,跳转到404页面;
		&#39;admin/$&#39; => &#39;admin/login/jump&#39;,
		&#39;admin/login$&#39; => &#39;admin/login/jump&#39;,
		&#39;admin/login/index&#39; => &#39;admin/login/jump&#39;,
		$admin_module . &#39;/$&#39; => &#39;admin/login/index&#39;,	
    ];
    $route_config = array_merge($route_config, $admin_route_config);
}
return $route_config;

The fourth step, add the jump() method for jump verification in the login controller Login.php

1. This jump() method is actually the designated method for prohibiting routing in our third step

public function jump() {
	if(!Session::has(&#39;uid&#39;)) {
		$request = Request::instance();
		if(sysconfig(&#39;admin_module&#39;) == &#39;admin&#39; || sysconfig(&#39;admin_module&#39;) == &#39;&#39;) {
			$this->redirect(&#39;@admin/login/index&#39;);
		} else {
			header("HTTP/1.1 404 Not Found");
			return $this->fetch(APP_PATH.&#39;/404.html&#39;);
		}
	} else {
		$this->redirect(&#39;@admin/index/index&#39;);
	}
}

2. The code in jump() above has only one function, that is If you are not logged in, accessing a prohibited route will jump to the 404 page, as follows:

How to configure routing in ThinkPHP to hide the background!

3. The 404.html page is placed in the application directory, and the code is as follows :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>很抱歉,此页面暂时找不到!</title>

<style type="text/css">
body {margin: 0px; padding:0px; font-family:"微软雅黑", Arial, "Trebuchet MS", Verdana, Georgia,Baskerville,Palatino,Times; font-size:16px;}
div{margin-left:auto; margin-right:auto;}
a {text-decoration: none; color: #1064A0;}
a:hover {color: #0078D2;}
img { border:none; }
h1,h2,h3,h4 {
/*	display:block;*/
	margin:0;
	font-weight:normal; 
	font-family: "微软雅黑", Arial, "Trebuchet MS", Helvetica, Verdana ; 
}
h1{font-size:44px; color:#0188DE; padding:20px 0px 10px 0px;}
h2{color:#0188DE; font-size:16px; padding:10px 0px 40px 0px;}

#page{width:910px; padding:20px 20px 40px 20px; margin-top:80px;}
.button{width:180px; height:28px; margin-left:0px; margin-top:10px; background:#009CFF; border-bottom:4px solid #0188DE; text-align:center;}
.button a{width:180px; height:28px; display:block; font-size:14px; color:#fff; }
.button a:hover{ background:#5BBFFF;}
</style>

</head>
<body>

<div id="page" style="border-style:dashed;border-color:#e4e4e4;line-height:30px;">
	<h1 id="抱歉-找不到此页面">抱歉,找不到此页面~</h1>
	<h2 id="Sorry-nbsp-the-nbsp-page-nbsp-you-re-nbsp-trying-nbsp-to-nbsp-find-nbsp-has-nbsp-moved-nbsp">Sorry, the page you&#39;re trying to find has moved. </h2>
	<font color="#666666">你请求访问的页面,暂时找不到!</font><br /><br />
	<div class="button">
		<a href="javascript:;" onClick="javascript :history.back(-1);" title="返回上一页">返回上一页</a>
	</div>
</div>

</body>
</html>

4. How to log out

public function logout() {
	if(Session::has(&#39;adminid&#39;)) {
		Session::delete(&#39;adminid&#39;);
	}
	$this->redirect(url(&#39;@&#39;.sysconfig(&#39;admin_module&#39;)));
}

Original address: https://juejin.cn/post/6981428649765371940

More programming For related knowledge, please visit: Introduction to Programming! !

The above is the detailed content of How to configure routing in ThinkPHP to hide the background!. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
What Are the Key Features of ThinkPHP's Built-in Testing Framework?What Are the Key Features of ThinkPHP's Built-in Testing Framework?Mar 18, 2025 pm 05:01 PM

The article discusses ThinkPHP's built-in testing framework, highlighting its key features like unit and integration testing, and how it enhances application reliability through early bug detection and improved code quality.

How to Use ThinkPHP for Building Real-Time Stock Market Data Feeds?How to Use ThinkPHP for Building Real-Time Stock Market Data Feeds?Mar 18, 2025 pm 04:57 PM

Article discusses using ThinkPHP for real-time stock market data feeds, focusing on setup, data accuracy, optimization, and security measures.

What Are the Key Considerations for Using ThinkPHP in a Serverless Architecture?What Are the Key Considerations for Using ThinkPHP in a Serverless Architecture?Mar 18, 2025 pm 04:54 PM

The article discusses key considerations for using ThinkPHP in serverless architectures, focusing on performance optimization, stateless design, and security. It highlights benefits like cost efficiency and scalability, but also addresses challenges

How to Implement Service Discovery and Load Balancing in ThinkPHP Microservices?How to Implement Service Discovery and Load Balancing in ThinkPHP Microservices?Mar 18, 2025 pm 04:51 PM

The article discusses implementing service discovery and load balancing in ThinkPHP microservices, focusing on setup, best practices, integration methods, and recommended tools.[159 characters]

What Are the Advanced Features of ThinkPHP's Dependency Injection Container?What Are the Advanced Features of ThinkPHP's Dependency Injection Container?Mar 18, 2025 pm 04:50 PM

ThinkPHP's IoC container offers advanced features like lazy loading, contextual binding, and method injection for efficient dependency management in PHP apps.Character count: 159

How to Use ThinkPHP for Building Real-Time Collaboration Tools?How to Use ThinkPHP for Building Real-Time Collaboration Tools?Mar 18, 2025 pm 04:49 PM

The article discusses using ThinkPHP to build real-time collaboration tools, focusing on setup, WebSocket integration, and security best practices.

What Are the Key Benefits of Using ThinkPHP for Building SaaS Applications?What Are the Key Benefits of Using ThinkPHP for Building SaaS Applications?Mar 18, 2025 pm 04:46 PM

ThinkPHP benefits SaaS apps with its lightweight design, MVC architecture, and extensibility. It enhances scalability, speeds development, and improves security through various features.

How to Build a Distributed Task Queue System with ThinkPHP and RabbitMQ?How to Build a Distributed Task Queue System with ThinkPHP and RabbitMQ?Mar 18, 2025 pm 04:45 PM

The article outlines building a distributed task queue system using ThinkPHP and RabbitMQ, focusing on installation, configuration, task management, and scalability. Key issues include ensuring high availability, avoiding common pitfalls like imprope

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment