限制php if语句来评估上次写入

时间:2017-04-18 20:03:55

标签: php if-statement

我正在尝试将几个php if语句仅在最后一个fwrite运行时运行。我只想使用$ output输出一个$ key。这是我的代码片段:

$cnt = 1;
fwrite($fh, $phptag);
$cnt = 2;
// The last fwrite that I want checked
fwrite($fh, $key);
// Check if write has been successful
if ($fwrite !== false && $cnt == 2) {
  $output = json_encode(array( // create JSON data
    'type'=>'success', 
    'text' => 'Congratulations !  The salt key has been successfully created.'
  ));
  exit($output); // exit script outputting json data
}
// Check if write has been unsuccessful
if ($fwrite === false && $cnt == 2) {
  $output = json_encode(array( // create JSON data
   'type'=>'error', 
    'text' => 'There has been an error in creating the salt key.'
  ));
  exit($output); // exit script outputting json data
}

我尝试使用$ cnt来控制何时运行,但是$ output永远不会被发送回ajax done语句 - 只是未定义。我做错了什么?

更新代码:

fwrite($fh, $phptag);
// The last fwrite that I want checked
fwrite($fh, $key);
// Check if write has been successful
if (fwrite($fh, $key)) { // Check if write has been successful
  $output = json_encode(array( // create JSON data
    'type'=>'success', 
    'text' => 'Congratulations !  The salt key has been successfully created.'
  ));
}
else {  // Check if write has been unsuccessful
  $output = json_encode(array( // create JSON data
    'type'=>'error', 
    'text' => 'There has been an error in creating the salt key.'
  ));
}
exit($output); // exit script outputting json data
fclose($fh);

更新#2:

fwrite($fh, $phptag);
//fwrite($fh, $key);
// Check if write has been successful
if (fwrite($fh, $key)) { // Check if write has been successful
  $output = json_encode(array( // create JSON data
    'type'=>'success', 
    'text' => 'Congratulations !  The salt key has been successfully created.'
  ));
}
else {  // Check if write has been unsuccessful
  $output = json_encode(array( // create JSON data
    'type'=>'error', 
    'text' => 'There has been an error in creating the salt key.'
  ));
}
exit($output); // exit script outputting son data
fclose($fh);

2 个答案:

答案 0 :(得分:2)

fwrite返回写入文件的字节数,如果有错误则返回FALSE。所以你可以检查一下。

if (fwrite($fh, $key)) {
    $output = json_encode(array( // create JSON data
        'type'=>'success', 
        'text' => 'Congratulations !  The salt key has been successfully created.'
      ));
} else {
    $output = json_encode(array( // create JSON data
        'type'=>'error', 
        'text' => 'There has been an error in creating the salt key.'
    ));
}
exit($output);

答案 1 :(得分:0)

为什么使用exit而不是return?这是我想的问题

如果写入失败,您可以避免不成功的检查原因,您将始终到达错误输出。