开发者

Writing user input to a file

The below code doesn't create info.txt file and dies: How can i show error codes in开发者_Go百科 such case - appending to die command with "."?

$MorF .= $name ." ". $family;
$MorF .="with username " . $user;
$MorF .="  and password " . $pass;
$MorF .=" lives in " . $city;

$fileLines = "";
if (file_exists("info.txt"))
{
    $fileLines = file_get_contents("info.txt");
    $fileNewLines = $fileLines . $MorF . "\n";
    file_put_contents("info.txt", $fileNewLines);   
}
else
{
    die("Something went wrong !");
}


You can use try...catch so you have some debugging information upon encountering an error. Also, not sure if this is intentional, but your logic there has the script fail when the file does not already exist. I've included an allowance for that condition here, but I am not certain if that was your intent.

  try {
    // do not continue if file does not exist
    if (!file_exists("info.txt"))
       die('Something went wrong: file does not exist');
    // append the data to the file
    $fileLines = file_get_contents("info.txt");
    $fileNewLines = $fileLines . $MorF . "\n";
    file_put_contents("info.txt", $MorF);       
  } catch (Exception $e) {
    // handle an error 
    die("Something went wrong: ".$e->getMessage());
  }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