Overwriting File if File already exists - php

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);
}

Related

PHP fwrite can not write to a txt file

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);
?>

move_uploaded_file() is not working but file is uploaded?

So i'm currently trying to create a code which simply creates and publishes a file to my webroot, modifies and writes to that file, and then finally change the location of the file to another directory/folder using move_uploaded_file()
This is my code so far
$myfile = fopen($_POST['title'].".txt", "w");
move_uploaded_file($myfile,'$dir/$title.txt');
fwrite($myfile, $_POST['textarea11']);
fclose($myfile);
The code doesn't work, i've tried echoing move_uploaded_file() and it returned nothing, however the file was uploaded but it's location just wasn't changed.
$dir is defined as $dir = __DIR__.'/../uploads/'; and $title is define as $title = $_POST['title'];
move_uploaded_file() can only be used if you are submitting a multipart form and you want to save the uploaded file.
What you probably need is this:
http://php.net/manual/en/function.rename.php
Change your given code as
$dir = __DIR__.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'uploads';
$myfile = fopen($_POST['title'].".txt", "w");
move_uploaded_file($myfile,"$dir".DIRECTORY_SEPARATOR."$title.txt");
fwrite($myfile, $_POST['textarea11']);
In your code
move_uploaded_file($myfile,'$dir/$title.txt');
php variable $dir and $title value is not coming. and value of $dir is consisting '/' and you are adding one more to make full file path too.
Always use directory separator to run in all Operating System. some OS use '/' and some OS use '\'.

PHP save and retrive options from a file

I use a custom CMS in PHP and I need to let admin user to save a global configuration option for his website.
I would like to store this value into a file.
Avoiding to save it into mysql DB, so I don't need to do an extra query on every page load.
What is the best way to store this option from a form into a file?
I need to reload my saved setting so it can be edited with my form
Ini file format simple enough for anyone to understand (read). You might want to paste the file's content into a textarea for simple edition.
For advanced edition, you can use parse_ini_file http://php.net/manual/en/function.parse-ini-file.php .
here is the code to open a php file using php :
$file = "/home/dir/file.php";
$fs = fopen( $file, "a+" ) or die("error when opening the file");
while (!feof($fs)) {
$contents .= fgets($fs, 1024);
}
fclose($fs);
now you can take the $contents and modify it to however you would like and then save it. here is how you can save it :
$fs = fopen( $_POST["file"], "a+" ) or die("error when opening the file");
fwrite($fs, $updatedContents);
fclose();
$updatedContents
is the updated content
how to update a php file's source code via another php file

using fgetcsv from a file on a FTP server

I need to read a list of CSV files from an FTP and delete them after I successfully read them.
Until now, i opened the csv file using fopen into a resource and then used fgetcsv to read the csv lines from it.
$res = fopen($url);
while ($csv_row = fgetcsv($res, null, self::DELIMITER)) {
.....
}
The problem is that I need to read a list of csv files and delete them too. the ftp_get function save the file into a local file. I rather avoid that. any way I can keep using the fgetcsv function with the ftp_nlist & ftp_connect functions? ?
You can save the csv file to a temporary file stream using ftp_fget(). This allows you to avoid the "create-read-delete" cycle. Once you close the file stream it's like it magically never existed :)
$ftp_handle = ftp_connect($ftp_server);
$remote_path = "/path/to/file.csv";
$tmp_handle = fopen('php://temp', 'r+');
if (ftp_fget($ftp_handle, $tmp_handle, $remote_path, FTP_ASCII)) {
rewind($tmp_handle);
while ($csv_row = fgetcsv($tmp_handle)) {
// do stuff
}
}
fclose($tmp_handle);
If you wanted to loop over a directory of files just get the list of files and then put the above code in a loop.

php: writing files

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
?>

Categories