簡體   English   中英

未定義變量和未定義索引php錯誤

[英]undefined variable and undefined index php errors

我被賦予刪除未定義變量和未定義索引錯誤的任務,我知道該如何

$value = isset($_POST['value']) ? $_POST['value'] : '';

問題是這太耗時了,我預測還沒有設置2000個以上的變量$ _GET,$ _ POST。 那么,我可以使用正則表達式來快速設置這些變量嗎?

我如何做正則表達式來將此$category = $_GET['c']更改為此

$category = isset($_GET['c']) ? $_GET['c'] : '' $category = isset($_GET['c']) ? $_GET['c'] : ''

以及我如何做正則表達式將if($page or $category or $profile)更改為此

if(isset($page) or isset($category) or isset($profile))嗎?

這是我可以通過在記事本++中使用正則表達式查找和替換想到的最佳方法。 我假設超過2000個PHP變量/索引未定義錯誤。 如何解決此問題而不關閉錯誤?

您不應該使用正則表達式,因為它很繁瑣:)如果我對您的問題理解正確,則可以使用此方法執行此操作,使用這種方法,無論有多少參數包含POST或GET,您都可以通過foreach對其進行過濾循環並獲取帶有參數的干凈數組,也可以使其成為返回數組的函數,然后只需要檢查if_array_key_exests()並執行操作即可。

 $_POST = ["user"=>"1", "num"=>2];
 $_GET  = ["user" => '', "num"=>1];


//function method
 function filter($array)
 {
   $arr = array();

   foreach ($array as $key => $val) {

    if (!empty($val)) {
        $arr[$key] = $val;
    } 
  }

  return $arr;
}

沒有功能

 $post = array();
 foreach ($_POST as $key => $val) {
        if (!empty($val)) {
            $post[$key] = $val;
        }
 }

 $get = array();
 foreach ($_GET as $key => $val) {
         if (!empty($val)) {
             $get[$key] = $val;
         }  
 }

對於您的第一個問題,更換類似

(\$\w+)\s*=\s*\$_GET\[['"]?(\w+)['"]?\]\s*;

通過

$1 = isset($_GET['$2']) ? $_GET['$2'] : '';

應該管用。

關於第二個,我不知道使用可變數量的變量是否可行。 這一項適用於3個變量,替換

if\s*\(\s*\s*(\$\w+)\s+or\s+(\$\w+)\s+or\s+(\$\w+)\s*\)

通過

if (isset($1) or isset($2) or isset($3))

您可以在搜索中的最后一個\\s*之前添加另一個\\s+or\\s+(\\$\\w+) ,並在替換中添加另一個or isset($4)等4個變量,等等。

我建議您一一替換它們,而不要一次全部替換;-)

另請注意, if ($a)if (isset($a)) 考慮這樣的事情:

// query string is a=0
$a = $_GET['a'];
if ($a) // will be false
if (isset($a)) // will be true
if (!empty($a)) // will be false

因此,也許您想使用!empty()而不是isset() 這也應該在沒有通知的情況下起作用。

resove first issue:
define a function like:
function global_get($key){
    return isset($_GET[$key])?$_GET[$key]:'';
}

then use sed(linux tool) to replace all parts like this(it will modify all the $_GET[.*] of php extension files in your project,so be careful to use this):
find /yourproject -name "*.php" -exec sed -i "s/\$_GET\[\([^]]*\)\]/global_get(\1)/" \;

you may modify this command to apply your own demand.


The second issue could be harmful if you use the regex expression because it is hard to make a role rule.so I recommend you to replace manually.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM