admin avatar

使用php腳本自建簡單隨機圖片API

🕤 by admin

在網站根目錄下新建檔,內容如下:randomimg.php

PHP:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?php
//调用次数简单统计,文件为count.txt
if (!file_exists("count.txt")) {
    $count_file = fopen("count.txt", "w+");
    fwrite($count_file, "1");
    fclose($count_file);
} else {
    $num = file_get_contents("count.txt");
    $num++;
    file_put_contents("count.txt", "$num");
}

//调用图片数量,记录文本为num.txt
if (!file_exists("num.txt")) {
    $num_file = fopen("num.txt", "w+");
    fwrite($num_file, "1");
    fclose($num_file);
} else {
    $img_num = file_get_contents("num.txt");
}

//获取随机图片名,存放随机图片的文件为img.txt
$name_file = "img.txt";
$pic = "";
$img_url = "https://img.example.com/img/";
if (!file_exists($name_file)) {
    die('Name file does not exist!');
} else {
    //生成随机数
    $seed = time();
    $rand_num = rand(0, $img_num - 1);

    //生成连接
    $fs = new SplFileObject($name_file, 'r');
    $fs->seek($rand_num);
    $pic = trim($fs->current());
    $pic = $img_url . $pic;

    //返回指定连接
    die(header("Location: $pic"));
}

記錄圖片名

Bash:
1
ls /path/to/img > /path/to/img.txt

這一條命令就可以搞定了,但個人有點強迫症,想要給圖片編號,又想名稱顯示一部分隨機數,所以就寫了一個小腳本,但以下完全是可以忽略的。

創建一個shell腳本,腳本內容如下:format-name.sh

這一條命令就可以搞定了,但個人有點強迫症,想要給圖片編號,又想名稱顯示一部分隨機數,所以就寫了一個小腳本,但以下完全是可以忽略的。

創建一個shell腳本,腳本內容如下:format-name.sh

Bash:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/bin/bash
IMG_DIR=/path/to/dir
NAME_FILE=/path/to/img.txt
NUM_FILE=path/to/num.txt

num=0
OIFS=$IFS
IFS=$'\n'
mkdir $IMG_DIR/temp && cd $IMG_DIR
while read line; do
    if [ -f $line ]; then
        ((num=num+1))
        img_type=${line##*.}
        mv $IMG_DIR/$line $IMG_DIR/temp/"$num-$(head -n 4 /dev/urandom | tr -dc "A-Za-z0-9" | cut -c 1-8).$img_type"
    fi
done <<< $(ls $IMG_DIR)
IFS=$OIFS

mv $IMG_DIR/temp/* $IMG_DIR
rm -rf $IMG_DIR/temp
ls -v $IMG_DIR > $NAME_FILE
echo -n $num > $NUM_FILE

賦權。chmod +x format-name.sh

定時任務,一天執行一次。crontab -e

Bash:
1
0 0 * * * /path/to/format-name.sh > /dev/null

來源:

https://justo.cyou/posts/%E8%87%AA%E5%BB%BA%E7%AE%80%E5%8D%95%E9%9A%8F%E6%9C%BA%E5%9B%BE%E7%89%87api/

💘 相关文章

写一条评论