如何让CodeIgniter中函数仅可通过AJAX调用而无法通过URL访问
Hey there! I totally get your goal—you want to make sure your CRUD actions can't be accessed directly via URL, only through AJAX requests. That's a smart move for both security and proper application flow. Let's break down how to implement this in your CodeIgniter controller.
The Core Idea: Check for AJAX Requests
CodeIgniter has a built-in method to detect if a request is coming from AJAX: $this->input->is_ajax_request(). We can use this to block direct access to your CRUD methods. To avoid repeating code, let's create a reusable validation method.
Modified Controller Code
Here's your updated controller with the necessary checks (plus a few extra security touches):
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Class_List extends MY_Controller{ function __construct(){ parent::__construct(); // Don't forget to call the parent constructor! $this->load->model('mdl_class_list'); } function index(){ // This method can stay accessible directly (e.g., your class list page) } function form($id = NULL){ // Your form page is safe to access directly } // Private helper method to validate AJAX requests private function _validate_ajax() { // Check if the request is AJAX if (!$this->input->is_ajax_request()) { // Return a 403 Forbidden error (JSON format for better AJAX handling) $this->output ->set_status_header(403) ->set_content_type('application/json') ->set_output(json_encode([ 'status' => 'error', 'message' => 'Direct access to this endpoint is not allowed.' ])); exit; } // Optional (but highly recommended): Validate CSRF token if (!$this->security->csrf_verify()) { $this->output ->set_status_header(403) ->set_content_type('application/json') ->set_output(json_encode([ 'status' => 'error', 'message' => 'Invalid CSRF token. Please refresh the page.' ])); exit; } } function create(){ $this->_validate_ajax(); // Your create logic here (process POST data, call model, etc.) // Example response: echo json_encode([ 'status' => 'success', 'message' => 'Class created successfully!' ]); } function read($term_id = NULL){ $this->_validate_ajax(); // Your read logic here (fetch data from model) $class_data = $this->mdl_class_list->get_class_details($term_id); echo json_encode([ 'status' => 'success', 'data' => $class_data ]); } function update(){ $this->_validate_ajax(); // Your update logic here echo json_encode([ 'status' => 'success', 'message' => 'Class updated successfully!' ]); } function delete(){ $this->_validate_ajax(); // Your delete logic here echo json_encode([ 'status' => 'success', 'message' => 'Class deleted successfully!' ]); } } ?>
Key Notes to Keep in Mind
- Parent Constructor: Make sure you call
parent::__construct()in your controller's constructor—this loads CodeIgniter's core libraries (likeinputandsecurity) that we use for validation. - CSRF Protection: I added CSRF token verification because even AJAX requests can be forged. To enable this, go to
application/config/config.phpand set:$config['csrf_protection'] = TRUE; $config['csrf_token_name'] = 'csrf_test_name'; // Default, can be changed $config['csrf_cookie_name'] = 'csrf_cookie_name'; $config['csrf_expire'] = 7200; - Frontend AJAX Example: When making AJAX calls from your frontend (using jQuery here), you need to include the CSRF token:
// Get CSRF token details from the server const csrfTokenName = '<?php echo $this->security->get_csrf_token_name(); ?>'; const csrfTokenHash = '<?php echo $this->security->get_csrf_hash(); ?>'; // Example: Create a new class via AJAX $.ajax({ url: '<?php echo base_url('class_list/create'); ?>', method: 'POST', data: { [csrfTokenName]: csrfTokenHash, class_name: 'Introduction to Biology', term_id: 123 }, dataType: 'json', success: function(response) { if (response.status === 'success') { alert(response.message); // Refresh your class list or update the UI here } else { alert('Error: ' + response.message); } }, error: function(xhr) { alert('Request failed: ' + xhr.responseJSON.message); } });
What Happens if Someone Tries Direct Access?
If someone tries to visit yourdomain.com/class_list/create directly in their browser, they'll get a 403 Forbidden response with a JSON error message—no way to execute the CRUD logic without an AJAX request.
内容的提问来源于stack exchange,提问作者William Jay Inclino

