2014-04-16 43 views
0

我有一個sendmessage.php文件和其他類似的文件發送電子郵件。我想禁止直接訪問這些文件,保持它們可行,但我不知道爲什麼。如何通過文件權限禁止特定文件?

如何做到這一點?

這是我如何使用它們

  $.ajax({ 
       type: 'POST', 
       url: 'sendmessage-contact.php', 
       data: $("#contact").serialize(), 
       success: function(data) { 
        if(data == "true") { 
         $("#send").fadeOut("fast", function(){ 
          $(this).before("<p><strong style='color:#D60096'></strong></p>"); 
          setTimeout("$.fancybox.close()", 3000); 
         }); 
        } 
       } 
      }); 
+0

你可以通過客戶端(通過JS)調用'sendmessage-contact.php',但是你想從客戶端也阻止它?請仔細考慮一下 – HamZa

+1

你不知道你爲什麼要阻止訪問這些文件? –

回答

2

執行你的情況簡單deny form all可能不適合你的要求,所以我提出另一項建議:

相反,你應該隨機生成一個散列字符串頁面加載,並將其寫入到會話:後

session_start(); 
//$_SERVER['HTTP_X_REQUESTED_WITH'] is pretty much pointless, just illustrating redundancy here, may not work for you so remove as desired 
if(isset($_POST['hash_key']) && $_SERVER['HTTP_X_REQUESTED_WITH']): 
    if(isset($_SESSION['hash_key']) && $_POST['hash_key'] === $_SESSION['hash_key']): 
     //call your function to process this 
     return myFunction($_POST['contact']); 
    else: 
     //no session key, deny them 
     header('HTTP/1.0 403 Forbidden'); 
    endif; 
elseif(!isset($_POST['hash_key']) && !isset($_SERVER['HTTP_X_REQUESTED_WITH'])): 
    //not trying to post, not trying to send ajax, generate a new hash key 
    $_SESSION['hash_key'] = md5(uniqid(rand(), true)); 
endif; 

現在在頁面當生成你的HTML,你需要做一個隱藏的輸入攜帶ŧ他的價值。

<input type="hidden" id="hash_key" name="hash_key" value="<?php echo $_SESSION['hash_key'];?>"/> 

現在你可以在你的Ajax函數將該值傳遞給服務器:

$.ajax({ 
    type: 'POST', 
    url: 'sendmessage-contact.php', 
    data: { 
     'contact' : $("#contact").serialize(), 
     'hash_key' : $("#hash_key").val() 
    }, 
    success: function(data){ 
     console.log(data); 
    } 
}); 

現在,如果機器人嘗試垃圾郵件的腳本,它不會不要緊,因爲他們將得到禁止403錯誤,因爲它們無法匹配我們爲我們的$_SESSION['hash_key']創建的唯一生成的字符串。

免責聲明

請在任何情況下實際使用md5(uniqid(rand(), true))。我只是簡單地提供了這個,它不是一個完全安全的方法。

編輯

過於冗長。簡化。

+0

謝謝你,我正在嘗試。但是我無法獲取數據:部分工作。如果有幫助,我會上傳更多的代碼。 – EnexoOnoma

+0

@Kououmpas請參閱上面的編輯。 – Ohgodwhy

相關問題