我有以下腳本,它可以很好地從我的 HTML 表單中獲取資料并將其寫入 .conf 檔案。
<?php
$path = '/usr/local/flowsim/data/phptest.conf';
if (isset($_POST['CollectorIP']) && isset($_POST['CollectorPort']) && isset($_POST['NetflowVersion'])) {
$fh = fopen($path,"a ");
$string = 'collector-ip='.$_POST['CollectorIP']. "\n". 'collector-port='.$_POST['CollectorPort']. "\n". 'engine='.$_POST['NetflowVersion'];
fwrite($fh,$string); // Write information to the file
fclose($fh); // Close the file
}
?>
但是,我需要此腳本使用 HTML 表單中的變數以不同方式“自動命名” .conf 檔案。例如,目前腳本正在創建檔案phptest.conf并寫入通過 HTML 表單輸入的以下資訊(每次都會不同):
collector-ip=10.0.0.0
collector-port=9000
engine=Netflow Version 10 (IPFIX)
由于每次運行腳本時這三個輸入都是唯一的,我想在每次提交表單時使用它們來命名新檔案。
例如,如果收集器 ip 為 5.5.5.5、收集器埠 9996 和引擎 Netflow 版本 10 (IPFIX),則檔案名將為5.5.5.5:9996:Netflow Version 10 (IPFIX).conf.
我對 PHP 很陌生,但我相信這可以通過使用檔案路徑中的(isset($_POST['CollectorIP']),($_POST['CollectorPort'])和isset($_POST['NetflowVersion'])變數來實作,這些變數將從輸入的資料中完成,并在每次提交表單時按預期命名檔案。
這是正確的還是我錯了?以下腳本會起作用還是有更好的方法來做到這一點?
<?php
$path = '/usr/local/flowsim/data/(isset($_POST['CollectorIP']):isset($_POST['CollectorPort']):isset($_POST['NetflowVersion']).conf';
if (isset($_POST['CollectorIP']) && isset($_POST['CollectorPort']) && isset($_POST['NetflowVersion'])) {
$fh = fopen($path,"a ");
$string = 'collector-ip='.$_POST['CollectorIP']. "\n". 'collector-port='.$_POST['CollectorPort']. "\n". 'engine='.$_POST['NetflowVersion'];
fwrite($fh,$string); // Write information to the file
fclose($fh); // Close the file
}
?>
uj5u.com熱心網友回復:
在展示代碼之前,我認為有幾點值得指出:
看起來您正在通過網路表單上的帖子接收這些資料。因此,您的意圖是允許用戶發送將寫入您服務器上的檔案的資料。這是一個很大的安全風險,因此您需要 100% 確定他們輸入的任何內容都是值得信賴的。
假設以上是正確的,并且該腳本將存在于 Web 服務器上,大多數情況下該腳本將沒有寫入權限來創建檔案/寫入檔案。因此,您必須修改權限等,這再次存在您必須注意的安全問題
無論如何,就腳本本身而言,您正在使用的行isset不會像它所寫的那樣作業。我會將測驗分開并這樣做:
if ( isset( $_POST['CollectorIP'] ) && isset($_POST['CollectorPort']) && isset($_POST['NetflowVersion']) ) {
// ok let's try to create the file
$path = '/usr/local/flowsim/data/' . trim($_POST['CollectorIP']) . ':' . trim($_POST['CollectorPort']) . ':' . trim($_POST['NetflowVersion']) . '.conf';
if ( $fh = fopen($path,"a ") ) {
$string = 'collector-ip='.$_POST['CollectorIP']. "\n". 'collector-port='.$_POST['CollectorPort']. "\n". 'engine='.$_POST['NetflowVersion'];
if ( fwrite($fh,$string) ) {
// yay
} else {
// do some sort of error handling because the file couldn't be written to
}
fclose($fh); // Close the file
} else {
// do some sort of error handling because the file couldn't be opened
}
} else {
// do some sort of error handling because they didn't provide the necessary data
}
uj5u.com熱心網友回復:
運算式不會在字串文字內進行評估。您需要使用串聯。
$path = '/usr/local/flowsim/data/' . (isset($_POST['CollectorIP']):isset($_POST['CollectorPort']):isset($_POST['NetflowVersion']) . '.conf';
在檔案名中使用 POST 資料時應該非常小心,因為用戶可以../../..輸入值以訪問要寫入的目錄之外的內容。添加一些資料驗證,或用于basename()丟棄目錄部分。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/516965.html
標籤:php
下一篇:如何根據模式過濾資料框?
