fgets() Warning: Not a valid stream resource - php

I had a script that was working fine until suddenly my input reads failed for:
Warning: Not a valid stream resource in
/data/users/myusername/processingscript.php on line 1036
and fails at line with fgets(). My function is below
function read_stdin($question)
{
echo "\033[1;37m".$question;
$fr=fopen("php://stdin","r"); // open our file pointer to read from stdin
$input = fgets($fr,128); // read a maximum of 128 characteyrs
$input = strtolower(rtrim($input)); // trim any trailing spaces.
fclose ($fr); // close the file handle
return $input; // return the text entered
}
I have no idea what has happened and can't find an answer elsewhere.

Related

Copy a file's text to another file PHP

I want to copy the content from (Bazamod.txt) to (compile.txt) but I get this error:
Warning: fopen(LicenteSi/Test/compile.txt): failed to open stream: No
such file or directory in
/storage/ssd3/361/16261361/public_html/createL.php on line 137
Warning: fwrite() expects parameter 1 to be resource, boolean given in
/storage/ssd3/361/16261361/public_html/createL.php on line 141
Function create_compile_mod($Licence_Name, $Path){
$FilePath = "$Path/compile.txt";
$myFile = fopen($FilePath, "r+");
copy("bazamod/Bazamod.txt", $FilePath);
fwrite($myFile, $FilePath);
}
Thank you!
If you what you need to do is just to copy the contents of Bazamod.txt to compile.txt, by providing a path to compile.txt as argument, then the following function will do the trick:
<?php
function create_compile_mod($Path)
{
$fileContents = file_get_contents("bazamod/Bazamod.txt");
$fileHandle = fopen($Path . "/compile.txt", "r+");
fputs($fileHandle, $fileContents);
fclose($fileHandle);
}
?>
I have not included your $Licence_Name argument as it does not seem to be used, but you can adapt the above code to fit your needs.
Keep in mind that the above code will copy the entire contents of Bazamod.txt and replace the existing contents of compile.txt. If you would just like to append new text, use the "a" access mode instead of the specified "r+", and the text will automatically be added at the bottom of the document.
If you need to add at a specific line, you could go for:
<?php
function create_compile_mod($Path, $lineIndex)
{
$oldContents = file_get_contents("bazamod/Bazamod.txt");
$compileArray = file($Path . "compile.txt");
array_splice($compileArray, $lineIndex, 0, $oldContents);
$newContent = implode(PHP_EOL, $compileArray);
$compileFh = fopen($Path . "compile.txt", "r+");
fputs($compileFh, $newContent);
}
?>
Specify your $lineIndex to be the line number at which you want you content to be put (starting from line 0), and call your function like create_compile_mod("./", 4).

Reading .gz file line by line

I am trying to read large .gz file line by line.
Here is what i got so far:
$sfp = gzopen($filename, "rb");
while (!gzeof($sfp))
{
$line = gzread($sfp, 4096);
}
and thats where the problem comes in, gzread reading the length specified in variable (in this case 4096) and ignoring new lines .
I checked "fget" function and it works properly, so its reading line limiting the size by hitting new line or the size which ever comes first.
How I can do the same with gzread or any work around ?
Use fgets() just like reading an ordinary file.
You shouldn't use b mode if you're reading lines, since line-by-line implies it's a text file.
$sfp = gzopen($filename, "r");
while ($line = fgets($sfp)) {
echo $line;
}

Creating new files from an old one

