打开c:\Windows\System32\drivers\etc\host文件
添加
127.0.0.1 www.tp5.com
修改完成之后,保存
使用cmd命令行去ping该域名
[外链图片转存失败(img-KeaaQHkd-1568536528011)(C:\Users\王龙\Desktop\批注 2019-08-10 124500.jpg)]
若ping得本机则成功。
修改服务器配置,使键入域名时跳转到指定文件目录下
服务器使用apache时,修改Httpd.conf
添加内容
DocumentRoot "C:\wamp\www\tp5\public"
ServerName www.tp5.com
即可以使用www.tp5.com域名直接进入C:\wamp\www\tp5\public文件目录下
application:应用目录
extend :拓展类库
public :入口文件
runtime :运行缓存文件
thinkphp :框架核心文件
vendor :第三方类库
TP5.0\application\config.php 项目配置文件
开发环境开启debug模式
TP5.0\application\database.php 数据库配置文件
使用$this->request安全对象来获取内容,request->param() 用来代替_GET_,POST
模块/控制器/方法
控制器名首字母大写
加’_'之后,解析url时去掉‘_’,并且将紧邻字母转换为大写
路由
Route::rule(‘路由表达式’,‘路由地址’,‘请求类型’,‘路由参数(数组)’,‘变量规则(数组)’);
use think\Route;
return [
Route::rule('hello/[:name]','index/index/hello'),
...
];
//或
return [
'hello/[:name]' => ['index/index/index2',['methon' => 'get']],
...
];
当访问http://localhost/hello/name时,会自动路由到http://localhost/index/index/hello/name
未添加动态路由时
添加内容如下
'index2/[:name]' => ['index/index/index2',['method' => 'get']],
添加动态路由后
public function today($year = 1970 ,$mouth = 1,$day = 1)
{
echo "今天是".$year."年".$mouth."月".$day."日";
}
添加动态路由,并限制传输年份为4个数字,月份为2个数字
'today/[:year]/[:mouth]/[:day]' => ['index/index/today',['method' => 'get'],['year' => '\d{4}','mouth' => '\d{2}']],
public function url1()
{
echo url('index2','name=aaa');
//内置url函数,第一个参数若不全时一般默认为当前模块下当前控制器下的index2方法,并且传值名为name,值为aaa,
}
效果:
use think\Request;
public function myRequest($name = 'hello')
{
echo $name."
";
echo "request参数
";
$request = Request::instance(); //初始化request对象
print_r( $request -> param()); //使用request对象的param()方法查询传递参数
echo "
";
print_r( $request -> cookie()); //查询cookie值
echo "
";
echo $request -> param('name');
//$request 属性绑定
$request->bind('user','wl');
}
查询结果
public function myResponse()
{
//$data = ['name' => 'wl','status' => '1'];
//return $data; //格式不正确
//return json($data); //屏幕打印json格式的data
//return json($data,201);//屏幕打印json格式的data,并修改status
//return xml($data); //屏幕打印xml格式的data
$this->assign('name','wl');
return $this->fetch('index'); //跳转到对应index方法view模板文件,并传值
//$this->success("成功跳转",'myRequest'); //延时成功跳转
//$this->error("失败跳转","index2"); //延时失败跳转
//$this->redirect("http://www.baidu.com");//直接跳转
}
user think\Db
$result = Db::connect('databaseName')->query('SQLs');
/*databaseName需提前在database.php中配置,SQLs为sql语句,*/
$db = Db::connect('db');
$db->query('SQLs')
use think\Db;
Db::table('type_tableName')
->insert(['id' => 6,'name' => 'think','status' => '1']); //插入
Db::table('type_tableName')
->where('id',2)
->update(['name' => "hello"]); //更新
Db::table('type_tableName')
->where('id',2)
->select(); //查找
Db::table('type_tableName')
->where('id',2)
->delete(); //删除
/*比较麻烦,当修改了database.php中的前缀时,需逐一修改SQL语句*/
Db::name('tableName')
->insert(['id' => 6,'name' => 'think','status' => '1']) //插入
/*当执行插入时,会在database.php中自动搜索前缀名加上,这样就不需要多处修改,较为简洁*/
//更新数据库数据时,若使用了关联数组进行更新,则关联数组中必须含有主键,或语句中有where语句,例如
$data = [
'id' => input('id'),
'title' => input('articletitle'),
'descr' =>input('articledescr'),
'keywords' => input('articlekeyword'),
'content' =>input('articlecontent'),
'author' => input('articleauthor'),
'time' => time(),
'cateid' => input('articlecateid'),
];
$save = db('article')->update($data);
//id 为主键,若无主键,则会报 缺少更新条件 错误
use think\Db;
Db::table('type_tableName')
->where('status',1) //status为1
->order('create_time') //按create_time排序
->limit(10) //十条记录
->select();
/*这里的where、order、limit就被称为链式操作方法,除了select必须放在最后,其他没有先后顺序之分*/
Db::table("tp_article")
->alias('a')
->join('tp_cate c','a.cateid=c.id')
->field('a.id,a.cateid,a.title,c.catename')
->select();
//意为在tp_article和tp_cate表里进行联合查找,查找articel.cateid=cate.id的a.id,a.cateid,a.title,c.catename属性内容
更多相关信息,参考点击链接
一系列基础操作,要么全部成功,要么全部失败
将mysql的存储引擎设为InnoDB
使用transaction方法操作数据库事务,当发生异常时会自动回滚
//自动控制事务处理
use think\Db;
Db::transaction(function(){
Db::table('type_tableName')->find(1);
Db::table('type_tableName')->delete(1);
});
//手动控制事务
Db::startTrans(); //启动事务
try{
Db::table('type_tableName')->find(1);
Db::table('type_tableName')->delete(1);
Db::commit(); //提交事务
}catch(\Exception $e){
Db::rollback(); //回滚事务
}
//模板输出,需要在相应控制器的方法中声明,若声明不正确或未声明,报未定义error
//控制器,变量
$admin = 'hello';
//模板,输出变量
{
$admin}
//控制器,数组
$admin = [
'name' => 'wl',
'age' => '20',
'sex' => 'man',
];
$this->assign('admin',$admin)
//模板,输出数组元素
{
$admin['name']}
//控制器,类
$admin = new Admin();
//模板,输出类内元素
{
$admin:age}
{
$admin->name}
//当使用比较标签时,可以如下操作,意为当$a.value等于1时,输出keyvalue
{
compare name="$a.value" value="1" type="eq"}keyvalue{
/compare}
/*
C:\wamp\www\tp5\application\admin\validate
该目录下为验证期目录,新建名称与控制器相同的验证器文件
*/
namespace app\admin\validate;
use think\Validate;
class Cate extends Validate
{
protected $rule = [
'catename|栏目名称' => 'require|max:30|unique:cate',
];
//验证期规则
protected $message = [
'cate.require' => '栏目名称不能为空',
'cate.max' => '栏目名称长度不能大于30个字符',
'cate.unique' => '栏目名称已经存在',
];
//验证期相应提示信息
protected $scene = [
'edit' => ['catename'],
'add' => ['catename'],
];
}
?>
/*
C:\wamp\www\tp5\application\admin\controller
该文件夹下为控制器文件
调用验证器代码如下
*/
$data = [
catename = input('catename'),
];
$validate = \think\Loader::validate('Cate'); //实例化验证器类
if($validate->scene('edit')->check($data) === false) //注意使用全等===来进行判断,否则某些验证规则无法生效,如unique等
{
$this->error($validate->getError());
die;
}
//图片上传功能,前端页面模板
<html>
<head>
<title>图片上传测试</title>
</head>
<body>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="articlepic" >
<input type="submit">
</form>
</body>
</html>
//注意form表单中的enctype属性填写,该属性值为"multipart/form-data",该部分意为form表单中的上传数据不止有文本数据,也有文件等二进制数据,该属性的默认值为"application/x-www-form-urlencoded",此时表示上传前编码所有数据,不能传送文件类型的数据
//后端模板
public function addpic()
{
$file = request()->file('articlepic');
if(request()->isPost())
{
if($file)
{
$info = $file->move(ROOT_PATH.'public'.DS.'static/uploads');
echo $info->getExtension(); //文件类型
echo $info->getSavename(); //文件保存名
echo $info->getFilename();
}
else
{
echo "上传失败";
//echo $file->getError();
}
}
return $this->fetch();
}
//例如:move函数中需要将文件挪到/public/static/uploads文件夹下,则参数写为“ ROOT_PATH.'public'.DS.'static/uploads' ”即可,
需要引入想对应版本的类;负责会发生引入错误
例如,使用TP5.0时,对应版本为1.*
在TP5.0项目根目录下打开cmd,官方指导手册提示输入
composer require topthink/think-captcha
实测在TP5.0中会报错,错误内容如下:
Warning: Accessing repo.packagist.org over http which is an insecure protocol.
Using version ^3.0 for topthink/think-captcha
./composer.json has been updated
Loading composer repositories with package information
Warning: Accessing repo.packagist.org over http which is an insecure protocol.
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.
Problem 1
- topthink/think-captcha v3.0.1 requires topthink/framework ^6.0.0 -> satisfiable by topthink/framework[6.0.x-dev, v6.0.0-rc2, v6.0.0-rc3, v6.0.0-rc4] but these conflict with your requirements or minimum-stability.
- topthink/think-captcha v3.0.0 requires topthink/framework ^6.0.0 -> satisfiable by topthink/framework[6.0.x-dev, v6.0.0-rc2, v6.0.0-rc3, v6.0.0-rc4] but these conflict with your requirements or minimum-stability.
- topthink/think-captcha v3.0.1 requires topthink/framework ^6.0.0 -> satisfiable by topthink/framework[6.0.x-dev, v6.0.0-rc2, v6.0.0-rc3, v6.0.0-rc4] but these conflict with your requirements or minimum-stability.
- topthink/think-captcha v3.0.0 requires topthink/framework ^6.0.0 -> satisfiable by topthink/framework[6.0.x-dev, v6.0.0-rc2, v6.0.0-rc3, v6.0.0-rc4] but these conflict with your requirements or minimum-stability.
- Installation request for topthink/think-captcha ^3.0 -> satisfiable by topthink/think-captcha[v3.0.0, v3.0.1].
Installation failed, reverting ./composer.json to its original content.
原因是由于版本不匹配
正确引入验证码类方法:
composer require topthink/think-captcha=1.* //ThinkPHP5.0
composer require topthink/think-captcha=2.0 //ThinkPHP5.1
下载成功之后:
Warning: Accessing repo.packagist.org over http which is an insecure protocol.
./composer.json has been updated
Loading composer repositories with package information
Warning: Accessing repo.packagist.org over http which is an insecure protocol.
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
- Installing topthink/think-captcha (v1.0.8): Downloading (100%)
Invalid zip file, retrying...
- Installing topthink/think-captcha (v1.0.8): Downloading (60%)
Downloading (100%)
Writing lock file
Generating autoload files
之后就可以成功进行验证码的使用
PS:ThinkPHP5.0的官方拓展库版本号为1.*;ThinkPHP5.1的拓展库版本号为2.0;
在模板中显示验证码
在控制器中操作验证码进行验证
$data = input('code');
if(!captcha_check($data)){
return $this->error('验证码错误');
};
实现单击刷新验证码
<img src="{:captcha_src()}" alt="captcha" title="单击刷新验证码" style="width:120px;float:left"
onclick="this.src='{:captcha_src()}?'+Math.random()"/>
session的使用,记录用户登录信息
/*
Session::delete();
Session::clear();
区别
delete()可以指定删除域和删除内容
clear()清空session中的所有信息
*/
Session::delete('username','think'); //删除think作用域下的username值
Session::delete('uid'); //删除当前作用域下的uid值
/**
* 删除session数据
* @param string|array $name session名称
* @param string|null $prefix 作用域(前缀)
* @return void
*/
public static function delete($name, $prefix = null)
{
empty(self::$init) && self::boot();
$prefix = !is_null($prefix) ? $prefix : self::$prefix;
if (is_array($name)) {
foreach ($name as $key) {
self::delete($key, $prefix);
}
} elseif (strpos($name, '.')) {
list($name1, $name2) = explode('.', $name);
if ($prefix) {
unset($_SESSION[$prefix][$name1][$name2]);
} else {
unset($_SESSION[$name1][$name2]);
}
} else {
if ($prefix) {
unset($_SESSION[$prefix][$name]);
} else {
unset($_SESSION[$name]);
}
}
}
/**
* 清空session数据
* @param string|null $prefix 作用域(前缀)
* @return void
*/
public static function clear($prefix = null)
{
empty(self::$init) && self::boot();
$prefix = !is_null($prefix) ? $prefix : self::$prefix;
if ($prefix) {
unset($_SESSION[$prefix]);
} else {
$_SESSION = [];
}
}