限制PHP如果语句评估最后写



我正在尝试获得几个php,如果语句仅在最后一个FWRITE运行时运行。而且我只想使用$输出输出一个$键。这是我的代码片段:

$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来控制何时运行,但是$输出永远不会发送回AJAX DOUST DOUST DOUST的语句 - 只是变得不确定。我做错了什么?

更新的代码:

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);

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);

为什么要使用退出而不是返回?这是你的问题,我认为

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

最新更新