I am using latest version of php.. and i stuck on this error
Warning: fwrite() expects parameter 1 to be resource, string given in c:\ this error shows me 6 times
Warning: fclose() expects parameter 1 to be resource, string given in // this error reapeat only one time.
I am trying to get last id of last line but i am facing that error.. here is my php code :
<?php
include_once('../../fucrenzione.php');
/*
$codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$codeAlphabet.= "abcdefghijklmnopqrstuvwxyz";
$codeAlphabet.= "0123456789";*/
$filename ="data.txt" or die("Unable to open file!");
$line="";
fopen($filename, 'a+');
for($i=0;$i<=5;$i++ ){
$va=rand(1,20);
$re= rand(2,50);
$data = [
'val1' => $va,
'val2' => $re,
'body' => getToken(10),
'Id'=> $i,
'timestamp' => time()
];
/* echo "<pre>".*/$line = serialize($data);
$line .= "\n";
fwrite($filename, $line);
}
fclose($filename);
?>
I tried to use also fputs() but i still get that error.
The error tells you the issue. fopen() returns a resource:
$handle = fopen($filename, 'a+');
Then fwrite() expects the first argument to be that resource:
fwrite($handle, $line);
Also, I think the or die("Unable to open file!"); would be better on the fopen() line rather than the assignment line.
Related
Disclaimer: I am very unfamiliar with PHP. The answers I have seen floating around Stack don't seem applicable to my situation. This could be due to my unfamiliarity.
I need to write to an existing array in a JSON file:
[
[
// data should be written to this array
],
[]
]
My PHP looks like so:
<?php
$ip = $_POST["ip"];
$likes = "../data/likes.json";
$fp = fopen($likes, "a");
fwrite($fp, json_encode($ip) . ", ");
fclose($fp);
?>
When the PHP runs it writes to the end of the file like so (as you'd expect):
[
[
],
[]
]"data",
How do I resolve my PHP to do so?
Open the file:
$filename = '../data/likes.json'
$fp = fopen($filename, 'r');
Then read the existing data structure into a variable:
$data = json_decode(fread($fp, filesize($filename)));
Add the data to the correct array entry:
$data[0][] = $ip;
Close and reopen the file with write privileges, so that we overwrite its contents:
fclose($fp);
$fp = fopen($filename, 'w');
And write the new JSON:
fwrite($fp, json_encode($data));
$ip = $_POST["ip"];
$likes = json_decode(file_get_contents("../data/likes.json"), true);
$likes[] = $ip;
file_put_contents("../data/likes.json", json_encode($likes));
You can not fimply add record to file and get valid json jbject.
So idea of that code:
we read all from file, append array with new data, and rewrite file with new data
I want to parse csv-like string so I can emulate csv and assert it into a test case.
// init CSV-like string
$str = <<<EOD
1,john\r\n
2,smith\r\n
EOD;
// Open file Handler, puts the CSV-like string, rewind the file pointer
$fp = fopen('php://memory','r+');
fputs($fp,$str);
rewind($fp);
// Parse the CSV-like string
$parsed = [];
while (($data = fgetcsv($fp, 2048)) !== FALSE) {
$parsed[] = fgetcsv($fp);
}
var_dump($parsed);
But it won't parse into arrays. This is the output:
array (size=2)
0 =>
array (size=1)
0 => null
1 => boolean false
Remove the \r\n, not needed
Your moving the pointer twice per loop, change to $parsed[] = $data
... the code is nice, however, #Verbatim has fgetcsv() twice.
I am trying to get details for bans on a Steam user account using the file_get_contents function in PHP. However, it keeps erroring and I have no idea why:
$detailURL = file_get_contents("http://api.steampowered.com/ISteamUser/GetPlayerBans/v1/?key=3C11B751BB59DEEE28D744C0A8BAC2EC&steamids=76561198078737264");
$profile = file_get_contents($detailURL);
$buffer = fopen("coOn4LxnQm/{$steamIDpost}.json", "w+");
fwrite($buffer, $profile);
fclose($buffer);
$steam = json_decode(file_get_contents("coOn4LxnQm/{$steamIDpost}.json"));
The error is as follows:
Warning: file_get_contents({ "players": [ { "SteamId": "76561198078737264", "CommunityBanned": false, "VACBanned": true, "NumberOfVACBans": 1, "DaysSinceLastBan": 309, "NumberOfGameBans": 0, "EconomyBan": "none" } ] }): failed to open stream: Invalid argument in C:\xampp\htdocs\addToList.php on line 18
If you have any idea, please help me. No idea what "failed to open stream: Invalid argument" means and googling and such did not help much.
Thanks.
After this line
$detailURL = file_get_contents("http://api.steampowered.com/ISteamUser/GetPlayerBans/v1/?key=3C11B751BB59DEEE28D744C0A8BAC2EC&steamids=76561198078737264");
$detailURL will now contain the result from the API (a JSON String)
If you have a look at this line:
$profile = file_get_contents($detailURL);
This line is doing a file_get_contents on a JSON String, and it has no sense.
Why am I receiving this error? According to the ftp_get docs, the function is defined like so:
bool ftp_fget ( resource $ftp_stream , resource $handle , string $remote_file , int $mode [, int $resumepos = 0 ] )
However, when I pass this function a file resource, I receive the error:
ftp_get() expects parameter 2 to be a valid path, resource given
Here is my code:
$ftp = ftp_connect(FTP_HOST);
if (ftp_login($ftp, FTP_USERNAME, FTP_PASSWORD)) {
$file = tmpfile();
if(ftp_get($ftp, $file, FTP_FILENAME, FTP_ASCII)) {
file_get_contents($file);
}
}
Why is the error suggesting that the function expects a path, when the docs show it defined as expecting a resource? I am using PHP 5.5.9.
Because you use the doc of ftp_fget instead of ftp_get:
http://php.net/manual/en/function.ftp-get.php
bool ftp_get ( resource $ftp_stream , string $local_file , string $remote_file , int $mode [, int $resumepos = 0 ] )
I am using stream_get_line to store some php output in a variable, while I'm running a telnet session via fsockopen.
However, my second server does not run PHP5, which is disabled the ability to use stream_get_line. Is there any alternative for PHP 4.3?
I heard that fgets is almost the same, but I don't seem to get it to work exactly like stream_get_line.
Code:
...
# opening connection
$fp = #fsockopen($ip, 23, $errno, $errstr, 8);
# loggin in
fputs($fp, "$user\r");
usleep(250000);
fputs($fp, "$password\r");
# getting information
fputs($fp, "show info\n");
usleep(250000);
fputs($fp, "show info 2\n");
usleep(250000);
fputs($fp, "show info 3\n");
usleep(250000);
fputs($fp, "show info 4\n");
usleep(250000);
fputs($fp, "?\n");
$content = stream_get_line($fp, 0, "?");
$contentvalues = array(
1 => substr($content, 130, 3),
2 => substr($content, 180, 3)
);
fclose($fp);
...
(I am storing specific parts of my output in the $contentvalues variable.)
From the docs:
This function is nearly identical to fgets() except in that it allows
end of line delimiters other than the standard \n, \r, and \r\n, and
does not return the delimiter itself.
From the comments:
when fgets reads some bytes from socket, where EOF is reached, it
returns bool(false) same as stream_get_line
BUT if remote client drops connection, and server script will try to
read some data with function fgets, function will return bool(false),
and stream_get_line will return string(0) ""
so you can detect remote client disconnection with stream_get_line,
and cannot with fgets
There's also some dithering about which function is faster, but it seems to be dependant on the version of PHP, the day of the week, and what the commenter had for dinner the previous night.
edit
Judging by your response to Steffen's answer you're hung up on the fact that fgets() does not take a third parameter as a delimiter. Applying a basic input loop and checking the string will get you there. Also, in Steffen's defense, you were never quite clear on in your question, stating only that it doesn't "work exactly like stream_get_line".
<?php
$delim = '?';
$buf = 4096;
$fp = #fsockopen($ip, 23, $errno, $errstr, 8);
// ... yadda yadda yadda ... //
$content = '';
while( $part = fgets($fp, $buf) ) {
$ind = strpos($part, $delim);
if( $ind !== false ) {
$content .= substr($part, 0, $ind);
break;
}
$content .= $part;
}
Also, even with stream_get_line() you should be using a loop to get the input as a length parameter or 0 does not mean "unlimited", but rather will use one of PHP's defaults which is 8192 bytes.
You can use fgets() (string fgets ( resource $handle [, int $length ] )) instead.
http://www.php.net/manual/de/function.fgets.php