PHP code example of liopoos / http-code

1. Go to this page and download the library: Download liopoos/http-code library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

liopoos / http-code example snippets




use Liopoos\HttpCode\Http;

// Access as constants
echo Http::HTTP_OK; // 200
echo Http::HTTP_NOT_FOUND; // 404
echo Http::HTTP_INTERNAL_SERVER_ERROR; // 500

// Or use as static methods
echo Http::HTTP_OK(); // 200
echo Http::HTTP_NOT_FOUND(); // 404
echo Http::HTTP_INTERNAL_SERVER_ERROR(); // 500



use Liopoos\HttpCode\Http;

$statusCode = Http::HTTP_OK;

if (Http::isSuccessful($statusCode)) {
    echo "Request was successful!";
}

// Works with any 2xx status code
Http::isSuccessful(Http::HTTP_CREATED); // true
Http::isSuccessful(Http::HTTP_ACCEPTED); // true
Http::isSuccessful(Http::HTTP_NOT_FOUND); // false



use Liopoos\HttpCode\Http;

function handleApiResponse($response)
{
    $statusCode = $response->getStatusCode();
    
    if (Http::isSuccessful($statusCode)) {
        return $response->getData();
    }
    
    switch ($statusCode) {
        case Http::HTTP_NOT_FOUND:
            throw new NotFoundException("Resource not found");
        case Http::HTTP_UNAUTHORIZED:
            throw new AuthException("Unauthorized access");
        case Http::HTTP_INTERNAL_SERVER_ERROR:
            throw new ServerException("Server error occurred");
        default:
            throw new Exception("Unexpected status: " . $statusCode);
    }
}