I'm using CentOS7. My index.html, action.php and file.txt are all in the same folder. I have already set chown apache:apache to the entire /var/www/html tree. The file does get open but I am not able to write anything to it. It's my first ever PHP code, so please let me know if I'm being stupid or something. The var_dump($_POST); works fine as well.
<?php
$name = $_POST['fname'];
$fp = fopen("file.txt","w") or die("Can not open file");
fwrite("file.txt",$name) or die ("can not write to file");
fclose($fp);
?>
You have to use the file handle resource in this case $fp, and not the name.
So this:
$name = $_POST['fname'];
$fp = fopen("file.txt","w") or die("Can not open file");
fwrite("file.txt",$name) or die ("can not write to file");
Should be:
//if(!empty($_POST['fname'])){ ..you should really check this
$name = $_POST['fname'];
$fp = fopen("file.txt","w") or die("Can not open file");
fwrite($fp,$name) or die ("can not write to file");
For reference:
http://php.net/manual/en/function.fwrite.php
int fwrite( resource $handle, string $string [, int $length ] )
That said in a case like this, writing a single line.
if(!file_put_contents("file.txt", $name)) die ("can not write to file");
Is a bit easier to use. But in any case these 2 things you don't need to do:
fclose($fp);
?>
The file is closed when PHP is done, and the ending tag can actually cause more issues then it's worth. The only time I use fclose is if I open a file and read from it and then delete it with unlink you can't unlink it if its open, otherwise I just let PHP close it. The ending tag is only needed if you plan to follow the PHP code with something like HTML. Having space (for example) after an ending tag can corrupt file downloads because any content that is output will be included in a download. What's worse is if you included a file that has the space (or other stuff) it can be really hard to find out why you can't open a zip file you sent as a download (for example).
Cheers, and good luck.
you need to pass the file object to the function
<?php
$name = $_POST['fname'];
$fp = fopen("file.txt","w") or die("Can not open file");
fwrite($fp,$name) or die ("can not write to file");
fclose($fp);
?>
Related
I have code I'm using to create a file using the name of one field, then opening that file and writing the contents from another. That works fine.
However when users attempt to pull up this file and change information and save it it doesn't overwrite the information.
If a user deletes the file (which works) then recreates it using the same name, but attempts to input new data, it creates the new file (with the same name as the old file) however it retains the old information and doesn't update. I can't find out what's causing that.
I was originally using file_put_contents and I've attempted to use different parameters for the fopen() but it doesn't seem to work. They can create and save just fine, however the main issues are they can't edit as it doesn't overwrite data and they can't delete the file (even as a workaround) and recreate it using the same name.
edited to add: Also when they try and save information, instead of opening the file and overwriting it, it creates a second and NEW file filename.html.html
// Put together the full path of the file we want to create
$FILENAME = $USER_DIRECTORY.'/'.$_POST['CodeDescription'].'.html';
$CODE = $_POST['Code'];
if( !is_file( $FILENAME ) ):
// Open the text file, write the contents, and close it.
$fp = fopen($FILENAME, "w+") or die("Couldn't open $FILENAME for
writing!");
fwrite($fp, $CODE) or die("Couldn't write values to file!");
endif;
header('Location: mywebsite.comsaved=1&file='.$FILENAME);
}
?>
A quick hack might be to try this:
// Put together the full path of the file we want to create
$FILENAME = $USER_DIRECTORY.'/'.$_POST['CodeDescription'].'.html';
$CODE = $_POST['Code'];
//Delete file if exists.
if(is_file( $FILENAME)) {
unlink($FILENAME);
}
// Open the text file, write the contents, and close it.
$fp = fopen($FILENAME, "w+") or die("Couldn't open $FILENAME for
writing!");
fwrite($fp, $CODE) or die("Couldn't write values to file!");
header('Location: mywebsite.comsaved=1&file='.$FILENAME);
}
I want to change the old values of a text file with a new values (delete the old content and replace it), when I use the code below it shows me an error page , don't really know how to fix this , even used the different types of file opening methods (w , r+ , a ...) and didn't work !
$i=$_POST['id'];
$fp = fopen ("/test/member_dl.txt", "r+");
$ch = fgets ($fp);
$t=explode('||',$ch);
$t[$i-1]='';
$ch2=implode('||',$t);
fwrite($fp,$ch2);
fclose ($fp);
As you want to completely replace the contents, why not just delte it, and re-create it?
unlink ("/test/member_dl.txt");
$fp = fopen ("/test/member_dl.txt", "r+");
// Continue with your code.
// Not sure I follow what you are doing with it
Edit: I am not sure I understand what that part of your code is doing to be honest.
The unlink() command deletes the file. From there you can start over and write the file out as you need it?
Whilst it's open as $fp = fopen ("/test/member_dl.txt", "r+");
You will not be able to fwrite($fp,$ch2);
Opening it with 'w+' should enable read and writing.
Try this:
$i=$_POST['id'];
$fp = fopen("/test/member_dl.txt", "w+");
$ch = fread($fp, filesize($fp));
$t=explode('||',$ch);
$t[$i-1]='';
$ch2=implode('||',$t);
fwrite($fp,$ch2);
fclose ($fp);
EDIT:
Tested this, this works
$ch = file_get_contents("test.txt");
$t=explode('||',$ch);
$t[$i-1]='';
$ch2=implode('||',$t);
file_put_contents("test.txt","hello");
I have a file "tw.txt" with the text "test text" in it.
If I try to write "lol" in "tx.txt" with fwrite, the content ("test text") is simply erased and not replaced.
There is no error displayed by the server, however, I can see my Error: can't write in file.
CHMOD is set to 777 in every files and folders, from the "var" rep to the website folder. If I try to read a file with fopen, no problem. I tried to change the chmod with PHP... no success. I tried to append, it erase.
The code works fine on two other servers.
Any clues ? Thanks.
<?php
ini_set('display_errors', 'On');
ini_set('allow_url_fopen', '1');
error_reporting(E_ALL);
$fd=fopen("tw.txt","w") or die("Error: can't open file.");
//chmod("tw.txt", 511);
fwrite($fd,"lol") or die('Error: can't write in file.');
fclose($fd);
?>
Have you tried other opening modes?
If you need to append some data, you should try something like:
$fd=fopen("tw.txt","a+")
$myFile = 'tw.txt';
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, 'lol');
fclose($fh);
I'm trying to create a php file which I can edit straight away without manually set the permissions.
I'm trying this...
<?php
$var = '<?php $mycontent = new Content(); echo $mycontent->block($p_name);?>';
$myFile = "testFile.php";
$fh = fopen($myFile, 'w+') or die("can't open file");
$stringData = $var;
fwrite($fh, $stringData);
fclose($fh);
?>
...it creates the file, but when I try to edit the file in my IDE it won't let me of course. I have to manually set the permission of the file created. Is there any way I can create the file and have the permission already set?
Thanks in advance
Mauro
Yes, you can thanks to PHP CHMOD
// Read and write for owner, read for everybody else
chmod("/somedir/somefile", 0644);
Since this aspect wasn't covered in previous answers I'll add it here:
chmod() will only take a path string as the 1st argument. So you cannot try to pass to resource that was open with fopen(), in this case $fh.
You need to fclose() the resource and then run chmod() with the file path. So a proper practice would be storing the filePath in a variable and using that variable when calling fopen() rather than passing it a direct string in the first argument.
In the case of the example code in the answer this would simply mean running chmod($myfile, 0755) (the permission code is only an example and be different of course.)
full code after corrections:
<?php
$var = '<?php $mycontent = new Content(); echo $mycontent->block($p_name);?>';
$myFile = "testFile.php";
$fh = fopen($myFile, 'w+') or die("can't open file");
$stringData = $var;
fwrite($fh, $stringData);
fclose($fh);
// Here comes the added chmod:
chmod($myFile, 0755);
?>
Php has chmod, works just like the Linux version.
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
?>