I've got a php problem.
I've got a php file that reads data from a .txt file.
This works, with this code:
$filename= "deadlines.txt";
$fp = fopen($filename,"r");
$content = fread($fp, filesize($filename));
$rawArray = setRawArray($content);
$epochAndTitleArray = toEpoch($rawArray);
Now, I want to make it so that this stuff is executed every second, not just once at the start.
So, I tried to fit it into a function, like this:
$filename= "deadlines.txt";
$fp = 0;
$content = 0;
$rawArray = 0;
$epochAndTitleArray = 0;
function readFile(){
$GLOBALS['fp'] = fopen($GLOBALS['filename'], "r");
$GLOBALS['content'] = fread($GLOBALS['fp'], filesize($GLOBALS['filename']));
$GLOBALS['rawArray'] = setRawArray($GLOBALS['content']);
$GLOBALS['epochAndTitleArray'] = toEpoch($GLOBALS['rawArray']);
}
In this case I'm working with globals, before, I did it without, and also left out the lines before the function itself. This was incorrect I think, so I added the globals.
Now, this doesn't work.
It gives me the following error:
Fatal error: Cannot redeclare readFile() in .....on line 28,
this line 28 is the line of the closing } at the end of the function.
Can you guys help me in completing this task?
Thanks already!
readfile is a defined function in php , you cannot redeclare it or redeclare any function using the same name .
for more reference about how to declare valid functions in php
PHP does not support function overloading, nor is it possible to
undefine or redefine previously-declared functions.
Rename 'readFile' to another, readfile() is predefined function 'http://php.net/manual/kr/function.readfile.php'
Related
I'm creating a library and I want to test a system that asks the user by input in the console. I use PHPUnit as a testing library but and I don't know how to execute readline function and then print a text to answer the input to test it.
Here it is my test:
$app = new Application;
$i = null;
$app->registerCommand('test', function(Input $input) use(&$i){
// $input->getInput() asks the user and returns the value
$i = $input->getInput();
});
$this->expectOutputString("\n");
// Run the application, so asks the user to enter a value
$app->run();
// Here, I want force to enter a value by the code
$this->assertSame($i, 'test');
I've tested to replace readline by fgets(STDIN) but without results. I thought to solve the problem with asynchronous callables but I need guide for good libraries to use.
Here it is differents ways I've tested in getInput function:
return readline();
return trim(fgets(STDIN));
Thank for your help.
Try replacing the use of read line or some 3rd party prompt command with your own function and use the following:
You can read keyboard input manually in php with this:
$fp = fopen("php://stdin", "r");
$input = rtrim(fgets($fp, 1024));
Note the string with std input used as the input stream.
And then when testing replace the input stream with a file like so
$fp = fopen(__DIR__ . '/../test/test_input', "r");
$input = rtrim(fgets($fp, 1024));
This time it will read a single line from the file instead.
Obviously you will have to make a function and some way to swap the input stream string during testing but the above is all you need to get it working.
Here is a working unit test:
class PromptTest extends TestCase
{
public function testPrompt()
{
$fp = fopen(__DIR__ . '/../test/test_input', "r");
$rtrim = rtrim(fgets($fp, 1024));
self::assertEquals('first line of file', $rtrim);
}
}
This produced
OK (1 test, 1 assertion)
ALso found here: Is there a way to access a string as a filehandle in php?
that a string input can be used.
I use PHP app in Google appengine,
I'm trying to read a input file and write it to an output file in Storage bucket like below.
$input_file = fopen('gs://mybucket/input.csv','r');
$output_file = fopen('gs://mybucket/output.csv', 'w');
And trying to write some date like
while(!feof($input_file)) {
$csv = fgetcsv($input_file,1024);
if(!$csv[0]){
fclose($output_file); //Close the connection when the loop ends
fclose($input_file);
exit(0);
}
fwrite($output_file, $csv[0]."\r\n");
}
It works perfectly, When i try to upload some data in to input file and it successfully write in to output.csv as well. but if i try more than 5 or 6th time it starts to throw an error in appengine logs like below. Any help to troubleshoot this issue will be highly appreciated!
2015-04-08 21:31:29.006 PHP Fatal error: Undefined class constant 'WRITE_SCOPE' in /base/data/home/runtimes/php/sdk/google/appengine/ext/cloud_storage_streams/CloudStorageWriteClient.php on line 214
Update:
I think this is because of opening 2 file streams at same time,
Did some work around and solved this!
$input_file = fopen('gs://mybucket/input.csv','r');
$array_acc = array();
while(!feof($input_file)) {
$csv = fgetcsv($input_file, 1024);
if($csv[0]) array_push($array_acc, $csv[0]);
}
fclose($input_file); //close the file
$acc_count = count($array_acc);
$output_file = fopen('gs://tool-synclio/output.csv','w'); // Open the output file now
while($acc_count > 0){
fwrite($output_file,$array_acc[$acc_count]."\r\n");
$acc_count --;
}
fclose($output_file);
But, I'm still waiting for some one to give better solution.
You have 2 dollar signs in a variable:
fwrite($output_file, $$csv[0]."\r\n");
This question already has answers here:
Need to write at beginning of file with PHP
(10 answers)
Closed 9 years ago.
Hi I want to append a row at the beginning of the file using php.
Lets say for example the file is containing the following contnet:
Hello Stack Overflow, you are really helping me a lot.
And now i Want to add a row on top of the repvious one like this:
www.stackoverflow.com
Hello Stack Overflow, you are really helping me a lot.
This is the code that I am having at the moment in a script.
$fp = fopen($file, 'a+') or die("can't open file");
$theOldData = fread($fp, filesize($file));
fclose($fp);
$fp = fopen($file, 'w+') or die("can't open file");
$toBeWriteToFile = $insertNewRow.$theOldData;
fwrite($fp, $toBeWriteToFile);
fclose($fp);
I want some optimal solution for it, as I am using it in a php script. Here are some solutions i found on here:
Need to write at beginning of file with PHP
which says the following to append at the beginning:
<?php
$file_data = "Stuff you want to add\n";
$file_data .= file_get_contents('database.txt');
file_put_contents('database.txt', $file_data);
?>
And other one here:
Using php, how to insert text without overwriting to the beginning of a text file
says the following:
$old_content = file_get_contents($file);
fwrite($file, $new_content."\n".$old_content);
So my final question is, which is the best method to use (I mean optimal) among all the above methods. Is there any better possibly than above?
Looking for your thoughts on this!!!.
function file_prepend ($string, $filename) {
$fileContent = file_get_contents ($filename);
file_put_contents ($filename, $string . "\n" . $fileContent);
}
usage :
file_prepend("couldn't connect to the database", 'database.logs');
My personal preference when writing to a file is to use file_put_contents
From the manual:
This function is identical to calling fopen(), fwrite() and fclose()
successively to write data to a file.
Because the function automatically handles those three functions for me I do not have to remember to close the resource after I'm done with it.
There is no really efficient way to write before the first line in a file. Both solutions mentioned in your questions create a new file from copying everything from the old one then write new data (and there is no much difference between the two methods).
If you are really after efficiency, ie avoiding the whole copy of the existing file, and you need to have the last inserted line being the first in the file, it all depends how you plan on using the file after it is created.
three files
Per you comment, you could create three files header, content and footer and output each of them in sequence ; that would avoid the copy even if header is created after content.
work reverse in one file
This method puts the file in memory (array).
Since you know you create the content before the header, always write lines in reverse order, footer, content, then header:
function write_reverse($lines, $file) { // $lines is an array
for($i=count($lines)-1 ; $i>=0 ; $i--) fwrite($file, $lines[$i]);
}
then you call write_reverse() first with footer, then content and finally header. Each time you want to add something at the beginning of the file, just write at the end...
Then to read the file for output
$lines = array();
while (($line = fgets($file)) !== false) $lines[] = $line;
// then print from last one
for ($i=count($lines)-1 ; $i>=0 ; $i--) echo $lines[$i];
Then there is another consideration: could you avoid using files at all - eg via PHP APC
You mean prepending. I suggest you read the line and replace it with next line without losing data.
<?php
$dataToBeAdded = "www.stackoverflow.com";
$file = "database.txt";
$handle = fopen($file, "r+");
$final_length = filesize($file) + strlen($dataToBeAdded );
$existingData = fread($handle, strlen($dataToBeAdded ));
rewind($handle);
$i = 1;
while (ftell($handle) < $final_length)
{
fwrite($handle, $dataToBeAdded );
$dataToBeAdded = $existingData ;
$existingData = fread($handle, strlen($dataToBeAdded ));
fseek($handle, $i * strlen($dataToBeAdded ));
$i++;
}
?>
I have an array that I want to write to a CSV file and tried the fputcsv function following the example on the manual.
However I am getting the error "Fatal error: Call to undefined function fputcsv()"
$csv = array();
foreach($compare as $ukvalue)
{
$csv[] = array($ukvalue, $uk[$ukvalue]);
}
$fp = fopen("lang.csv", "w");
foreach ($csv as $fields)
{
fputcsv($fp,explode(',', $fields));
}
fclose($fp);
Can anyone shed some light on this issue or is there an alternative to fputcsv I can try?
As per the docs at http://www.php.net/manual/en/function.fputcsv.php the function putcsv is available only for PHP 5.1.0 or later
Which version oh PHP are you running?
Also, you should not explode the fields, in fact the expected second parameter should be an array.
This one is a bit of a weird one. Ive created a function designed to select a template and either include it or parse the %0, %1,%3 etc. variables. This is the current function:
if(!fopen($tf,"r")){
$this->template("error",array("404"));
}
$th = fopen($tf,"r");
$t = fread($th, filesize($tf) );
$i=0;
for($i;$i<count($params);$i++){
$i2 = '%' . $i;
$t = str_replace($i2,$params[$i],$t);
}
echo $t . "\n";
fclose($th);
Where $th is the relative directory to my template file. My issue is, I need to execute the PHP inside of these files whilst at the same tme being able to replace the string variables %0 %1 etc.
How could I go about attempting this?
Like I said in my comment I think a template engine like Smarty would probably serve you better but here's how I'd do it with output buffering rather than eval()
Something like this
ob_start();
include "your_template_file.php";
$contents = ob_get_contents(); // will contain the output of the PHP in the file
ob_end_clean();
// process your str_replace() variables out of $contents