PHP code example of wp-php-toolkit / corsproxy

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

    

wp-php-toolkit / corsproxy example snippets



// cors-proxy-config.php — placed next to cors-proxy.php.

function playground_cors_proxy_maybe_rate_limit() {
	$ip      = isset( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '0.0.0.0';
	$bucket  = sys_get_temp_dir() . '/cors-rl-' . md5( $ip );
	$now     = time();
	$window  = 60;
	$max_req = 30;

	$hits = array();
	if ( file_exists( $bucket ) ) {
		$hits = json_decode( file_get_contents( $bucket ), true );
		if ( ! is_array( $hits ) ) $hits = array();
	}
	$hits = array_filter( $hits, function ( $t ) use ( $now, $window ) {
		return $t > $now - $window;
	} );

	if ( count( $hits ) >= $max_req ) {
		header( 'Retry-After: ' . $window );
		http_response_code( 429 );
		echo 'Rate limit exceeded';
		exit;
	}

	$hits[] = $now;
	file_put_contents( $bucket, json_encode( array_values( $hits ) ) );
}

echo "Config loaded — rate limiter armed.\n";


// cors-proxy-config.php — combine with the rate-limit example above.

function playground_cors_proxy_maybe_rate_limit() {
	$allow = array(
		'api.github.com',
		'raw.githubusercontent.com',
		'codeload.github.com',
		'repo.packagist.org',
		'downloads.wordpress.org',
		'api.wordpress.org',
	);

	$target = isset( $_SERVER['PATH_INFO'] ) ? $_SERVER['PATH_INFO'] : ( '/' . ( isset( $_SERVER['QUERY_STRING'] ) ? $_SERVER['QUERY_STRING'] : '' ) );
	$target = ltrim( $target, '/' );
	$host   = parse_url( $target, PHP_URL_HOST );

	if ( ! $host || ! in_array( strtolower( $host ), $allow, true ) ) {
		http_response_code( 403 );
		header( 'Content-Type: text/plain' );
		echo "Upstream not allowed: " . ( $host ? $host : '(none)' );
		exit;
	}
}

echo "Allowlist config active.\n";