PHP的随机图像网址

时间:2019-02-19 20:20:17

标签: php .htaccess random

我创建了此代码,以在同一链接上随机显示一个URL。 这是文件prova.php:

<?php
$file = "foto.txt";
// Convert the text fle into array and get text of each line in each array index
$file_arr = file($file);
// Total number of linesin file
$num_lines = count($file_arr);
// Getting the last array index number by subtracting 1 as the array index starts from 0
$last_arr_index = $num_lines - 1;
// Random index number
$rand_index = rand(0, $last_arr_index);
// random text from a line. The line will be a random number within the indexes of the array
$rand_text = $file_arr[$rand_index];
echo $rand_text;
   $file = $rand_text;

    // write out
    $type = 'image/jpg';
    header('Content-Type:'.$type);
    header('Content-Length: ' . filesize($file));
    readfile($file);
?>

这是.htaccess:

 RewriteEngine On
    RewriteRule ^foto.jpg prova.php [L]

然后我转到http://mysite/folder/foto.jpg,但是我的图像没有加载。 WordPress告诉我该页面不存在。 相反,如果我转到prova.php,则会在文件内看到正确的链接。

怎么了?

1 个答案:

答案 0 :(得分:1)

使用htaccess测试器(https://htaccess.madewithlove.be/)。

按照书面规定,您的htaccess不适用于您的URL方案。此规则仅适用于“ http://test.com/foto.jpg”或您的域。

如果foto.jpg应该位于“文件夹”中,则可以将htaccess更改为读取^folder/foto.jpg


编辑

尝试一下:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]

# Your rules here
RewriteRule ^wp-content/folder/foto.jpg prova.php [L]

# This should be last
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>