PHP - writing into a file - fwrite - php

I am PHP noob, but i am trying to learn it. I have handled some variables and obtaining variable from html form and I wanted to take a string that users types in form -here is code of the form on the page
<form method="POST" action="/php/write.php">
<input type="text" name="string"><input type="submit">
</form>
and in subfolder php I have file "write.php" and it looks like this
<?php
chmod(/write.txt, 0755);
$write == $_POST['string'];
$file = fopen("write.txt","w") or die("cant open file");
fwrite($file, $write);
fclose($file);
?>
I have tried to put into normal HTML file but didnt work too.
The problem is, when I type in the form and press submit, it redirects me on write.php but nothing happens, "cant open file" isnt written nor some error and the file stays empty and no fwrite works for me. Could someone help me please?

A few problems with your code:
chmod(/write.txt, 0755);
The file name must be quoted, and it probably shouldn't be located in the root. The chmod() function only works on existing files. If your file already exists, this is not an error.
$write == $_POST['string'];
The == is the comparison operator. You want assignment =.
You code should look something like this:
$write = $_POST['string'];
$file = fopen('write.txt','w') or die('cant open file');
fwrite($file, $write);
fclose($file);
chmod('write.txt', 0755);
(I prefer single-quoted strings when I don't need to have variables expanded inside.)
Also, in a well-written program, you should:
check if $_POST['string'] actually exists before accessing it, using isset ($_POST['string']).
check the return values of fopen(), fwrite(), fclose() and chmod(), and deal with potential errors.

Related

Form empty itself without doing anything

Earlier today I asked a question about what I was doing wrong, I got this working but now I'm running into another problem with this script.
Previously
The code gave a warning(), that's fixed now. You can read the post Here
What's the problem?
The code automatically empty itself. When you refresh the page where the script is the text file is empty. I have no idea why...
This is the code
<?php
$fn = "file.txt";
$file = fopen($fn, "w+");
$size = filesize($fn);
if($_POST['addition']) fwrite($file, $_POST['addition']);
fclose($file);
?>
<form action="<?=$PHP_SELF?>" method="post">
<input type="text" name="addition" value="<?php echo file_get_contents('file.txt');?>"/>
<input type="submit"/>
</form>
I use this script to display a youtube video on my website, so I got to update it often.
You can find a working example of the script with this link: http://beta.martijnmelchers.nl/private/Test/test.php
What have i tried?
I didn't try many because I couldn't find a solution for this on the internet and also not in the code.
Please help me again! Thanks in advance!
According to the manual with the w+ option:
Open for reading and writing; 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.
It looks like you want to replace all contents when a post is made, so the easiest solution is to put all file-handling calls in the POST condition:
// To avoid warnings, this is better.
// You can add your original condition after it if you need it.
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
$file = fopen($fn, "w+");
// not sure why you need this...
// $size = filesize($fn);
fwrite($file, $_POST['addition']);
fclose($file);
}

Cannot open file using fopen (php)

I am trying to open a file for reading in php script but having trouble.
This is my code
$fileHandle = fopen("1234_main.csv", "r")or die("Unable to open");
if (!file_exists($fileHandle))
{
echo "Cannot find file.";
}
The script is in the same directory as the file I am trying to read and there are no other read/write permission errors as I can create/read other files in the same directory.
When I run the script I just get the "Cannot find file" error message. Why is this error message being shown? Surely if fopen() can't open the file the "or die statement" should end the script?
Also, why can't I open the file when it definitely exists and is in the same location as the script (I have also tried using the full path of the filename instead of just the filename).
I am fairly new to php (but have exp in c++) so if its a stupid question I apologize.
Many thanks
In PHP, file_exists() expects a file name rather than a handle. Try this:
$fileName = "1234_main.csv";
if (!file_exists($fileName))
{
echo "Cannot find file.";
} else {
$fileHandle = fopen($fileName, "r")or die("Unable to open");
}
Also keep in mind that filenames have to be specified relative to the originally requested php-script when executing scripts on a web server.
You can use file_get_content() for this operation. On failure, file_get_contents() will return FALSE.For example
$file = file_get_contents('1234_main.csv');
if( $file === false ){
echo "Cannot find file.";
}
file_exists() take the file-name as input, but the logic of your code has problem. You first try to open a file then you check its existence?
You first should check its existence by file_exists("1234_main.csv") and if it exists try to open it.
file_exists takes a string, not a file handle. See http://php.net/manual/en/function.file-exists.php

Open a file in a new browser window after having written it (with fopen)

I'm writing a simple order system where several numbers (filled in inside a form) are written to another .php file (may be .html also), using the fopen function. This works fine, but after writing to the file, I want the browser to actually open that written file, preferably in a new browser window. This way my client can use this to print, use as an invoice, etc.
Now I'm still a rookie on php grounds and am not experienced with the use of fopen. But everywhere I look for tutorials etc., it's said that fopen opens (or writes of course) a file, but it doesn't for as far as I've experienced. It just seems to allow access to the specified file to write and read, rather to actually display the newly written page.
To avoid any confusion: I do NOT want to open links like other questions here on SO state.
My code:
<form action="" method="post">
<input type="text" id="amountTuna" name="numberTuna" value="0"/>
<input type="text" id="amountCheese" name="numberCheese" value="0"/>
<input name="send" id="send" type="submit" value="Post order" />
</form>
<?php
if (array_key_exists('send', $_POST)) {
$order = "order.php";
$fh = fopen($order, 'w') or die("can't open file");//file handler
fwrite($fh, "Tuna sandwiches: " . stripslashes($_POST['numberTuna']));
fwrite($fh, "Cheese sandwiches: " . stripslashes($_POST['numberCheese']));
$fh = fopen($factuur, 'r');
$fileip = fread($fh, filesize($factuur));
fclose($fh);
}
?>
Trying different fopen parameters such as 'w','r','r+' etc doesn't seem to make any difference. Removing fclose($fh) doesn't seem to make any difference either.
Use JS script to open new window. For example right after fclose($fh):
echo "<script>window.open($order, '_blank'); window.focus();</script>";
Storing things in a database would likely be a lot easier.
That said, using fopen is to open the file itself, opening the written file in a new browser window will require some client-side scripting (i.e. Javascript) to load the newly created file.
Google Javascript window.open().
Tom
Since you just want to write to a printable page .. have you tried file_put_contents
Example
if (isset($_POST['send'])) {
$file = "test.html";
$data = "Tuna sandwiches: " . stripslashes($_POST['numberTuna']) . "<br>";
$data .= "Cheese sandwiches: " . stripslashes($_POST['numberCheese']) . "<br>";
touch($file);
file_put_contents($file, $data);
}

How can I include custom text inside a file saved from a php form?

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.

Php fopen write in css file -> file empty

i have this following php code :
$filename = '/front/style.css';
$cssfile='#h1{font-size:12px}';
if($id_file=fopen($filename, "w+"))
{
echo'file exist';
$id_file=fopen($filename, "w+");
flock($id_file,1);
fwrite($id_file,$cssfile);
flock($id_file,3);
fclose($id_file);
}
else
{
echo "file don t exist";
}
My file is empty but with space.
My file exist and it s writable.
I have nothing in my apache logs.
I m using Mamp with php 5.3.2.
Any ideas ?
Thx
A few mistakes I can see are:
You are using fopen to check if a file exists. That does not work. With the w+ mode PHP will try to create the file if it does not exist. Use the file_exits function to check the existence of a file.
You are opening the same file twice.
Also use PHP constants(LOCK_SH, LOCK_UN) for the second argument of flock. That will make your program more readable.
Updated
Have you checked if its writing to a different directory than you expect? Check your path to see where it defaults to, or even just do a search for the file and see where else it turns up. getcwd() will show what the current working dir is.
Have you checked the return value of fwrite to see if the write is actually working? If fwrite is successful, then try read the file in the code using the same $id_file and see if there is anything there while the program is still running.
You are calling fopen twice. w+ truncates the file and you are writing to the 2nd $id_file so my guess is that its being truncated when the 1st $id_file is being closed.
You can use this approach if your file empty after using fopen w+ option.
// only read
$filename = '/path/to/blah.txt';
$myfile = fopen($filename, "r");
$mydata = fread($myfile, filesize($filename));
$mynewdata = $mydata + 'abc';
fclose($myfile);
// only write
$myfile = fopen($filename, "w");
fwrite($myfile, $mynewdata);
fclose($myfile);

Categories