Senaryomuz çok basit. Eğer kullanıcı login olmamışsa, HTTP üzerinden yapılan dosyalara ulaşım isteklerini, kullanıcıyı ana sayfaya yönlendirerek engelliyoruz. Bu örneğimizde test olarak sadece PDF dosyası kullanacağız ama siz isterseniz diğer dosya tiplerinide ekleyebilirsiniz.


Çalışma mantığı


URL'nin http://www.inanzzz.com/ olduğunu varsayalım.



Apache mod_rewrite aktifleştirme


Dosya /etc/httpd/conf/httpd.conf içindeki AllowOverride None satırını AllowOverride All olarak değiştirin ve apache serveri yeniden başlatın.


# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
AllowOverride All

.htaccess


RewriteEngine On
RewriteCond %{REQUEST_URI} \.(pdf)$ [NC]
RewriteRule ^ validate.php?request_url=%{REQUEST_URI} [L]
# To disable or prevent the directory access/listing
Options -Indexes

validate.php


<?php
session_start();

if (!isset($_SESSION['login'])) {
header ('Location: index.php');
exit();
} else {
// Get server document root
$document_root = $_SERVER['DOCUMENT_ROOT'];
// Get request URL from .htaccess
$request_url = $_GET['request_url'];
// Get file name only
$filename = basename($request_url);

// Set headers
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename='.$filename);

// Output file content
@readfile($document_root.$request_url);
}

index.php


<h3>HTACCESS controlled site</h3>

<p>You should be logged in in order to access 1.pdf via URL.</p>

<?php
session_start();

echo !isset($_SESSION['login'])
? '<a href="?login">Click here to login</a>'
: '<a href="?logout">Click here to logout</a>';

if (isset($_GET['login'])) {
$_SESSION['login'] = true;
header('location: index.php');
exit;
} elseif (isset($_GET['logout']) && isset($_SESSION['login'])) {
unset($_SESSION['login']);
session_destroy();
header('location: index.php');
exit;
}

// Do something else here if you want

Yapımız


project-folder
.htaccess
1.pdf
index.php
validate.php

Test


http://www.inanzzz.com/ adresine gidip "Login" linkini tıklayın. http://www.inanzzz.com/1.pdf adresine gitmeyi denediğinizde, 1.pdf dosyasına başarıyla ulaşabileceksiniz. Şimdi geriye gidip http://www.inanzzz.com/ adresindeki "Logout" linkine tıklayın. Bu sefer http://www.inanzzz.com/1.pdf adresine gitmeyi denediğinizde, otomatik olarak ana sayfaya yönlendirileceksiniz.