View difference between Paste ID: EDuY2Cfu and HrXpgijn
SHOW: | | - or go back to the newest paste.
1
<?php
2
3
/**
4
 * 呼叫 flickr.people.getPublicPhotos
5
 * @param string $user_id 要傳回照片的user id
6
 * @return string json格式的字串
7
 */
8
function getPublicPhotos($user_id) {
9
    $ch = curl_init();
10
    //產生API網址,有部分參數在此寫死,例如輸出格式這邊是直接設定為JSON
11
    $api_key = '3dd490cec911376eb3356af84efc05e6';
12
    $url = "https://api.flickr.com/services/rest/?method=flickr.people.getPublicPhotos&api_key={$api_key}&user_id={$user_id}&format=json&nojsoncallback=1";
13
    $options = array(
14
        CURLOPT_URL => $url,
15
        CURLOPT_HEADER => false,
16
        CURLOPT_RETURNTRANSFER => true,
17
            //CURLOPT_SSL_VERIFYHOST => 0,
18
            //CURLOPT_SSL_VERIFYPEER => 0,
19
    );
20
    curl_setopt_array($ch, $options);
21
    $result = curl_exec($ch);
22
    curl_close($ch);
23
    return $result;
24
}
25
26
//檢查是否有GET的user_id參數
27-
if (isset($_GET['user_id'])) {
27+
if (isset($_GET['user_id']) and !empty($_GET['user_id'])) {
28
    $user_id = $_GET['user_id'];
29
    $data = getPublicPhotos($user_id);
30
    $json = json_decode($data, true);
31-
    $photos = $json['photos'];
31+
    $photos = $json['photos']['photo'];
32
} else {
33
    $photos = array();
34
}
35
?>
36
37
<html>
38
    <head></head>
39
    <body>
40
        <form method="get">
41
            <label>user_id <input type="text" name="user_id" value="<?php echo isset($_GET['user_id']) ? $_GET['user_id'] : ''; ?>"></label>
42
            <input type="submit">
43
        </form>
44
        <div>
45
            <?php
46-
            foreach ($photos['photo'] as &$photo) {
46+
            foreach ($photos as &$photo) {
47
                //產生flickr的連結
48
                $url = "https://www.flickr.com/photos/{$photo['owner']}/{$photo['id']}";
49
                //產生照片的連結
50
                $img = "http://www.flickr.com/photos/{$photo['id']}_{$photo['secret']}.jpg";
51
                //另一種產生照片連結的方法
52
                //$img = "https://farm{$photo['farm']}.staticflickr.com/{$photo['server']}/{$photo['id']}_{$photo['secret']}.jpg";
53
                echo "<a href=\"$url\" target=\"_blank\"><img src=\"{$img}\" border=\"0\"></a>\n";
54
            }
55
            ?>
56
        </div>
57
    </body>
58
</html>