Create New Post

Handling HTTP requests and responses in CodeIgniter

In CodeIgniter, you can handle HTTP requests and responses within your controllers. Here's a guide on how to handle HTTP requests and responses:

Handling HTTP Requests:

  1. Accessing Request Data:

    • Use CodeIgniter's input class to access request data such as GET, POST, PUT, DELETE parameters.
    • Example:
     // Getting POST data
    $post_data = $this->input->post();
    
    // Getting GET data
    $get_data = $this->input->get();
    
    // Getting PUT data (via PHP input stream)
    parse_str(file_get_contents("php://input"), $put_data);
    
    // Getting DELETE data (similar to PUT)
    
  2. Determining Request Method:

    • Use the method() method of the input class to determine the HTTP request method.
    • Example:
    $http_method = $this->input->method(); 

Handling HTTP Responses:

  1. Setting Response Headers:

    • Use CodeIgniter's output class to set HTTP response headers.
    • Example:
    $this->output->set_content_type('application/json'); 
  2. Returning JSON Response:

    • Use json_encode() to encode data as JSON and set it as the response.
    • Example:
     $data = array('key' => 'value');
    $json_response = json_encode($data);
    $this->output->set_output($json_response);
    
  3. Returning HTML Response:

    • Use CodeIgniter's view loading mechanism to load and display HTML views as responses.
    • Example:
     $this->load->view('my_view', $data); 
  4. Returning Other Types of Responses:

    • Use appropriate methods of the output class to set the response content type and output data accordingly.
    • Example:
    $this->output->set_content_type('text/plain')->set_output('Hello, World!');
     

Example Controller Method:

public function handle_request() {
    // Determine HTTP method
    $http_method = $this->input->method();

    // Handle different HTTP methods
    switch ($http_method) {
        case 'get':
            // Handle GET request
            break;
        case 'post':
            // Handle POST request
            break;
        case 'put':
            // Handle PUT request
            break;
        case 'delete':
            // Handle DELETE request
            break;
        default:
            // Handle unsupported request
            break;
    }

    // Set response content type and output data
    $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode($response_data));
}
 

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

94899