首页 > 解决方案 > PHP 警告:extract() 期望参数 1 是数组

问题描述

在错误日志中我收到此错误PHP Warning: extract() expects parameter 1 to be array,这将使服务器超载并增加 CPU 使用率。我的 php 函数有什么问题。

<?php
function rel2abs($rel, $base) {
  if (empty($rel)) $rel = ".";
  if (parse_url($rel, PHP_URL_SCHEME) != "" || strpos($rel, "//") === 0) return $rel; 
  if ($rel[0] == "#" || $rel[0] == "?") return $base.$rel; 
  extract(parse_url($base)); 
  $path = isset($path) ? preg_replace('#/[^/]*$#', "", $path) : "/"; 
  if ($rel[0] == '/') $path = ""; 
  $port = isset($port) && $port != 80 ? ":" . $port : "";
  $auth = "";
  if (isset($user)) {
    $auth = $user;
    if (isset($pass)) {
      $auth .= ":" . $pass;
    }
    $auth .= "@";
  }
  $abs = "$auth$host$path$port/$rel"; //Dirty absolute URL
  for ($n = 1; $n > 0; $abs = preg_replace(array("#(/\.?/)#", "#/(?!\.\.)[^/]+/\.\./#"), "/", $abs, -1, $n)) {} 
  return $scheme . "://" . $abs;
}

标签: php

解决方案


正如上面评论中提到的,parse_url()如果函数 fan 无法解析 URL,则返回 false。并且extract()需要一个数组作为第一个参数(不是布尔值)。

所以而不是:

extract(parse_url($base));

你需要这样的东西:

$parsedUrl = parse_url($base);
if ($parsedUrl === false) {
    throw new \RuntimeException(sprintf('Unable to parse url [%s]', $base));
}

extract($parsedUrl);

推荐阅读