PHP code example of cardano-php / bech32

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

    

cardano-php / bech32 example snippets




use PhpCardano\Bech32\Bech32;

// Set up our data to be encoded and our human readable part (HRP)
$data = 'does-the-php-dev';
$hrp = 'cardanophp';
echo 'HRP: ' . $hrp . "\n" . ' Data: ' . $data . "\n";

// Hex-encode our data payload
$hexdata = bin2hex($data);
echo 'Hex Data: ' . $hexdata . "\n";

// Convert our hex-encoded payload to a 5-bit "byte" array
$bitdata = Bech32::hexToByteArray($hexdata);

// Bech32 encode the HRP + 5-bit data payload
$encoded = Bech32::encode($hrp, $bitdata);
echo 'Encoded: ' . $encoded . "\n";

use PhpCardano\Bech32\Bech32;

$bech32 = 'cardanophp1v3hk2uedw35x2ttsdpcz6er9wcjv4g3u'; // Your Bech32 string

// Decode returns the human readable part (HRP) and the data payload in a 5-bit array
[$hrp, $bitData] = Bech32::decode($bech32);

// Convert the 5-bit data back to a hex string
$hexData = Bech32::byteArrayToHex($data);

echo 'HRP: ' . $hrp . "\n";
echo 'Hex Data: ' . $hexData . "\n";

// Convert (if needed) from hex back to binary/ASCII

$plainData = hex2bin($hexData);

echo 'Data Payload: ' . $plainData . "\n";
 
/**
* JPG v2 Staked Public Contract
**/

use CardanoPhp\Bech32\Bech32;

$bech32String = 'addr1qxegfu8m62peqmyamrdwmwqm00zjcak3u25xnanfdct4p9pf488uagw68fv50kjxv3wrx38829tay6zszthnccsradgqwt4upy';
$result = Bech32::decodeCardanoAddress($bech32String);
echo "Result:\n".json_encode($result, JSON_PRETTY_PRINT)."\n";
 
/**
* JPG v2 Staked Public Contract
**/

use CardanoPhp\Bech32\Bech32;

$addressType = 3;                                                          // Script Hash + Script Hash
$networkId = 1;                                                            // Cardano Mainnet
$paymentHash = '9068a7a3f008803edac87af1619860f2cdcde40c26987325ace138ad'; // Payment Validator
$stakeHash = '2c967f4bd28944b06462e13c5e3f5d5fa6e03f8567569438cd833e6d';   // Stake Validator

$address = Bech32::encodeCardanoAddress($addressType, $networkId, $paymentHash, $stakeHash);
echo "Result:\n" . json_encode($address, JSON_PRETTY_PRINT) . "\n";

try {
    [$hrp, $data] = Bech32::decode($bech32);
} catch (Exception $e) {
    echo "Decoding failed: " . $e->getMessage();
}
bash
composer