Task: Cut or erase a file after first walk-through.
i have an install file called "index.php" which creates another php file.
<?
/* here some code*/
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "<?php \n
echo 'hallo, *very very long text*'; \n
?>";
fwrite($fh, $stringData);
/*herecut"/
/*here some code */
after the creation of the new file this file is called and i intent to erase the
filecreation call since it is very long and only needed on first install.
i therefor add to the above code
echo 'hallo, *very very long text*'; \n
***$new= file_get_contents('index.php'); \n
$findme = 'habanot';
$pos = strpos($new, $findme);
if ($pos === false) {
$marker='herecut';\n
$new=strstr($new,$marker);\n
$new='<?php \n /*habanot*/\n'.$new;\n
$fh = fopen('index.php', 'w') or die 'cant open file');
$stringData = $new;
fwrite($fh, $stringData);
fclose($fh);***
?>";
fwrite($fh, $stringData);]}
Isnt there an easier way or a function to modify the current file or even "self destroy" a file after first call?
Regards
EDIT: found the way to edit, sorry to zaf
unlink(__FILE__);
can be used to delete the "helper file" after execution.
unlink(__FILE__);
for the "helper" file seems necessary since i cant find a way to modify the php-file inuse/process.
Most self-installing PHP sites use an install.php to perform the initial set-up. When the install is verified, you would redirect to removeinstall.php which would call unlink() on each installation file to clear them all out.
This does leave behind the removeinstall.php, but has the benefit of not polluting any of the "live code" with installation removal code.
removeinstall.php would simply contain the unlink statements...
if (file_exists('install.php')) {
unlink('install.php');
}
If you don't want to leave behind the removeinstall.php, you could have a conditional call in a different file... for example index.php?removeinstallation=1 or similar.
Related
I have bunch of images file (.jpg) in a folder, then I want to list them to a single file text, I using php (xampp in windows).
This for list images name in my browser (it's working):
<?php
ob_start();
$file='F:\images\upload\google\ready_45';
foreach (glob($file."\*.jpg") as $filenames) {
echo $filenames."<br />";
}
?>
This for create text file called 'images_list.txt' (not working):
<?php
ob_start();
$file='F:\images\upload\google\ready_45';
foreach (glob($file."\*.jpg") as $filenames) {
$my_file = 'image_list.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file);
$data = echo $filenames."<br />";
fwrite($handle, $data);
}
?>
When I execute that script, appear warning message
"
Parse error: syntax error, unexpected 'echo' (T_ECHO) in D:\xampp\htdocs\rename_file_php\try_list_img.php on line 7"
If line 7, I change
$data = $filenames;
The file 'images_list.txt' will created, but only fill one image name listing in the file. Can anyone help me?
Sorry for my bad english.
Open file once and try to write data once:-
<?php
ob_start();
$file='F:\images\upload\google\ready_45';
$data = '';
foreach (glob($file."\*.jpg") as $filenames) {
$data .= $filenames."\n";
}
$my_file = 'image_list.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file);
fwrite($handle, $data);
fclose($handle);
?>
You want to fopen() the file only once, so outside the loop. Otherwise you overwrite the content again and again. Take a look at this modified version:
<?php
$folder = 'F://images/upload/google/ready_45';
$my_file = 'image_list.txt';
$handle = fopen($my_file, 'w') or die("Cannot open file: ". $my_file);
foreach (glob($folder . "/*.jpg") as $filename) {
$data = $filename . PHP_EOL;
fwrite($handle, $data);
}
fclose($handle);
One certainly could simplify that. For example by simply imploding the list of matched file names with a linebreak and then writing the result in one go:
<?php
$folder = 'F://images/upload/google/ready_45';
$data = implode(PHP_EOL, glob($folder . "/*.jpg"));
$my_file = 'image_list.txt';
$handle = fopen($my_file, 'w') or die("Cannot open file: ". $my_file);
fwrite($handle, $data);
fclose($handle);
However the first (loop based) approach allows more flexibility, for example filtering or escaping.
Side notes:
using a normal slash as folder delimiter (/) instead of the insane backslash (\\) natively used in MS-Windows will save you a lot of hassle. PHP can work with both on a MS-Windows platform.
using a line break instead of the html linewrap makes more sense when writing into a file in most cases. Using PHP_EOL instead of a hard coded line break (\r\n) will make your code portable for systems using different types of line breaks (only MS-Windows uses \r\n for that).
I took the liberty to also fix some indentation and code styling issues. It definitely makes sense if programmers loosely agree on some standard to enhance readability of code.
This is all you need:
// Creates a newline separated list from the array returned by glob()
$files = glob ($folder.'/*.jpg');
$files = implode (PHP_EOL, $files);
∕∕ This is all that is needed to write something to a file.
file_put_contents ($my_file, $files);
The fopen() and all that is old, old code, which should be avoided whenever possible. Not only is this method simpler and easier to read, but it's also generally faster.
Note that you might want to wrap an IF statement around the last line, in order to handle any errors with writing that might crop up.
Following code is working fine, I have a images folder which is having some image files, please change the folder path and try the below code
<?php
ob_start();
$file='images';
foreach (glob($file."\*.jpg") as $filenames) {
$my_file = 'image_list.txt';
$handle = fopen($my_file, 'a') or die('Cannot open file: '.$my_file);
$data = $filenames."\r\n";
fwrite($handle, $data);
}
?>
I'm trying to create a script which will check if a file is writable before writing to it,
Making sure the script doesn't exit prematurely.
I've gotten this far
$meta =stream_get_meta_data($file);
while(!is_writable($meta['uri'])){
sleep(rand(0,3));
$meta=stream_get_meta_data($file);
echo("sleeping\n");
}
$csv = fopen($file, 'a+')or die("can't open file");
When I test the script with $file open, it blocks on the sleeping part even after $file is closed.
I'm fairly new to PHP, so there might be a processing paradigm that i'm not aware of.
Any help would be very welcome.
EDIT : The reason I entered this into a while loop is to continually check if the file is open or not. Hence it should only exit the while loop once the file is finally writable.
The sleep is simply to replicate a person trying to open the file.
its is_writable ( string $filename )
$filename = 'test.txt';
if (is_writable($meta['uri']) {
echo 'The file is writable';
} else {
echo 'The file is not writable';
}
is_writable(<your_file>)
This should do the trick?
http://www.php.net/manual/en/function.is-writable.php
--
Also you can use
#fopen(<your_file>, 'a')
If this returns false, file is not writiable
Using touch():
if (touch($file_name) === FALSE) {
throw new Exception('File not writable');
}
You probably should not be using a while loop just to check if the file is writable. Maybe change your code around a bit to something like this:
$meta =stream_get_meta_data($file);
if (is_writable($file)){
sleep(rand(0,3));
$meta=stream_get_meta_data($file);
echo("sleeping\n");
}
$csv = fopen($file, 'a+')or die("can't open file");
However since I do not know what your main goal is you could do it like this:
$meta =stream_get_meta_data($file);
while(!is_writable($file)){
sleep(rand(0,3));
$meta=stream_get_meta_data($file);
echo("sleeping\n");
}
$csv = fopen($file, 'a+')or die("can't open file");
I have this issue, I would like to create a new file, with another name.
For now I have the file CLPRE.txt opened and saving the changes in the same file, I would like to create a new file from the original one like this
pseudo-code:
$unique= sha1( uniqid(phc) );
$newFile = $unique.CLPRE.txt
The actual code is resumed with this:
$myFile = $loja."/CL.xml";
$fh = fopen($myFile, 'w') or die("can't open");
$pre= file_get_contents('CLPRE.txt');
$writeThis = "some text";
fwrite($fh, $pre.$writeThis);
fclose($fh);
use file_put_contents
This function is identical to calling fopen(), fwrite() and fclose()
successively to write data to a file.
If filename does not exist, the file is created. Otherwise, the
existing file is overwritten, unless the FILE_APPEND flag is set.
Umm you're basically doing it already, you just need to do another call and create it via:
$new = fopen($unique.'CLPRE.txt', 'w') or die("can't open");
then add what you want into it, and close with:
fwrite($new , $pre.$writeThis);
fclose($new );
Reference to fopen() - http://www.decompile.com/cpp/faq/fopen_write_append.htm
I have a PHP generated page containing the results of a submitted form, what I would like to do is save this as a .doc file on the server.
After some googling I came across this code which I adapted:-
$myFile = "./dump/".$companyName."/testFile.doc";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Bobby Bopper\n";
fwrite($fh, $stringData);
$stringData = "Tracy Tanner\n";
fwrite($fh, $stringData);
fclose($fh);
But the problem with this is that I would have to recreate the results in order to manually write them to the file and it doesn't seem very efficient.
So I continued to google and found the PHP manual which left me scratching my head frankly, however I eventually found this:-
ob_start();
// code to generate page.
$out = ob_get_contents();
ob_end_clean();
// or write it to a file.
file_put_contents("./dump/".$companyName."/testFile.doc",$out);
Which will create the file, but doesn't write anything to it. However this seems to be the way to do what (Based on the PHP manual) I want even if I can't get it to work!
Any advice? I don't mind googling if I can figure out a decent search term :)
This sould do it for you:
$cache = 'path/to/your/file';
ob_start();
// your content goes here...
echo "hello !"; // would put hello into your file
$page = ob_get_contents();
ob_end_clean();
$fd = fopen("$cache", "w");
if ($fd) {
fwrite($fd,$page);
fclose($fd);
}
It's also a great way to cache dynamic pages. Hope it helps.
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);
?>