Why cant i do file write in php?
Hi i have a client connecting to a socket server in php.
I want to empty a particular file after connecting to the server, however, the codes is not giving me any error but it is not writing to the file?
<?php
set_ti开发者_开发问答me_limit(0);
//parameters to connect to server
$ip = "127.0.0.1";
$port = "1245";
$data = "";
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$result = socket_connect($socket, $ip, $port);
$myFile = "test.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, "");
while (true)
{
$data = "some value here"
socket_write($socket, $data, strlen($data));
$line =@socket_read($socket,2048, PHP_NORMAL_READ);
if($line != "")
{
echo $line."\n";
}
}
socket_close($socket);
?>
I'd use an absolute path $myFile = "/tmp/test.txt";
to make sure I knew where the file was to be written. Right now with just text.txt it could be written in a variety of places but most likely where the web servers binary is located.
If you'd rather not use an absolute path you can use http://php.net/manual/en/function.getcwd.php and http://www.php.net/manual/en/function.chdir.php to control the current working directory.
I would check the file is writable before trying to open it:
if(is_writable($myFile)) {
$fh = fopen($myFile, 'w');
} else {
die('unable to write to '.$myFile);
}
精彩评论