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).
Related
I have this file that is already stored in Storage. It's a txt file that contains data lines recorded as show picture below. I get this file using the Storage facade like
$file = Storage::get('public/' . $model->path_to_file);
dd($file); // <- output the picture below
Now I need read each line on this file, but can't figure it out how this must be done. Someone can help me?
I try this code but give me an exception:
$fp = fopen(Storage::path('public/' . $file_path->path_to_file), "r+");
while (($line = stream_get_line($fp, 1024 * 1024, "\n")) !== false) {
echo $line;
}
fclose($fp);
... 580583507 05-08-2021 15:20:09 05-08-2021 15:20:47 Luca RemoteControl {260f5a65-35a4-4b57-bd21-b378f0ab7b82}): failed to open stream: Invalid argument
How this must be solve?
You can use the comand feof (find end of file), so you can do anything you want to inside the loop.
$fp = fopen(Storage::path('public/' . $file_path->path_to_file), "r");
while(!feof($fp)){
$line = fgets($fp);
print_r($line."\n");
}
fclose($fp);
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
I am writing a PHP script so that I can do a find and replace in a large CSV file. I wrote this script:
// FIND AND REPLACE
$sourcePath = 'custom.csv';
$tempPath = $sourcePath . 'temp';
$source = fopen($sourcePath, 'r');
$target = fopen($tempPath, 'w');
while(!feof($source)) {
$line = preg_replace ("village", "village/",fgets($source));
fwrite($target, $line);
}
fclose($source);
fclose($target);
unlink($sourcePath);
rename($tempPath, $sourcePath);
But I am getting these errors,
Warning: feof() expects parameter 1 to be resource, boolean given
Warning: fgets() expects parameter 1 to be resource, boolean given
Warning: preg_replace(): Delimiter must not be alphanumeric or backslash
$source = fopen($sourcePath, 'r'); isn't returning what you think it is.
It's likely returning false, which typically happens when PHP can't find the file at the path you provided. If you're certain the file exists, you should confirm that the user executing the script has the proper permissions to read the file.
You're second issue regarding preg_replace() is being caused by not using delimiters. They are needed in the first argument.
$line = preg_replace ("/village/", "village/",fgets($source));
However, regular expressions aren't needed with this simple of a replacement. You should instead use str_replace() and the script should run faster.
Your code should look like this:
<?php
$sourcePath = 'custom.csv';
$tempPath = $sourcePath . 'temp';
$source = fopen($sourcePath, 'r');
$target = fopen($tempPath, 'w');
if($source){
while(!feof($source)) {
$line = str_replace("Village\\", "Village",fgets($source));
fwrite($target, $line);
}
} else {
echo "$sourcePath not found, or using the wrong permissions.";
}
fclose($source);
fclose($target);
unlink($sourcePath);
rename($tempPath, $sourcePath);
?>
You are not checking if fopen is actually returning a file pointer resource or a false result. It is likely returning false and throwing the warning that a boolean is provided.
Also, you could use:
$line = str_replace("village", "village/", fgets($source));
In this code :
$path = "C:\NucServ\www\vv\static\arrays\news.php";
$fp = fopen($path, "w");
if(fwrite($fp=fopen($path,"w"),$text))
{
echo "ok";
}
fclose($fp);
I have this error message:
failed to open stream: Invalid argument
What is wrong in my code?
Your backslashes is converted into special chars by PHP. For instance, ...arrays\news.php gets turned into
...arrays
ews.php
You should escape them like this:
$path = "C:\\NucServ\\www\\vv\\static\\arrays\\news.php";
Or use singles, like this:
$path = 'C:\NucServ\www\vv\static\arrays\news.php';
Also, your if is messed up. You shouldn't fopen the file again. Just use your $fp which you already have.
path error:
$path = 'C:/NucServ/www/vv/static/arrays/news.php';
file lock:
user file_get_contents replace fopen
I have:
<?php
$file=fopen(date("Y-m-d").".txt","r+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
fwrite($file,$_POST["lastname"]."\n");
}
fclose($file);
?>
but it overwrites the beginning of the file. How do I make it insert?
I'm not entirely sure of your question - do you want to write data and not have it over-write the beginning of an existing file, or write new data to the start of an existing file, keeping the existing content after it?
To insert text without over-writing the beginning of the file, you'll have to open it for appending (a+ rather than r+)
$file=fopen(date("Y-m-d").".txt","a+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
fwrite($file,$_POST["lastname"]."\n");
}
fclose($file);
If you're trying to write to the start of the file, you'll have to read in the file contents (see file_get_contents) first, then write your new string followed by file contents to the output file.
$old_content = file_get_contents($file);
fwrite($file, $new_content."\n".$old_content);
The above approach will work with small files, but you may run into memory limits trying to read a large file in using file_get_conents. In this case, consider using rewind($file), which sets the file position indicator for handle to the beginning of the file stream.
Note when using rewind(), not to open the file with the a (or a+) options, as:
If you have opened the file in append ("a" or "a+") mode, any data you write to the file will always be appended, regardless of the file position.
A working example for inserting in the middle of a file stream without overwriting, and without having to load the whole thing into a variable/memory:
function finsert($handle, $string, $bufferSize = 16384) {
$insertionPoint = ftell($handle);
// Create a temp file to stream into
$tempPath = tempnam(sys_get_temp_dir(), "file-chainer");
$lastPartHandle = fopen($tempPath, "w+");
// Read in everything from the insertion point and forward
while (!feof($handle)) {
fwrite($lastPartHandle, fread($handle, $bufferSize), $bufferSize);
}
// Rewind to the insertion point
fseek($handle, $insertionPoint);
// Rewind the temporary stream
rewind($lastPartHandle);
// Write back everything starting with the string to insert
fwrite($handle, $string);
while (!feof($lastPartHandle)) {
fwrite($handle, fread($lastPartHandle, $bufferSize), $bufferSize);
}
// Close the last part handle and delete it
fclose($lastPartHandle);
unlink($tempPath);
// Re-set pointer
fseek($handle, $insertionPoint + strlen($string));
}
$handle = fopen("file.txt", "w+");
fwrite($handle, "foobar");
rewind($handle);
finsert($handle, "baz");
// File stream is now: bazfoobar
Composer lib for it can be found here
You get the same opening the file for appending
<?php
$file=fopen(date("Y-m-d").".txt","a+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
fwrite($file,$_POST["lastname"]."\n");
}
fclose($file);
?>
If you want to put your text at the beginning of the file, you'd have to read the file contents first like:
<?php
$file=fopen(date("Y-m-d").".txt","r+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
$existingText = file_get_contents($file);
fwrite($file, $existingText . $_POST["lastname"]."\n");
}
fclose($file);
?>