TP6中請求和響應


TP6中請求的使用

一、請求的使用

//1、引入Request對象
use think\facade\Request;
//方式1、構造方法注入
 protected $request;
 public function __construct(Request $request)
{
    $this->request = $request;
}
//方式2、操作方法注入
public function index(Request $request)
{
    return $request->param('name');
}    
//方式3、靜態調用
public function index()
{
    return Request::param('name');
} 
//方式4、助手函數
public function index()
{
    return request()->param('name');
}
個人推薦使用助手函數方式或者靜態調用,比較簡單直觀

二、請求信息

常用的:
request()->host(); //當前訪問域名或者IP
request()->domain(); //當前包含協議的域名
request()->url();  //當前完整的url
request()->query(); //當前請求的query_string
request()->method(); //請求方法
request()->controller(); //當前控制器
request()->action(); //當前操作

三、獲取輸入變量

// 獲取當前請求的所有變量(經過過濾)
Request::param();
// 獲取當前請求未經過濾的所有變量
Request::param(false);
// 獲取當前請求的name變量
Request::param('name');
// 獲取部分變量
Request::param(['name', 'email']);

//判斷變量是否存在
Request::has('name','post');

//默認值
Request::get('name'); // 返回值為null
Request::get('name',''); // 返回值為空字符串
Request::get('name','default'); // 返回值為default

四、變量過濾

//框架默認沒有設置任何全局過濾規則,你可以在app\Request對象中設置filter全局過濾屬性:
namespace app;
class Request extends \think\Request
{
    protected $filter = ['htmlspecialchars'];
}

// 獲取get變量 並用htmlspecialchars函數過濾
Request::get('name','','htmlspecialchars'); 
// 獲取param變量 並用strip_tags函數過濾
Request::param('username','','strip_tags'); 
// 獲取post變量 並用org\Filter類的safeHtml方法過濾
Request::post('name','','org\Filter::safeHtml'); 

五、助手函數

//判斷變量是否定義
input('?get.id');
input('?post.name');
input('?name');

// 獲取單個參數
input('name'); 
// 獲取全部參數
input('');

 HTTP頭信息:

//獲取全部頭信息
$info = Request::header();
echo $info['accept'];
echo $info['accept-encoding'];
echo $info['user-agent'];
//獲取某個頭信息
$agent = Request::header('user-agent');
偽靜態:
在config/route.php 中設置
// URL偽靜態后綴  默認是 html
'url_html_suffix'       => 'html',

//如果設置為空,則可以支持任意的 后綴
'url_html_suffix'=>''

// 多個偽靜態后綴設置 用|分割
'url_html_suffix' => 'html|shtml|xml'

// 關閉偽靜態后綴訪問
'url_html_suffix' => false,

 

六、響應的使用

各種響應方式:

//響應輸出一個字符串
Route::get('hello/:name', function ($name) {
    return 'Hello,' . $name . '!';
});

或在控制器中
public function hello($name='thinkphp')
{
    return 'Hello,' . $name . '!';
}

//輸出json數據
$data = ['name' => 'thinkphp', 'status' => '1'];
return json($data);

//設置輸出的狀態碼
json($data,201);
view($data,401);

//設置輸出頭信息
json($data)->code(201)->header([
    'Cache-control' => 'no-cache,must-revalidate'
]);

//重定向
return redirect('http://www.thinkphp.cn');
//重定向使用 url傳參
redirect((string) url('hello',['name' => 'think']));

//文件下載
// download是系統封裝的一個助手函數
return download('image.jpg', 'my');

//直接下載內容
$data = '這是一個測試文件';
return download($data, 'test.txt', true);

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM