这段 PHP 代码可以改进吗?

发布于 2024-12-01 12:09:00 字数 3018 浏览 0 评论 0原文

我想要实现的基本上是根据通过表单输入的数据设置变量(然后在整个网站中使用这些变量)。我不关心安全问题,因为我是唯一有权访问该表格的人。

因此,目前我使用 fwrite 将数据保存在单独的文件中,然后对每个变量使用 file_get_contents 。表单中的数据很小,每个字段只有一两个字。

我无法使用数据库,因此下面是我目前正在工作的示例,它可以改进还是有其他方法可以实现这一目标?

<?php

if(isset($_REQUEST['sub']))
{
$myFile = "first.php";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = $_REQUEST['first'];
$string = preg_replace("/[^a-zA-Z0-9.:,=?%\/\\s]/", "", $stringData);
fwrite($fh, $string);
fclose($fh);

$myFile_second = "second.php";
$fh2 = fopen($myFile_second, 'w') or die("can't open file2");
$stringData2 = $_REQUEST['second'];
$string2 = preg_replace("/[^a-zA-Z0-9.:,=?%\/\\s]/", "", $stringData2);
fwrite($fh2, $string2);
fclose($fh2);

$myFile_third = "third.php";
$fh3 = fopen($myFile_third, 'w') or die("can't open file3");
$stringData3 = $_REQUEST['third'];
$string3 = preg_replace("/[^a-zA-Z0-9.:,=?%\/\\s]/", "", $stringData3);
fwrite($fh3, $string3);
fclose($fh3);
}

$first = file_get_contents ("first.php");
$second = file_get_contents ("second.php");
$third = file_get_contents ("third.php");

?>

<form method="post" name="installer">

<div id="field">
<label>First</label>
<input type="text" name="first" value="<?php echo $first; ?>" />
</div>

<div id="field">
<label>Second</label>
<input type="text" name="second" value="<?php echo $second; ?>" />
</div>

<div id="field">
<label>Third</label>
<input type="text" name="third" value="<?php echo $third; ?>" />
</div>

<div id="submit">
<input type="submit" value="Save" name="sub" />
</div>

</form>

任何建议将不胜感激,谢谢:)

更新

非常感谢大家的帮助和建议。我现在已经实现了类似于下面的东西,我必须说它效果非常好!

<?
if (isset($_REQUEST['sub'])) {

    $files_data = array(
        'first' => &$_REQUEST['first'],
        'second' => &$_REQUEST['second'],
        'third' => &$_REQUEST['third']
    );

    $files_data = preg_replace("/[^a-zA-Z0-9.:,=?%\/\\s]+/", "", $files_data);

    file_put_contents('data.txt', serialize($files_data)) !== FALSE or die("Can't write to file!" . PHP_EOL);
    } 

$files_data = unserialize(file_get_contents('data.txt'));

$first = $files_data[first];
$second = $files_data[second];
$third = $files_data[third];

?>

<form method="post" name="installer">
<div id="field">
<label>First</label>
<input type="text" name="first" value="<?php echo $first; ?>" />
</div>
<div id="field">
<label>Second</label>
<input type="text" name="second" value="<?php echo $second; ?>" />
</div>
<div id="field">
<label>Third</label>
<input type="text" name="third" value="<?php echo $third; ?>" />
</div>
<div id="submit">
<input type="submit" value="Save" name="sub" />
</div>
</form>

What I'm wanting to achieve is basically setting variables from data entered through my form (these variables are then used throughout my website). I'm not to concerned with security as I'm the only one who would have access to the form.

So at the moment I am using fwrite to save the data in separate files and then using file_get_contents for each variable. The data from the form is small, one or two words for each field.

I'm unable to use a database so below is an example of what I have working at the moment, can it be improved or is there any other ways of achieving this?

<?php

if(isset($_REQUEST['sub']))
{
$myFile = "first.php";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = $_REQUEST['first'];
$string = preg_replace("/[^a-zA-Z0-9.:,=?%\/\\s]/", "", $stringData);
fwrite($fh, $string);
fclose($fh);

$myFile_second = "second.php";
$fh2 = fopen($myFile_second, 'w') or die("can't open file2");
$stringData2 = $_REQUEST['second'];
$string2 = preg_replace("/[^a-zA-Z0-9.:,=?%\/\\s]/", "", $stringData2);
fwrite($fh2, $string2);
fclose($fh2);

$myFile_third = "third.php";
$fh3 = fopen($myFile_third, 'w') or die("can't open file3");
$stringData3 = $_REQUEST['third'];
$string3 = preg_replace("/[^a-zA-Z0-9.:,=?%\/\\s]/", "", $stringData3);
fwrite($fh3, $string3);
fclose($fh3);
}

$first = file_get_contents ("first.php");
$second = file_get_contents ("second.php");
$third = file_get_contents ("third.php");

?>

<form method="post" name="installer">

<div id="field">
<label>First</label>
<input type="text" name="first" value="<?php echo $first; ?>" />
</div>

<div id="field">
<label>Second</label>
<input type="text" name="second" value="<?php echo $second; ?>" />
</div>

<div id="field">
<label>Third</label>
<input type="text" name="third" value="<?php echo $third; ?>" />
</div>

<div id="submit">
<input type="submit" value="Save" name="sub" />
</div>

</form>

Any suggestions would be much appreciated thanks :)

Update

Well thank you to everyone for your help and suggestions. I've now implemented something similar to below and I must say it works wonderfully!

<?
if (isset($_REQUEST['sub'])) {

    $files_data = array(
        'first' => &$_REQUEST['first'],
        'second' => &$_REQUEST['second'],
        'third' => &$_REQUEST['third']
    );

    $files_data = preg_replace("/[^a-zA-Z0-9.:,=?%\/\\s]+/", "", $files_data);

    file_put_contents('data.txt', serialize($files_data)) !== FALSE or die("Can't write to file!" . PHP_EOL);
    } 

$files_data = unserialize(file_get_contents('data.txt'));

$first = $files_data[first];
$second = $files_data[second];
$third = $files_data[third];

?>

<form method="post" name="installer">
<div id="field">
<label>First</label>
<input type="text" name="first" value="<?php echo $first; ?>" />
</div>
<div id="field">
<label>Second</label>
<input type="text" name="second" value="<?php echo $second; ?>" />
</div>
<div id="field">
<label>Third</label>
<input type="text" name="third" value="<?php echo $third; ?>" />
</div>
<div id="submit">
<input type="submit" value="Save" name="sub" />
</div>
</form>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

下雨或天晴 2024-12-08 12:09:00

我猜你这样做是为了持久性(即网络服务器重新启动并且你希望数据在备份后仍然存在)?因此,如果您一直在编写、读取和解析大量文件,那么就很难从执行中节省大量时间。

您可以查看 fscan ,看看这是否会使读取速度更快一些你。

除此之外,我建议您在解析文件后缓存数据,这样您就不必一遍又一遍地执行此操作,并且只需在文件更改后重新扫描。您可以通过校验和或查看文件修改时间戳来跟踪这一点。

“简化”的一种方法是将您发布的数据保存在数组中,然后序列化并将其保存到文件中。然后,您可以一次性读取整个文件并反序列化它,您将获得包含数据的数组。

将数组保存到文件的一种快速而肮脏的方法类似于

file_put_contents('mydatafile', serialize($myArray)));

和 取回数组

$myArray = unserialize(file_get_contents('mydatafile'));

I guess you are doing this for persistence (i.e. the web server reboots and you want your data to be there once it's back up)? So if you are stuck with writing, reading and parsing a multitude of files it's hard to shave massive amounts of time from your execution.

You could look at fscan and see if that will make the reading a bit faster for you.

Other than that I recommend that you cache the data once you have parsed the files so you don't have to do it over and over and only rescan once the files change. You could keep track of this by a checksum or looking at the files modified time stamp.

One way to "simplify" it would be to save your posted data in an array and serializing that and saving it to a file. Then you could read the entire file in one go and unserialize it and you would have your array with the data back.

A quick-and-dirty way to save a array to a file would be something like

file_put_contents('mydatafile', serialize($myArray)));

and to get the array back

$myArray = unserialize(file_get_contents('mydatafile'));
聊慰 2024-12-08 12:09:00

您可以使用 php 会话来存储和检索值。
http://www.w3schools.com/php/php_sessions.asp

其次你可以使用SplFileInfo 而不是 fopen 、 fwrite

$myFile = 'foo.txt';
$file = new SplFileInfo($myFile);
$lines = $file->openFile('w');

you can use php sessions to store and retrieve values.
http://www.w3schools.com/php/php_sessions.asp

Secondly you can use SplFileInfo instead of fopen , fwrite

$myFile = 'foo.txt';
$file = new SplFileInfo($myFile);
$lines = $file->openFile('w');
月亮坠入山谷 2024-12-08 12:09:00

这应该可以解决问题。

<?php

if( isset($_REQUEST['sub']) ){

$files = array(
    'first.php'  => $_REQUEST['first'],
    'second.php' => $_REQUEST['second'],
    'third.php'  => $_REQUEST['third']
);  

foreach($files as $file => $request){
    $fh = fopen($file,'w') or die("can't open file ". $file);
    $string = preg_replace("/[^a-zA-Z0-9.:,=?%\/\\s]/", "", $request);
    fwrite($fh, $string);
    fclose($fh);
}

}

$first = file_get_contents ("first.php");
$second = file_get_contents ("second.php");
$third = file_get_contents ("third.php");

?>

但正如上面所说,使用数据库效率要高得多。

This should do the trick.

<?php

if( isset($_REQUEST['sub']) ){

$files = array(
    'first.php'  => $_REQUEST['first'],
    'second.php' => $_REQUEST['second'],
    'third.php'  => $_REQUEST['third']
);  

foreach($files as $file => $request){
    $fh = fopen($file,'w') or die("can't open file ". $file);
    $string = preg_replace("/[^a-zA-Z0-9.:,=?%\/\\s]/", "", $request);
    fwrite($fh, $string);
    fclose($fh);
}

}

$first = file_get_contents ("first.php");
$second = file_get_contents ("second.php");
$third = file_get_contents ("third.php");

?>

But as said above, it's much more efficient to use databases.

家住魔仙堡 2024-12-08 12:09:00
<?php

function do_file_operation($filename,$field_name)
{
    $myFile = $filename;
    $fh = fopen($myFile, 'w') or die("can't open file");
    $stringData = $_POST[$field_name];
    $string = preg_replace("/[^a-zA-Z0-9.:,=?%\/\\s]/", "", $stringData);
    fwrite($fh, $string);
    fclose($fh);
}


if(isset($_POST['sub']))
{

    do_file_operation("first.php","first");
    do_file_operation("second.php","second");
    do_file_operation("third.php","third");

}

$first = file_get_contents ("first.php");
$second = file_get_contents ("second.php");
$third = file_get_contents ("third.php");

?>

<form method="post" name="installer">

<div id="field">
<label>First</label>
<input type="text" name="first" value="<?php echo $first; ?>" />
</div>

<div id="field">
<label>Second</label>
<input type="text" name="second" value="<?php echo $second; ?>" />
</div>

<div id="field">
<label>Third</label>
<input type="text" name="third" value="<?php echo $third; ?>" />
</div>

<div id="submit">
<input type="submit" value="Save" name="sub" />
</div>

</form>
<?php

function do_file_operation($filename,$field_name)
{
    $myFile = $filename;
    $fh = fopen($myFile, 'w') or die("can't open file");
    $stringData = $_POST[$field_name];
    $string = preg_replace("/[^a-zA-Z0-9.:,=?%\/\\s]/", "", $stringData);
    fwrite($fh, $string);
    fclose($fh);
}


if(isset($_POST['sub']))
{

    do_file_operation("first.php","first");
    do_file_operation("second.php","second");
    do_file_operation("third.php","third");

}

$first = file_get_contents ("first.php");
$second = file_get_contents ("second.php");
$third = file_get_contents ("third.php");

?>

<form method="post" name="installer">

<div id="field">
<label>First</label>
<input type="text" name="first" value="<?php echo $first; ?>" />
</div>

<div id="field">
<label>Second</label>
<input type="text" name="second" value="<?php echo $second; ?>" />
</div>

<div id="field">
<label>Third</label>
<input type="text" name="third" value="<?php echo $third; ?>" />
</div>

<div id="submit">
<input type="submit" value="Save" name="sub" />
</div>

