PHP code example of web-eid / ocsp-php

1. Go to this page and download the library: Download web-eid/ocsp-php 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/ */

    

web-eid / ocsp-php example snippets


// Loading certificate from file
$certificate = (new CertificateLoader)->fromFile('/path/to/cert.crt')->getCert();

// Loading certificate from string
$certificate = (new CertificateLoader)->fromString('-----BEGIN CERTIFICATE-----MIIEAzCCA...-----END CERTIFICATE-----')->getCert();

$certLoader = (new CertificateLoader)->fromFile('/path/to/cert.crt');
$issuerCertificateUrl = $certLoader->getIssuerCertificateUrl();

$certLoader = (new CertificateLoader)->fromFile('/path/to/cert.crt');
$ocspResponderUrl = $certLoader->getOcspResponderUrl();

$subjectCert = (new CertificateLoader)->fromFile('/path/to/subject.crt')->getCert();
$issuerCert = (new CertificateLoader)->fromFile('/path/to/issuer.crt')->getCert();

// Create the certificateId
$certificateId = (new Ocsp)->generateCertificateId($subjectCert, $issuerCert);

// Build request body
$requestBody = new OcspRequest();
$requestBody->addCertificateId($certificateId);

// Add nonce extension when the nonce feature is enabled,
// otherwise skip this line
$requestBody->addNonceExtension(random_bytes(8));

// Send request to OCSP responder URL
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $ocspResponderUrl);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: ' .Ocsp::OCSP_REQUEST_MEDIATYPE]);
curl_setopt($curl, CURLOPT_POSTFIELDS, $requestBody->getEncodeDer());
$result = curl_exec($curl);
$info = curl_getinfo($curl);
if ($info["http_code"] !== 200) {
    throw new RuntimeException("HTTP status is not 200");
}

// Check the response content type
if ($info["content_type"] != Ocsp::OCSP_RESPONSE_MEDIATYPE) {
    throw new RuntimeException("Content-Type header of the response is wrong");
}

// Decode the raw response from the OCSP Responder
$response = new OcspResponse($result);

// Validate response certificateId
$response->validateCertificateId($certificateId);

// Validate response signature
$response->validateSignature();

// Validate nonce when the nonce feature is enabled,
$basicResponse = $response->getBasicResponse();
if ($requestBody->getNonceExtension() != $basicResponse->getNonceExtension()) {
    throw new RuntimeException("OCSP request nonce and response nonce do not match");
} 


// Read response status
$response->getStatus();
$basicResponse = $response->getBasicResponse();

try {
    // code
} catch (OcspException $e) {
    // exception handler
}

npm install --global prettier @prettier/plugin-php

composer fix-php