baseController.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. namespace common\components;
  3. use Yii;
  4. use yii\web\Controller;
  5. /**
  6. * 前后台基类
  7. */
  8. class baseController extends Controller
  9. {
  10. public $imgUrl, $adminUrl, $frontUrl, $openUrl, $picUrl, $wwwUrl;
  11. public function beforeAction($action)
  12. {
  13. // 新增:全局安全检查
  14. $this->securityCheck();
  15. $hostInfo = Yii::$app->urlManager->getHostInfo();
  16. $parse = parse_url($hostInfo);
  17. $host = $parse['host'];
  18. $pos = strpos($host, '.') + 1;
  19. $pre = substr($host, $pos);
  20. $this->imgUrl = 'http://img.' . $pre;
  21. $this->adminUrl = 'http://a.' . $pre;
  22. $this->frontUrl = 'http://m.' . $pre;
  23. $this->openUrl = 'http://o.' . $pre;
  24. $this->picUrl = 'http://pic.' . $pre;//阿里云oss图床
  25. $this->wwwUrl = 'http://www.' . $pre;
  26. return parent::beforeAction($action);
  27. }
  28. /**
  29. * 全局安全检查
  30. */
  31. protected function securityCheck()
  32. {
  33. $request = Yii::$app->request;
  34. $this->checkSuspiciousParameters($request);
  35. }
  36. /**
  37. * 检查可疑参数
  38. */
  39. protected function checkSuspiciousParameters($request)
  40. {
  41. $dangerousPatterns = [
  42. // 代码执行相关
  43. '/eval\s*\(/i',
  44. '/exec\s*\(/i',
  45. '/system\s*\(/i',
  46. '/passthru\s*\(/i',
  47. '/shell_exec\s*\(/i',
  48. '/proc_open\s*\(/i',
  49. '/popen\s*\(/i',
  50. ];
  51. foreach (['get', 'post'] as $method) {
  52. $params = $request->$method();
  53. foreach ($params as $value) {
  54. $value = strval($value);
  55. foreach ($dangerousPatterns as $pattern) {
  56. if (preg_match($pattern, $value)) {
  57. util::fail("非法参数:{$value}。提示来自baseController");
  58. }
  59. }
  60. }
  61. }
  62. }
  63. }