</form>
萌酱 2024-12-08 12:09:00
<?
if (isset($_REQUEST['sub'])) {
    # MAKE SURE YOUR FORM IS WELL PROTECTED !
    file_put_contents("first.php",  preg_replace("/[^a-zA-Z0-9.:,=?%\/\\s]/", "", $_REQUEST['first']));
    file_put_contents("second.php", preg_replace("/[^a-zA-Z0-9.:,=?%\/\\s]/", "", $_REQUEST['second']));
    file_put_contents("third.php", preg_replace("/[^a-zA-Z0-9.:,=?%\/\\s]/", "", $_REQUEST['third']));
}    
?>
<form method="post" name="installer">
<div id="field">
<label>First</label>
<input type="text" name="first" value="<?php echo file_get_contents("first.php"); ?>" />
</div>
<div id="field">
<label>Second</label>
<input type="text" name="second" value="<?php echo file_get_contents("second.php"); ?>" />
</div>
<div id="field">
<label>Third</label>
<input type="text" name="third" value="<?php echo file_get_contents("third.php"); ?>" />
</div>
<div id="submit">
<input type="submit" value="Save" name="sub" />
</div>
</form>
<?
if (isset($_REQUEST['sub'])) {
    # MAKE SURE YOUR FORM IS WELL PROTECTED !
    file_put_contents("first.php",  preg_replace("/[^a-zA-Z0-9.:,=?%\/\\s]/", "", $_REQUEST['first']));
    file_put_contents("second.php", preg_replace("/[^a-zA-Z0-9.:,=?%\/\\s]/", "", $_REQUEST['second']));
    file_put_contents("third.php", preg_replace("/[^a-zA-Z0-9.:,=?%\/\\s]/", "", $_REQUEST['third']));
}    
?>
<form method="post" name="installer">
<div id="field">
<label>First</label>
<input type="text" name="first" value="<?php echo file_get_contents("first.php"); ?>" />
</div>
<div id="field">
<label>Second</label>
<input type="text" name="second" value="<?php echo file_get_contents("second.php"); ?>" />
</div>
<div id="field">
<label>Third</label>
<input type="text" name="third" value="<?php echo file_get_contents("third.php"); ?>" />
</div>
<div id="submit">
<input type="submit" value="Save" name="sub" />
</div>
</form>
A君 2024-12-08 12:09:00

这只是@Austin Brunkhorst 代码的一点修改。抱歉,评论太多,无法发表。

if (isset($_REQUEST['sub'])) {
    //No need to copy variables
    $files_data = array(
        'first' => &$_REQUEST['first'],
        'second' => &$_REQUEST['second'],
        'third' => &$_REQUEST['third']
    );
    //Note that you should use '+' at the end of match
    //so that preg can match more the one character at once,
    //it is much faster. And we can apply it once to whole array.
    $files_data = preg_replace("/[^a-zA-Z0-9.:,=?%\/\\s]+/", "", $files_data);
    //Note '&' in foreach to disable variable copying
    foreach ($files_data as $filename => &$request_str) {
        //Why use complex fwrite when we have a ready function to write to file?
        file_put_contents($filename . '.php', $request_str) !== FALSE or die("Can't write to file '$filename'!" . PHP_EOL);
        //We don't need to read files again when we already have our string
        //It is ugly, but fun! Maby this should be avoided :)
        $filename = $request_str;
    }
} else {
    $first = file_get_contents("first.php");
    $second = file_get_contents("second.php");
    $third = file_get_contents("third.php");
}

This is just a little modification of @Austin Brunkhorst's code. Sorry, too much to post in comment.

if (isset($_REQUEST['sub'])) {
    //No need to copy variables
    $files_data = array(
        'first' => &$_REQUEST['first'],
        'second' => &$_REQUEST['second'],
        'third' => &$_REQUEST['third']
    );
    //Note that you should use '+' at the end of match
    //so that preg can match more the one character at once,
    //it is much faster. And we can apply it once to whole array.
    $files_data = preg_replace("/[^a-zA-Z0-9.:,=?%\/\\s]+/", "", $files_data);
    //Note '&' in foreach to disable variable copying
    foreach ($files_data as $filename => &$request_str) {
        //Why use complex fwrite when we have a ready function to write to file?
        file_put_contents($filename . '.php', $request_str) !== FALSE or die("Can't write to file '$filename'!" . PHP_EOL);
        //We don't need to read files again when we already have our string
        //It is ugly, but fun! Maby this should be avoided :)
        $filename = $request_str;
    }
} else {
    $first = file_get_contents("first.php");
    $second = file_get_contents("second.php");
    $third = file_get_contents("third.php");
}

如果您只想在项目中包含代码,可以使用 eval

$includes = array('first', 'second', 'third');
foreach ($includes as $value) {
    $code = preg_replace("/[^a-zA-Z0-9.:,=?%\/\\s]/", "", $_REQUEST[$value]);
    if (!eval($code))
        die('Parse Error in $_REQUEST["'.$value.'"]');
}

正如所指出的,这使您容易受到任何攻击,因此请确保您真正保护脚本,例如使用.htaccess-文件

If you just want to include the code in your project, you can use eval:

$includes = array('first', 'second', 'third');
foreach ($includes as $value) {
    $code = preg_replace("/[^a-zA-Z0-9.:,=?%\/\\s]/", "", $_REQUEST[$value]);
    if (!eval($code))
        die('Parse Error in $_REQUEST["'.$value.'"]');
}

As pointed out, this leaves you wide open for any attack, so make sure you really secure the script, e.g. with a .htaccess-file.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文