Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marlocorridor/2e06f950a895013d6324a8aac32ab630 to your computer and use it in GitHub Desktop.
Save marlocorridor/2e06f950a895013d6324a8aac32ab630 to your computer and use it in GitHub Desktop.
Updates the .htaccess with the recent ClouldFlare IPs
<?php
# Exec during deployment
# php cloudflareWhitelistUpdate.php public/.htaccess
$srcUrls = [
'https://www.cloudflare.com/ips-v4',
'https://www.cloudflare.com/ips-v6'
];
$htacessFile = $argv[1] ?? '.htaccess';
$ips = [];
// Collect IPs
foreach ($srcUrls as $url) {
if ($data = file_get_contents($url)) {
$ips = array_merge($ips, explode(PHP_EOL, trim($data)));
}
}
// Deny / Allow rules
if (count($ips)) {
$htacessContents = 'ErrorDocument 403 "Not Allowed"' . PHP_EOL;
$htacessContents .= 'Deny from all' . PHP_EOL;
$htacessContents .= '### Cloudflare IPs ###' . PHP_EOL . PHP_EOL;
foreach ($ips as $ip) {
$htacessContents .= 'Allow from ' . $ip . PHP_EOL;
}
}
// Merge with existing content
if (file_exists($htacessFile) && is_readable($htacessFile)) {
$htacessContents .= file_get_contents($htacessFile);
}
// Write .htaccess
if (file_put_contents($htacessFile, $htacessContents)) {
echo "Writing $htacessFile file" . PHP_EOL;
echo str_repeat('-', 30) . PHP_EOL;
echo substr($htacessContents, 0, 150) . PHP_EOL;
echo '...' . PHP_EOL;
echo substr($htacessContents, -150) . PHP_EOL;
}
// Original contents starts below
@marlocorridor
Copy link
Author

marlocorridor commented Apr 23, 2018

testing on fortrabbit - successful

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment