Last active
June 17, 2016 09:36
-
-
Save tored/17b230a010abf48c27b9df96e7bdf846 to your computer and use it in GitHub Desktop.
Bing Wallpaper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env php | |
<?php | |
function getDownloadPathWindows() | |
{ | |
$home = getenv('HOMEDRIVE') . getenv('HOMEPATH'); | |
if (!is_dir($home)) { | |
throw new RuntimeException("No home folder $home"); | |
} | |
return "$home/Pictures/Bing"; | |
} | |
function getDownloadPath() | |
{ | |
$os = strtoupper(php_uname('s')); | |
if (strpos($os, 'WINDOWS') === 0) { | |
return getDownloadPathWindows(); | |
} | |
throw new RuntimeException("Unknown operating system $os"); | |
} | |
$market = 'en-US'; | |
$resolution = '1920x1080'; | |
$image_filename = 'wallpaper.jpg'; | |
$download_directory = getDownloadPath(); | |
$download_path = "$download_directory/$image_filename"; | |
$bing_url = 'http://bing.com'; | |
$json_url = "{$bing_url}/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=$market"; | |
if (!is_dir($download_directory)) { | |
@mkdir($download_directory, 0755, true); | |
} | |
$json = file_get_contents($json_url); | |
if ($json === false) { | |
throw new RuntimeException("Failed downloading $json_url"); | |
} | |
$data = json_decode($json); | |
if ($data === null) { | |
throw new RuntimeException('Failed decoding json'); | |
} | |
$path = &$data->images[0]->urlbase; | |
if ($path === null) { | |
throw new RuntimeException("Found no image in $data"); | |
} | |
$url = "${bing_url}{$path}_{$resolution}.jpg"; | |
$handle = fopen($url, 'r'); | |
if ($handle === false) { | |
throw new RuntimeException("Could not downland $url"); | |
} | |
$bytes = file_put_contents($download_path, $handle); | |
if ($bytes === false) { | |
throw new RuntimeException("Failed writing to file $download_path"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment