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));
Related
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).
I am very new to php, and i have search and put together this script to convert text to csv and write the out put on the file.
$File = "/var/apache2/htdocs/loginS/host.txt";
$Handle = fopen($File,"r");
$Content = fread ($Handle,filesize ($File));
fclose($File);
fclose($Handle);
$Content = explode("\t", $Content);
foreach($Content as $Value) {
//echo $Value."|"; // till this line working
fwrite($save, $Value);
fclose($save);
}
the problem is when I try to write on the file. I got only one line.what is my error.
You are calling fclose() on the file in your loop that is writing records. fclose() closes the file handle so it is no longer valid and cannot be written to.
Move fclose($save); after the } that ends the foreach() with your content.
Also, you could simplify things a bit by calling $Content = file_get_contents($File); since that is what you are doing in effect with fread(). Also, since $File is just a string variable, calling fclose() on it is unnecessary and doesn't do anything. You were correctly closing it by calling fclose() on $Handle. But using file_get_contents() will eliminate the need for both. The only file you would need is the one you were writing to.
Here is an example using the file() function which reads each line of a file into an array.
$file = '/var/apache2/htdocs/loginS/host.txt';
$content = file($file);
$save = fopen('./out.csv', 'w+');
foreach($content as $line) {
$line = rtrim($line, "\r\n"); // remove the newline from $line
$parts = explode("\t", $line);
$lineCsv = implode('|', $parts); // or ',' ?
fwrite($save, $lineCsv . "\n"); // write output to file
}
fclose($save);
I'm trying to define an array with a list of file urls, and then have each file parsed and if a predefined string is found, for that string to be replaced. For some reason what I have isn't working, I'm not sure what's incorrect:
<?php
$htF = array('/home/folder/file.extension', '/home/folder/file.extension', '/home/folder/file.extension', '/home/folder/file.extension', '/home/folder/file.extension');
function update() {
global $htF;
$handle = fopen($htF, "r");
if ($handle) {
$previous_line = $content = '';
while (!feof($handle)) {
$current_line = fgets($handle);
if(stripos($previous_line,'PREDEFINED SENTENCE') !== FALSE)
{
$output = shell_exec('URL.COM');
if(preg_match('#([0-9]{1,3}\.){3}[0-9]{1,3}#',$output,$matches))
{
$content .= 'PREDEFINED SENTENCE '.$matches[0]."\n";
}
}else{
$content .= $current_line;
}
$previous_line = $current_line;
}
fclose($handle);
$tempFile = tempnam('/tmp','allow_');
$fp = fopen($tempFile, 'w');
fwrite($fp, $content);
fclose($fp);
rename($tempFile,$htF);
chown($htF,'admin');
chmod($htF,'0644');
}
}
array_walk($htF, 'update');
?>
Any help would be massively appreciated!
Do you have permissions to open the file?
Do you have permissions to write to /tmp ?
Do you have permissions to write to the destination file or folder?
Do you have permissions to chown?
Have you checked your regex? Try something like http://regexpal.com/ to see if it's valid.
Try adding error messages or throw Exceptions for all of the fail conditions for these.
there's this line:
if(stripos($previous_line,'PREDEFINED SENTENCE') !== FALSE)
and I think you just want a != in there. Yes?
You're using $htF within the update function as global, which means you're trying to fopen() an array.
$fh = fopen($htF, 'r');
is going to get parsed as
$fh = fopen('Array', 'r');
and return false, unless you happen to have a file named 'Array'.
You've also not specified any parameters for your function, so array_walk cannot pass in the array element it's dealing with at the time.
Hey everyone, I have written a script that downloads a zip file from a remote source, and then is supposed to extract the zip file to a directory. Below is the script:
<?php
$url = "http://example.com/some_file.zip";
download($url,'file.zip');
function download($url,$file_name = NULL){
if($file_name == NULL){ $file_name = basename($url);}
$url_stuff = parse_url($url);
$port = isset($url_stuff['port']) ? $url_stuff['port'] : 80;
$fp = fsockopen($url_stuff['host'], $port);
if(!$fp){ return false;}
$query = 'GET ' . $url_stuff['path'] . " HTTP/1.0\n";
$query .= 'Host: ' . $url_stuff['host'];
$query .= "\n\n";
fwrite($fp, $query);
while ($tmp = fread($fp, 8192)) {
$buffer .= $tmp;
}
preg_match('/Content-Length: ([0-9]+)/', $buffer, $parts);
$file_binary = substr($buffer, - $parts[1]);
if($file_name == NULL){
$temp = explode(".",$url);
$file_name = $temp[count($temp)-1];
}
if(!file_exists("packages")){ mkdir("packages", 0755);}
$file_open = fopen("packages/" . $file_name,'w');
if(!$file_open){ return false;}
fwrite($file_open,$file_binary);
$zip = zip_open(realpath("packages")."/".$file_name);
if ($zip) {
while ($zip_entry = zip_read($zip)) {
$fp = fopen("some_dir/".zip_entry_name($zip_entry), "w");
if(zip_entry_open($zip, $zip_entry, "r")) {
$buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
fwrite($fp,"$buf");
zip_entry_close($zip_entry);
fclose($fp);
}
}
zip_close($zip);
}
fclose($file_open);
return true;
}
?>
The issue that I have is that while the downloading of the remote file works flawlessly, I can't seem to extract it. The zip_read() and zip_close() return errors saying that it "expects parameter 1 to be resource, integer given...", which I have found means that the zip_open() was unable to extract and is returning an error code, which I have found to be "19" meaning "Zip File Function error: Not a zip archive". However, I know the file I am downloading is, in fact, a zip file. Can anyone explain this odd behavior and provide a fix? It would be much appreciated!
Quoting php.net: "zip_open() ... Returns a resource handle for later use with zip_read() and zip_close() or returns the number of error if filename does not exist or in case of other error."
This means you cannot test if ($zip) like that. Try
if ( is_resource($zip) ) {
// stuff
} else {
print "Zip_open() returned error $zip\n";
}
edit: Apart from that, you need to cut the response in 2 parts properly. You are relying heavily on the Content-Length parameter. You don't check if the preg_match actually matched. A lot of things can go wrong and you should check those things. Try splitting the content on the first empty line (explode on \r\n\r\n or something like that)
Besides the fread() loop should check for feof(), since you would stop reading now if for some reason you would encounter an empty read. Copy&paste from php.net:
while (!feof($handle)) {
$contents .= fread($handle, 8192);
}
But we can go on and on here. Three main points have to be made:
read the fantastic manual (php.net)
check return values
don't assume you know things you don't
those are related: you must lookup the manual to see what return values you might encounter.
The file that I'm trying to read is a pgp-encrypted file. This is part of the process to decrypt it and I'm actually attempting to read the contents into a string so that I can then decrypt it. I'm not sure if that's the core problem here or not, but I'm getting an error:
Warning: feof(): supplied argument is not a valid stream resource
Here's the file code:
if($handle = opendir($dir)) {
while( false !== ($file = readdir($handle))) {
if($file != "." && $file != "..") {
$fhandle = fopen($file, "r");
$encrypted = '';
$filename = explode('.',$file);
while(!feof($fhandle)) {
$encrypted .= fread($fhandle, filesize($file));
}
fclose($fhandle);
$decrypted = $filename[0].'.txt';
shell_exec("echo $passphrase | $gpg --passphrase-fd 0 -o $decrypted -d $encrypted");
}
}
}
Learn to debug your code.
supplied argument is not a valid stream resource means passed variable contains unexpected value. So, we can make a logical conclusion, that a function returning this variable had fail.
So. we have to check fopen($file, "r"); what makes it fail? may be we can check if a file exists? And so on.
This is called debugging and you cannot program without it.
Though it seems very strange.
Because fopen should throw an error as well.
You should check the fopen call to make sure you're file has actually been opened. Check it's return value.
As for fixing it you're working directory is likely different than $dir. You probably need
fopen("$dir/$file","r");
unless you change to the directory first.
edit clarified that the code sample was a possible solution to the problem, not code to check the return value.
You need to check your return values. The error indicates that $fhandle doesn't contain a valid file handle - it probably contains false, which fopen returns on failure.
See http://ca.php.net/manual/en/function.fopen.php