2011-11-06 34 views
2

當我的腳本寫入文件時,它不會將添加的內容分解到新行。fwrite - 在變量之後需要一個新行 - PHP

Instead of: 
user1:password1 
user2:password2 

It writes: 
user1:password1user2:password2 

本來,我FWRITE這個樣子的fwrite($跳頻,$數據);並從搜索其他問題,我改變了我的代碼:

fwrite($fh, $data . "\n"); 

雖然這似乎並沒有工作。

這裏是我的代碼

<?php 

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

$username = $_POST['user']; 
$password = $_POST['password']; 
$confirmpw = $_POST['confirmpw']; 
$username = strtolower($username); 


//Check if passwords match 
if ($password != $confirmpw){ 
print "Passwords do not match, please try again."; 
} 
else{ 
//the data 
$data = "$username:$password\n"; 

//open the file and choose the mode 

$fh = fopen("passwd.txt", "a+"); 

// Cycle through the array 
$match_found = false; 

while (($buffer = fgets($fh, 4096)) !== false) 
{ 
// Parse the line 
list($usercheck, $passwordcheck) = explode(':', $buffer); 
if (trim($usercheck) == $username) 
{ 
    print "The username is already in our system. Please use another one."; 
    $match_found = true; 
    break; 
} 
} 

if(!$match_found) 
{ 
fwrite($fh, $data . "\n"); 
// Set cookies for an hour 
$hour = time() + 3600; 
setcookie("username", $username, $hour); 
//Redirect to home page 
header("location: index.php"); 
} 


} 
//close the file 

fclose($fh); 


} 


?> 
+2

使用PHP_EOL,它是一個包含您的操作平臺的EOL字符是預定的常數。 –

+0

看起來問題是這條線: $ data =「$ username:$ password \ n」; 當我在\ n之後刪除\ n後,一切似乎都奏效。 感謝您爲所有人提供幫助。 – Moses89

回答

3

你需要使用什麼是\r\n

+0

看起來問題是這條線: $ data =「$ username:$ password \ n」; 當我在\ n之後刪除\ n後,一切似乎都奏效。 感謝您爲所有人提供幫助。 – Moses89

+0

你救了我傍晚:)謝謝 – mit

0

對平臺相關換行符使用PHP_EOL。但是,\n實際上代表了* NIX世界中的換行符,但是一些窗口編輯器拒絕將它們顯示爲換行符(即您的情況會發生什麼)。您應該考慮使用其他IDE並始終使用\n以實現兼容性(如果該文件應在其他平臺上可用)。

2

對我來說只是工作PHP_EOL(在Windows 7的XAMPP PHP 5.3.8)

+0

這是我的fwrite()問題的答案 – Lego

相關問題