Skip to content

Instantly share code, notes, and snippets.

@Asbra
Created March 17, 2019 06:45
Show Gist options
  • Save Asbra/05be3501a35433734fc48301b5e1c67d to your computer and use it in GitHub Desktop.
Save Asbra/05be3501a35433734fc48301b5e1c67d to your computer and use it in GitHub Desktop.
PHP Wallhaven.cc full-resolution wallpaper downloader by keyword search
<?php
//// Simple Wallhaven downloader
// Downloads wallpapers from Wallhaven.cc at full resolution by searching for specified keywords
$keywords = [
'waterfall',
'nature',
'mountains',
];
// Resolutions (finds wallpapers of exactly these resolutions)
// Separate by comma for multiple
// eg. $resolutions = '1920x1080,2560x1440'
$resolutions = '';
// Minimum resolution (finds wallpapers of atleast this resolution)
// eg. $atleast = '1280x720'
$atleast = '';
// Use either $resolutions or $atleast and leave the other one blank
// Aspect ratios
// Valid values: [ 4x3, 5x4, 16x9, 16x10, 21x9, 32x9, 48x9, 9x16, 10x16, ]
// Separate by comma for multiple
$aspect_ratio = '16x9';
// Sort order
// Valid values: [ relevance, random, date_added, views, favorites, toplist ]
$sorting = 'relevance';
// Colors
// Any 3-byte hex value, searches by dominant color
$colors = '';
// Categories
// Field order [ General, Anime, People ]
// eg. General = 100, Anime & People = 011
$categories = '100';
// Purity
// Field order [ SFW, Sketchy, ? ]
// eg. SFW = 100, SFW & Sketchy = 110
$categories = '100';
///////////////////////////////////////////////////////////////////////////////
foreach ($keywords as $keyword) {
$url = "https://alpha.wallhaven.cc/search?q={$keyword}";
$url .= "&sorting=relevance";
$url .= "&order=desc";
if (!empty($categories)) $url .= "&categories={$categories}";
if (!empty($purity)) $url .= "&purity={$purity}";
if (!empty($resolutions)) $url .= '&resolutions='.urlencode($resolutions);
else if (!empty($atleast)) $url .= "&resolutions={$atleast}";
if (!empty($aspect_ratio)) $url .= "&ratios={$aspect_ratio}";
if (!empty($colors)) $url .= "&colors={$colors}";
echo $url."\n";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$html = curl_exec($ch);
$re = '/data-wallpaper-id="(\d+)"/';
preg_match_all($re, $html, $matches);
echo "Found ".count($matches[1])." wallpapers ..\n";
foreach ($matches[1] as $match) {
$id = $match;
$filename = "wallhaven-{$id}.jpg";
if (!file_exists($filename)) {
$img_url = "https://alpha.wallhaven.cc/wallpapers/full/{$filename}";
$data = file_get_contents($img_url);
if (strlen($data) <= 1) continue;
file_put_contents($filename, $data);
echo "Downloaded {$filename}\n";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment