<?
$file = ("file*");
$fp = fopen($file, 'a') or die("can't open file");
fwrite($fp, "testing");
fclose($fp);
?>
I want "testing" to be written to a file called file2.txt, but it instead writes to file*. I know that i can just set $file to "file2.txt", but this is just hypothetical.
I don't believe that globbing works the way you have it listed here. You could use the glob() function, which returns an array of matched filenames:
array = glob("file*")
I wouldn't recommend doing this, of course, because it's often hard to know that you'll only have a single file called file2.txt in the directory. If you do know that, it's better to specify explicitly, rather than using globbing.
That said, if you wanted to do things this way, that's how I would do it.
Related
I have the contents of a file in a string. I need to pass this file to a function where the function is expecting the parameter to be the name of the file, not the contents. The obvious and probably simplest way to do this would be to write the contents to a temp file, then pass that file name to the function, and unlink the file once I'm finished.
However, I'm looking for a solution that doesn't involve writing the file out to the file system and then reading it back in. I've had a need for this in multiple cases, so I'm not looking for a work-around to a specific function, but more of a generic method that will work for any function expecting a file name (like file_get_contents(), for instance).
Here are some thoughts, but not sure how to pursue these yet:
Is it possible to write the contents somewhere in memory, and then
pass that to the function as a filename? Perhaps something using
php://memory.
Is it possible to write the contents to a pipe, then pass the name of the
pipe to the function?
I did a short proof-of-concept trying with php://memory as follows, but no luck:
$data = "This is some file data.\n";
file_put_contents( 'php://memory', $data );
echo file_get_contents( 'php://memory' );
Would be interested in knowing of good ways to address this. Googling hasn't come up with anything for me.
It mainly depends on what the target function does with the file name. If you're lucky, you can register your own stream wrapper:
stream_wrapper_register('demo', 'DemoStream');
$data = "This is some file data.\n";
$filename = 'demo://foo';
file_put_contents($filename, $data );
echo file_get_contents($filename);
Why not use a file in the /tmp/ directory? Like this:
<?php
$filename = '/tmp/mytmpfile';
$data = "This is some file.\n";
file_put_contents($filename, $data);
$result = file_get_contents($filename);
var_dump($result);
Well, as you say you don't want to use a file, you shouldn't use file_get_contents().
But you can achieve the same result by using stream_get_contents(), like this:
<?php
$data = "This is some file data.\n";
$handle = fopen('php://memory', 'r+'); // open an r/w handle to memory
fputs($handle, $data); // write the data
rewind($handle); // rewind the pointer
echo stream_get_contents($handle); // retrieve the contents
I know you can create a temporary file with tmpfile and than write to it, and close it when it is not needed anymore. But the problem I have is that I need the absolute path to the file like this:
"/var/www/html/lolo/myfile.xml"
Can I somehow get the path, even with some other function or trick?
EDIT:
I want to be able to download the file from the database, but without
$fh = fopen("/var/www/html/myfile.xml", 'w') or die("no no");
fwrite($fh, $fileData);
fclose($fh);
because if I do it like this, there is a chance of overlapping, if more people try to download the same file at exactly the same time. Or am I wrong?
EDIT2:
Maybe I can just generate unique(uniqID) filenames like that, and than delete them. Or can this be too consuming for the server if many people are downloading?
There are many ways you can achieve this, here is one
<?php
// Create a temp file in the temporary
// files directory using sys_get_temp_dir()
$temp_file = tempnam(sys_get_temp_dir(), 'MyFileName');
echo $temp_file;
?>
The above example will output something similar to:
/var/tmp/MyFileNameX322.tmp
I know you can create a temporary file with tmpfile
That is a good start, something like this will do:
$fileHandleResource = tmpfile();
Can I somehow get the path, even with some other function or trick?
Yes:
$metaData = stream_get_meta_data($fileHandleResource);
$filepath = $metaData['uri'];
This approach has the benefit of leaving it up to PHP to pick a good place and name for this temporary file, which could end up being a good thing or a bad thing depending on your needs. But it is the simplest way to do this if you don't yet have a specific reason to pick your own directory and filename.
References:
http://us.php.net/manual/en/function.stream-get-meta-data.php
Getting filename (or deleting file) using file handle
This will give you the directory. I guess after that you are on your own.
For newer (not very new lol) versions of PHP (requires php 5.2.1 or higher) #whik's answer is better suited:
<?php
// Create a temp file in the temporary
// files directory using sys_get_temp_dir()
$temp_file = tempnam(sys_get_temp_dir(), 'MyFileName');
echo $temp_file;
?>
The above example will output something similar to: /var/tmp/MyFileNameX322.tmp
old answer
Just in case someone encounters exactly the same problem. I ended up doing
$fh = fopen($filepath, 'w') or die("Can't open file $name for writing temporary stuff.");
fwrite($fh, $fileData);
fclose($fh);
and
unlink($filepath);
at the end when file is not needed anymore.
Before that, I generated filename like that:
$r = rand();
$filepath = "/var/www/html/someDirectory/$name.$r.xml";
I just generated a temporary file, deleted it, and created a folder with the same name
$tempFolder = tempnam(sys_get_temp_dir(), 'MyFileName');
unlink($tempFolder);
mkdir($tempFolder);
I'm using this code below that simply takes the name of an artist submitted through a form and saves it as a html file on the server.
<?php
if (isset($_GET['artist'])) {
$fileName = $_GET['artist'].".html";
$fileHandler = fopen($fileName, 'w') or die("can't create file");
fclose($fileHandler);
}
?>
What I'm trying to work out is how I could possibly add any code within the file before it is saved. That way every time a user adds an artist I can include my template code within the file. Any help would be great :)
Use fwrite.
Two things:
file_put_contents as a whole will be faster.
Your design is a very bad idea. They can inject a file anywhere on your filesystem, e.g. artist=../../../../etc/passwd%00 would try to write to /etc/passwd (%00 is a NUL byte, which causes fopen to terminate the string in C - unless that's been fixed).
fwrite() allows you to write text to the file.
if (isset($_GET['artist'])) {
$fileName = $_GET['artist'].".html";
$fileHandler = fopen($fileName, 'w') or die("can't create file");
fwrite($fileHandler, 'your content goes here');
fclose($fileHandler);
}
Warning - be very careful about what you write to the filesystem. In your example there is nothing stopping someone from writing to parts of the filesystem that you would never have expected (eg. artist='../index'!).
I sincerely recommend that you think twice about this, and either save content to a database (using appropriate best practices, ie http://php.net/manual/en/security.database.sql-injection.php) or at least make sure that you limit the characters used in the filename strings (eg. only allow characters A-Z or a-z and '_', for example). It's dangerous and exploitable otherwise, and at the very least you run the risk of your site being defaced or abused.
As others have said - you should be able to write php code to the filesystem with fwrite.
I have this content on 'test.txt' file: lucas
I want to seek pointer in the file and override info ahead. Supposed I do:
$f = new SplFileObject('test.txt', 'a');
$f->fseek(-5, SEEK_END);
var_dump($f->ftell());
$f->fwrite('one');
This should produce: oneas But the result of execution: lucasone
I'm crazy about the code logic or even doesn't works?
How is the right way to do what I want?
You opened the file for appending:
$f = new SplFileObject('test.txt', 'a');
which means you cannot seek in the file. Instead, open it for reading and writing:
$f = new SplFileObject('test.txt', 'r+');
They also say it in the fseek documentation:
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, and the result of calling fseek() will be undefined.
I want to create a file on the webserver dynamically in PHP.
First I create a directory to store the file. THIS WORKS
// create the users directory and index page
$dirToCreate = "..".$_SESSION['s_USER_URL'];
mkdir($dirToCreate, 0777, TRUE); // create the directory for the user
Now I want to create a file called index.php and write out some content into it.
I am trying:
$ourFileName = $_SESSION['s_USER_URL']."/"."index.php";
$ourFileHandle = fopen($ourFileName, 'x') or die("can't open file");
fclose($ourFileHandle);
// append data to it
$ourFileHandle = fopen($ourFileName, 'a') or die("can't write to file");
$stringData = "Hi";
fwrite($ourFileHandle, $stringData);
But it never gets past the $ourFileHandle = fopen($ourFileName, 'x') or die("can't open file"); Saying the file does not exist, but that is the point. I want to create it.
I did some echoing and the path (/people/jason) exists and I am trying to write to /people/jason/index.php
Does anyone have any thoughts on what I am doing wrong?
PHP 5 on a linux server I believe.
-Jason
First you do :
$dirToCreate = "..".$_SESSION['s_USER_URL'];
But the filename you try to write to is not prefixed with the '..', so try changing
$ourFileName = $_SESSION['s_USER_URL']."/"."index.php";
to
$ourFileName = '..' . $_SESSION['s_USER_URL'] . '/index.php';
or probably tidier:
$ourFileName = $dirToCreate . '/index.php';
You are probably getting the warning because the directory you are trying to write the file into does not exist
It could be a result of one of your php ini settings, or possibly an apache security setting.
Try creating the dir as only rwxr-x--- and see how that goes.
I recall a shared hosting setup where "safemode" was compiled in and this behaviour tended to occur, basically, if the files/dirs were writable by too many people they would magically stop being acessible.
Its probably doc'd in php, but ill have to check.
why not use:
file_put_contents( $filename, $content )
or you could touch the file before writing to it.
Does the file 'index.php' already exist? When you fopen with the 'x' mode, if the file exists fopen will return FALSE and trigger a warning.
What i first noticed is you are making a directory higher in the tree, then attempting to make the php file in the current folder. Correct me if i'm wrong, but aren't you trying to make the file in the new created folder? if i recall php correctly (pardon me it's been a while, i'll probably add something from another language in here not noticing) here is an easier to understand way for a beginner, of course change the values accordingly, this simply makes a directory and makes a file then sets permissions.
<?php
$path = "..".$_SESSION['s_USER_URL'];
// may want to add a tilde (~) to user directory
// path, unixy thing to do ;D
mkdir($path, 0777); // make directory, set perms.
$file = "index.php"; // declare a file name
/* here you could use the chdir() command, if you wanted to go to the
directory where you created the file, this will help you understand the
rest of your code as you will have to perform less concatenation on
directories such as below */
$handle = fopen($path."/".$file, 'w') or die("can't open file");
// open file for writing, create if it doesn't exist
$info = "Stack Overflow was here!"; // string to input
fwrite($handle, $info); // perform the write operation
fclose($handle); // close the handle
?>