我已经阅读了关于stackoverflow可以找到的所有问题!这可能是重复的,但是我无法解决我的问题: 我无法使用php处理文件。
我已使用以下命令获得许可:
sudo chown -R www-data:www-data /var/www/mysite
sudo chmod -R 777 /var/www/mysite
这是代码:
<?php
if(isset( $_POST['save_values'])) { // retrieve the form data by using the element's name attributes value as key
if(!empty($_POST['getURL'])) {
$URL = $_POST['getURL'];
}
if(!empty($_POST['getRefreshRate'])) {
$RefreshRate = $_POST['getRefreshRate'];
}
if(!empty($_POST['getBrightness'])) {
$Brightness = $_POST['getBrightness'];
}
}
$filename = "/currentSettings.txt";
chmod($filename,0777);
$cSettings = fopen($filename, "r");
if($cSettings) {
echo "$cSettings exists";
while(($line = fgets($cSettings)) !== false) {
$arr = explode("\n", $line);
$URL = $arr[0];
$RefreshRate = $arr[1];
$Brightness = $arr[2];
}
fclose($cSettings);
} else {
echo "File does not exist";
fclose($cSettings);
$cSettings = fopen('/currentSettings.txt', 'w');
fwrite($cSettings,$URL."\n");
fwrite($cSettings,$RefreshRate."\n");
fwrite($cSettings,$Brightness."\n");
fclose($cSettings);
}
?>
它总是返回File does not exist
。它不会写入文件,也不会从文件读取。
我什至在www / mysite内部手动创建了文件,但仍然无法读取。
我对PHP还是很陌生,可以肯定我的代码已损坏,但是找不到解决方法。
<?php
$filename = "./inputs.txt";
$currentSettingsFile = fopen($filename, "c+");
$array = [];
if($currentSettingsFile) {
echo "Reading from $filename";
$array = explode(PHP_EOL, fread($currentSettingsFile, filesize($filename)));
var_dump($array);
$URL = $array[0];
$RefreshRate = $array[1];
$Brightness = $array[2];
$closeFlag = fclose($currentSettingsFile);
}
if(isset( $_POST['save_values'])) { // retrieve the form data by using the element's name attributes value as key
if(!empty($_POST['getURL'])) {
$URL = $_POST['getURL'];
$array[0] = $URL;
}
if(!empty($_POST['getRefreshRate'])) {
$RefreshRate = $_POST['getRefreshRate'];
$array[1] = $RefreshRate;
}
if(!empty($_POST['getBrightness'])) {
$Brightness = $_POST['getBrightness'];
$array[2] = $Brightness;
}
}
if(!$closeFlag) fclose($currentSettingsFile);
$currentSettingsFile = fopen($filename, "c");
if($currentSettingsFile) {
echo "Writing in $filename";
echo fwrite($currentSettingsFile,$array[0].PHP_EOL);
fwrite($currentSettingsFile,$array[1].PHP_EOL);
fwrite($currentSettingsFile,$array[2].PHP_EOL);
fclose($currentSettingsFile);
}
?>
答案 0 :(得分:1)
$handle
似乎没有定义。
这是一个似乎可以在尽可能接近示例的情况下运行的版本,但有一个重要警告:
$filename = "./currentSettings.txt";
if(is_file($filename)) {
echo "$filename exists";
$arr = explode("\n", file_get_contents($filename));
$URL = $arr[0];
$RefreshRate = $arr[1];
$Brightness = $arr[2];
} else {
echo "File does not exist";
$URL = ''."\n";
$RefreshRate = ''."\n";
$Brightness= ''."\n";
file_put_contents($filename, $URL.$RefreshRate.$Brightness);
chmod($filename,0777);
}
如果文件不存在,将创建它。 但是 ,由于未定义$URL, $RefreshRate, $Brightness
,因此仅向文件添加了三行。
我不确定项目的其余结构,但您可能需要定义一些占位符来填充文件。