while (($line = fgets($handle)) !== false) {
//look for the first payor block
if(strpos($line, 'N1*PR*') !== false || $block_start) {
$header_end = true; $block_start = true;
//see if the block finished
if(strpos($line, 'CAS*CO*45*20.43**253*1.27~') !== false) {
$block_start = false;
$payor_blocks[$count] .= $line;
$count++;
}
$payor_blocks[$count] .= $line;
} else {
//append to the header
if($header_end) {
$footer .= $line."\n";
} else {
$header .= $line."\n";
}
}
}
//get payor blocks and create a file foreach payor
$new_files = array();
foreach($payor_blocks as $block) {
$filename = $file . "_" . $count;
$count++;
$new_files[] = array(
'name' => $filename,
'content' => $header."\n".$block."\n".$footer
);
//loop through new files and create them
foreach($new_files as $new_file) {
$myfile = fopen($file, "x");
fwrite($myfile, $new_file['content']);
//close the file
fclose($myfile);
I have the code above, it's suppose to be able to open an original file called "$file" and create a new file then close it, However its not creating and when I run it, i get this warning error:
Warning: fopen(362931550.1a): failed to open stream:
File exists in /script2.php on line 90 Warning:
fwrite() expects parameter 1 to be resource,
boolean given in /script2.php on line 94 Warning:
fclose() expects parameter 1 to be resource, boolean
given in /script2.php on line 96
Any help is kindly appreciated.
I have one file named: 362931550.1a
I did a code that splits them at certain areas, (its pretty long to post), when i run the script I see it on my browser but it doesn't create 2 new files in the folder.
Your file open mode is incorrect.
From php.net documentation:
'x' Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING [...]
You should probably use 'w' mode:
'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
The script failed to open a stream with the fopen() function and return a boolean. The function fwrite() become the boolean value but need a resource.
The reason is that you only create files with the x-modifier in the stream.
Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it.
You see in the PHP manual more informations about the stream-modes (PHP manual).
To prevent this message check if the value isn't false.
$stream = fopen("file.txt", "x");
if($stream === false) {
echo "Error while open stream";
}
//here your code

Error by creating file

I got a error when creating a file using this php code:
$userdbfile = file('userfiles/' . $steamprofile['steamid'] . '.txt');
$fhuserdb = fopen($userdbfile, 'a');
fwrite($fhuserdb, $steamprofile['steamid']);
fwrite($fhuserdb, "0");
close($fhuserdb);
header("Location: index.html");
exit;
Error:
Warning: file(userfiles/76561198043436466.txt): failed to open stream: No such file or directory in /home/u294343259/public_html/admin/lw/login.php on line 7
Warning: fopen(): Filename cannot be empty in /home/u294343259/public_html/admin/lw/login.php on line 12
Warning: fwrite() expects parameter 1 to be resource, boolean given in /home/u294343259/public_html/admin/lw/login.php on line 13
Warning: fwrite() expects parameter 1 to be resource, boolean given in /home/u294343259/public_html/admin/lw/login.php on line 14
Fatal error: Call to undefined function close() in /home/u294343259/public_html/admin/lw/login.php on line 15
file() doesn't create a new file! It only reads file. So just remove it and use fopen(), like this
$userdbfile = 'userfiles/' . $steamprofile['steamid'] . '.txt';
$fhuserdb = fopen($userdbfile, 'a');
//checks that the file was successfully opened
if($fhuserdb) {
fwrite($fhuserdb, $steamprofile['steamid']);
fwrite($fhuserdb, "0");
fclose($fhuserdb);
}
//^ The function is 'fclose()' not 'close()' to close your file
header("Location: index.html");
exit;
Also make sure that the folder does have proper permissions to write to it.
Read the manual:
the file function reads an entire file into an array. The first warning tells you the requested file does not exist
the fopen function expects the first argument to be a string, file returns an array or false on failure. The first argument of fopen should be a string, specifying a path to a file you want to open. It returns a resource (file handle) or false on failure
fwrite expects you to pass a valid file handle, you don't check the return value of fopen (which is false in your case), so you're not writing to an actual file
close does not exist, fclose does, again: this needs to be called on a valid file handle, which you don't have, and thus this line, too, will fail
the header function can only be called if no output has been sent (read the bit below description carefully), your code is generating warnings and errors, which produce output. therefore, it's too late to call header
So what now?
Pas the path you're passing to file to fopen, check its return value and proceed accordingly:
$userdbfile = 'userfiles/' . $steamprofile['steamid'] . '.txt';
$fh = fopen($userdbfile, 'a');
if (!$fh)
{//file could not be opened/created, handle error here
exit();
}
fwrite($fh, $steamprofile['steamid']);
fwrite($fh, '0');
fclose($fh);
header('Location: index.html');
exit();

problem with fopen and fwrite

hi when i execute this code nothing happen in browser but when i delete lines with star,the contents printed correctly,whats wrong??
/////////////////
$documentroot=$_SERVER['DOCUMENT_ROOT'];
$handle=fopen("$documentroot/order/order.txt",'r+');
if(!$handle) {
echo 'error opening file';
}
$content="pepsi\ncola\npeperoni";
$write=fwrite($handle,$content); //*
if(!$write){ //*
echo 'error writing'; //*
} //*
while(!feof($handle)) {
$string=fgets($handle);
echo $string;
}
this line should be like this.
$handle=fopen("$documentroot/order/order.txt",'w');
file should be open in the write mode.try this.
Thanks.
/* This is the opening tag on PHP and it needs to be closed with another */ but the * in front this time. You can stick with // for just one line of commenting.
You are opening the file in r+ mode which means read+write mode. But if the file orders.txt does not exist, it'll not be created. So ensure file exists.
Also when there is problem with opening the file, you immediately exit.
if(!$handle) {
echo 'error opening file';
exit; // MISSING
}
Assuming the file already exists, it's contents will be wiped after the fopen. Next the fwrite will write the contents. Now the file pointer is at the end of the file so your call to feof() in the while loop will return true and the while is never entered.
To fix this you rewind the file pointer before you start reading from the file:
rewind($handle); // ADD THIS
while(!feof($handle)) {
...
}
$documentroot=$_SERVER['DOCUMENT_ROOT'];
$handle=fopen("$documentroot/order/order.txt",'r+');
if(!$handle) {
echo 'error opening file';
}
$content="pepsi\ncola\npeperoni";
$write=fwrite($handle,$content);
if(!$write){
echo 'error writing';
}
fseek($handle, 0);
while(!feof($handle)) {
$string=fgets($handle);
echo $string;
}
After file write operation, your file pointer sets to the end of written data which needs to set to the start position for fgets. fseek does that.
fseek($handle, 0);
This will take your pointer to the beginning so that fgets now can read from file. fgets function needs valid file pointer to read which in this case is the start position.

Categories