PHP code example of zeroad.network / token
1. Go to this page and download the library: Download zeroad.network/token 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/ */
zeroad.network / token example snippets
eroAd\Token\Site;
use ZeroAd\Token\Constants;
// Initialize once at startup
$site = new Site([
"clientId" => "YOUR_CLIENT_ID_HERE",
"features" => [Constants::FEATURE["CLEAN_WEB"], Constants::FEATURE["ONE_PASS"]]
]);
// In your middleware/controller
header("{$site->SERVER_HEADER_NAME}: {$site->SERVER_HEADER_VALUE}");
// Parse the user's subscription token
$tokenContext = $site->parseClientToken($_SERVER[$site->CLIENT_HEADER_NAME] ?? null);
// Use token context in templates
render("index", ["tokenContext" => $tokenContext]);
<!-- index.php -->
<!DOCTYPE html>
<html>
<head>
<title>My Site</title>
</head>
<body>
<h1>Welcome to My Site</h1>
<!-- Only show ads to non-subscribers -->
if (!$tokenContext["HIDE_ADVERTISEMENTS"]):
[
// CLEAN_WEB features
"HIDE_ADVERTISEMENTS" => bool,
"HIDE_COOKIE_CONSENT_SCREEN" => bool,
"HIDE_MARKETING_DIALOGS" => bool,
"DISABLE_NON_FUNCTIONAL_TRACKING" => bool,
// ONE_PASS features
"DISABLE_CONTENT_PAYWALL" => bool,
"ENABLE_SUBSCRIPTION_ACCESS" => bool
];
use ZeroAd\Token\Site;
use ZeroAd\Token\Constants;
$site = new Site([
"clientId" => "YOUR_CLIENT_ID",
"features" => [Constants::FEATURE["CLEAN_WEB"]],
"cacheConfig" => [
"ttl" => 10, // Cache for 10 seconds (default: 5)
"prefix" => "myapp:zeroad:" // Custom cache key prefix
]
]);
use ZeroAd\Token\Site;
use ZeroAd\Token\Constants;
$site = new Site([
"clientId" => $_ENV["ZERO_AD_CLIENT_ID"],
"features" => [Constants::FEATURE["CLEAN_WEB"]],
"cacheConfig" => [
"ttl" => 10, // Cache for 10 seconds
"prefix" => "myapp:zeroad:" // Namespace your cache keys
]
]);
use ZeroAd\Token\Logger;
// Development
Logger::setLogLevel("debug"); // error, warn, info, debug
// Production
Logger::setLogLevel("error");
use ZeroAd\Token\Logger;
// Integrate with Monolog
$monolog = new Monolog\Logger("zeroad");
$monolog->pushHandler(new StreamHandler("/var/log/zeroad.log"));
Logger::setLogHandler(function ($level, $message) use ($monolog) {
$monolog->log($level, $message);
});
// Disable logging in production
Logger::setLogHandler(function ($level, $message) {
// No-op: discard all logs
});
// Send errors to monitoring service
Logger::setLogHandler(function ($level, $message) {
if ($level === "error") {
Sentry\captureMessage($message);
}
});
// app/Http/Middleware/ZeroAdNetwork.php
namespace App\Http\Middleware;
use Closure;
use ZeroAd\Token\Site;
use ZeroAd\Token\Constants;
class ZeroAdNetwork
{
private $site;
public function __construct()
{
$this->site = new Site([
'clientId' => config('zeroad.client_id'),
'features' => [Constants::FEATURE['CLEAN_WEB'], Constants::FEATURE['ONE_PASS']],
'cacheConfig' => ['ttl' => 10]
]);
}
public function handle($request, Closure $next)
{
// Set Welcome Header
header("{$this->site->SERVER_HEADER_NAME}: {$this->site->SERVER_HEADER_VALUE}");
// Parse token
$tokenContext = $this->site->parseClientToken(
$_SERVER[$this->site->CLIENT_HEADER_NAME] ?? null
);
// Add to request
$request->attributes->set('tokenContext', $tokenContext);
return $next($request);
}
}
// In your controller
public function index(Request $request)
{
$tokenContext = $request->attributes->get('tokenContext');
return view('index', ['tokenContext' => $tokenContext]);
}
// src/EventListener/ZeroAdNetworkListener.php
namespace App\EventListener;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use ZeroAd\Token\Site;
use ZeroAd\Token\Constants;
class ZeroAdNetworkListener
{
private $site;
public function __construct(string $clientId)
{
$this->site = new Site([
"clientId" => $clientId,
"features" => [Constants::FEATURE["CLEAN_WEB"]],
"cacheConfig" => ["ttl" => 10]
]);
}
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
$tokenContext = $this->site->parseClientToken($_SERVER[$this->site->CLIENT_HEADER_NAME] ?? null);
$request->attributes->set("tokenContext", $tokenContext);
}
public function onKernelResponse(ResponseEvent $event)
{
$response = $event->getResponse();
$response->headers->set($this->site->SERVER_HEADER_NAME, $this->site->SERVER_HEADER_VALUE);
}
}
// wp-content/themes/your-theme/functions.php
// Initialize once
$GLOBALS['zeroad_site'] = new Site([
'clientId' => get_option('zeroad_client_id'),
'features' => [Constants::FEATURE['CLEAN_WEB'], Constants::FEATURE['ONE_PASS']],
'cacheConfig' => ['ttl' => 10]
]);
// Add Welcome Header
add_action('send_headers', function() {
$site = $GLOBALS['zeroad_site'];
header("{$site->SERVER_HEADER_NAME}: {$site->SERVER_HEADER_VALUE}");
});
// Parse token and make available globally
add_action('init', function() {
$site = $GLOBALS['zeroad_site'];
$GLOBALS['zeroad_context'] = $site->parseClientToken(
$_SERVER[$site->CLIENT_HEADER_NAME] ?? null
);
});
// Use in templates
function zeroad_context() {
return $GLOBALS['zeroad_context'] ?? [];
}
// In your template files
if (!zeroad_context()['HIDE_ADVERTISEMENTS']):
eroAd\Token\Site;
use ZeroAd\Token\Constants;
use ZeroAd\Token\Logger;
// Configure logging
Logger::setLogLevel("error");
// Initialize site instance
$site = new Site([
"clientId" => $_ENV["ZERO_AD_CLIENT_ID"] ?? "DEMO-Z2CclA8oXIT1e0Qmq",
"features" => [Constants::FEATURE["CLEAN_WEB"], Constants::FEATURE["ONE_PASS"]],
"cacheConfig" => [
"ttl" => 10,
"prefix" => "myapp:zeroad:"
]
]);
// Middleware function
function tokenMiddleware($site, callable $handler)
{
// Set Welcome Header
header("{$site->SERVER_HEADER_NAME}: {$site->SERVER_HEADER_VALUE}");
// Parse token
$tokenContext = $site->parseClientToken($_SERVER[$site->CLIENT_HEADER_NAME] ?? null);
// Call handler with context
$handler($tokenContext);
}
// Routes
$uri = $_SERVER["REQUEST_URI"];
if ($uri === "/") {
tokenMiddleware($site, function ($tokenContext) {
use ZeroAd\Token\Logger;
// Enable debug logging
Logger::setLogLevel("debug");
// Check if token is being received
$headerValue = $_SERVER[$site->CLIENT_HEADER_NAME] ?? null;
error_log("Header value: " . ($headerValue ?? "NULL"));
// Verify token context
$context = $site->parseClientToken($headerValue);
error_log("Token context: " . json_encode($context));
if (!extension_loaded("apcu") || !apcu_enabled()) {
error_log("WARNING: APCu not available - caching disabled");
} else {
error_log("APCu enabled - caching active");
}
$site = new Site([
'clientId' => 'YOUR_CLIENT_ID', // Required: Your Zero Ad Network client ID
'features' => [Constants::FEATURE[...]], // Required: Array of feature flags
'cacheConfig' => [ // Optional: Cache configuration
'ttl' => 5, // Cache TTL in seconds
'prefix' => 'zeroad:token:' // Cache key prefix
]
]);
// Properties
$site->CLIENT_HEADER_NAME; // Request header name (e.g., "HTTP_X_BETTER_WEB_HELLO")
$site->SERVER_HEADER_NAME; // Response header name ("X-Better-Web-Welcome")
$site->SERVER_HEADER_VALUE; // Response header value (encoded)
// Methods
$context = $site->parseClientToken(?string $headerValue): array
use ZeroAd\Token\Constants;
// Features
Constants::FEATURE['CLEAN_WEB'] // = 1
Constants::FEATURE['ONE_PASS'] // = 2
// Headers
Constants::SERVER_HEADER['WELCOME'] // = "X-Better-Web-Welcome"
Constants::CLIENT_HEADER['HELLO'] // = "X-Better-Web-Hello"
// Protocol
Constants::CURRENT_PROTOCOL_VERSION // = 1
use ZeroAd\Token\Logger;
Logger::setLogLevel(string $level): void
// Set minimum log level: 'error', 'warn', 'info', 'debug'
Logger::setLogHandler(?callable $handler): void
// Set custom log handler: function(string $level, string $message): void
Logger::log(string $level, ...$args): void
// Log a message
bash
# Debian/Ubuntu
sudo apt-get install php-apcu
# CentOS/RHEL
sudo yum install php-pecl-apcu
# Enable in php.ini
extension=apcu.so
apc.enabled=1
apc.shm_size=32M