首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHPCMS getJSON 回調失效解決:遠程調用方法必須加 public_ 前綴

     編輯:PHP 相關知識

現象

前端 $.getJSON() 請求 PHPCMS 後端,JSON 格式正確、JS 語法無誤,但 success 回調永不觸發,alert 無輸出。

根因:check_hash() 安全驗證攔截

PHPCMS 核心類 common.inc.php 中的 check_hash() 強制驗證路由方法名:

// 簡化邏輯
if (!preg_match('/^public_/', ROUTE_A) 
    && !(ROUTE_M == 'admin' && ROUTE_C == 'index')
    && !in_array(ROUTE_A, ['login', 'register'])
    && isset($_SESSION['pc_hash']) && $_SESSION['pc_hash'] !== $_GET['pc_hash']) {
    showmessage('hash_check_false');
}

結論:非後台、非登入註冊、無有效 pc_hash 的遠程請求,**方法名必須以 public_ 開頭**才能通過驗證。

解決方案:重命名控制器方法

<?php
// 修改前:mobile_getjson_ids() → 403 攔截
// 修改後:
public function public_mobile_getjson_ids()
{
    $modelid = intval($_GET['modelid']);
    $id      = intval($_GET['id']);

    $this->db->set_model($modelid);
    $table = $this->db->table_name . '_data';
    $data  = $this->db->get_one(['id' => $id], 'mobile_type');

    if (!$data) return json_encode('沒有添加相關文章');

    $types = explode('|', $data['mobile_type']);
    $typeNames = [];
    foreach ($types as $t) {
        $typeNames[] = iconv('gbk', 'utf-8', $t); // 編碼轉換
    }

    $mobileDb = pc_base::load_model('mobile_type_model');
    $result = $mobileDb->select(['id IN' => $typeNames], 'id,type_name');

    $output = [];
    foreach ($result as $row) {
        $output[] = ['sid' => 'v' . $row['id'], 'type_name' => $row['type_name']];
    }
    exit(json_encode($output));
}

前端調用不變

$.getJSON(
    "?m=content&c=content&a=public_mobile_getjson_ids&modelid=" + modelid + "&id=" + id,
    function(json) {
        if (json === '沒有添加相關文章') return;
        $.each(json, function(i, n) {
            $("#mobile_type_text").append(
                "<li id='" + n.sid + "'>·<span>" + n.type_name + "</span>" +
                "<a href='javascript:;' class='close' onclick=\"remove_relation('" + n.sid + "'," + n.id + ")\"></a></li>"
            );
        });
    }
);

最佳實務建議

  1. 所有對外開放的 API 方法統一加 public_ 前綴
  2. 敏感操作額外驗證 Token/Referer,不要只靠命名規則
  3. API 專用控制器繼承基類並覆寫 check_hash() 邏輯
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved