PHP fopen() won't write to txt files in some cases - php

I'm not sure if it has to do with my permissions for file writing, or if I'm just plain doing it wrong.
Here is my PHP code:
Note: this is located in www.sitename/folder1/folder2/index.php
$user = $_POST['user'];
$pass = $_POST['pass'];
$fp = fopen("../folder1/test.txt", "a");
$savestring = $user . "\n" . $pass . "\n";
fwrite($fp, $savestring);
fclose($fp);
It doesn't work. It says it is unwritable.
I tried this too: /folder1/test.txt
and http://sitename.com/folder1/test.txt
The only thing that works is fopen("folder1/test.txt"a");, but that writes to www.sitename.com/folder1/folder2/folder1/test.txt, which is what I completely do not want.
Is it something I did wrong?

Related

How do I create a file with PHP? (Ubuntu)

This may be marked as duplicate, but everything else I tried here didn't work. I am trying to create a file in PHP using this:
<?php
$con = $sup;
$fp = fopen($_SERVER['DOCUMENT_ROOT'] . "/var/www/HDdeltin/" . $sup , "wb");
fwrite($fp,$con);
fclose($fp);
?>
I am using ubuntu(xfce)
What is wrong with this?
$fp = fopen($_SERVER['DOCUMENT_ROOT'] . "/var/www/HDdeltin/" . $sup , "wb");
is incorrect: normally $_SERVER['DOCUMENT_ROOT'] is already /var/www/. Try
$fp = fopen($_SERVER['DOCUMENT_ROOT'] . "/HDdeltin/" . $sup , "wb");
or
$fp = fopen("/var/www/HDdeltin/" . $sup , "wb");
depending on whether you want your file under the document root or under a specific location.
<?php
$con = $sup;
$fp = fopen($_SERVER['DOCUMENT_ROOT'] . "/var/www/HDdeltin/" . $sup , "wb");
fwrite($fp,$con);
fclose($fp);
?>
I don't know if you can use the last parameter 'wb' for the fopen function. Try to use only 'w' option then let us know if it works.
This is what I came up with:
<?php
$text = "This will be placed in your file.";
$con = "test.txt";
$fp = fopen($_SERVER['DOCUMENT_ROOT']. "/HDdeltin/$con", "wb");
fwrite($fp,$text);
fclose($fp);
?>
This seems to works if the folder HDdeltin exists, otherwise it will return an error.
$text would be the replacement of your $sub because you didn't declare one.
And I removed the /var/www/ part since this is exactly what $_SERVER['DOCUMENT_ROOT']; should return.

Multiple fopens - only first one works

I've a strange issue I am encountering. Recently I switched from webhosting to a VPS, mainly because of flexibility a VPS provides me with.
I now however need to setup Apache on my own and I'm not to good at doing so.
I've a .php file and I have 2 fopen in it. The first one does it's job but the second one doesn't work for some reason.
I was wondering, is there some php.ini settings I need to make to allow multiple fopen in a file ?
EDIT
Code below:
$fp = fopen('ticket' . $_SESSION['id'] . '.txt', 'a+');
$savestring = "---";
fwrite($fp, $savestring);
fclose($fp);
$_SESSION['total'] = $total;
$fp = fopen('reqs.txt', 'a+');
$savestring = PHP_EOL . "Ticket Nou: " . $_SESSION['id'] . " | Ora: " . $ordertime . " | IP: " . $ip;
fwrite($fp, $savestring);
fclose($fp);
I shortened the $savestrings, in reality they are longer. The issue occurs with the second file, reqs.txt.
try to use flock
I have a file with 4 fopen it didn't work.
after using flock it worked.

PHP fwrite() how to insert a new line after some specific line

I'm new here.
Anyway, I did my research on fwrite(), but I couldn't find solution, so i'm asking for help.
What I want is f.e. to add a new line of text after some other specific line.
F.e. I have a .txt file in which there is:
//Users
//Other stuff
//Other stuff2
Now what I'd like to do is be able to add a new user below //Users without touching "Other Stuff" and "Other Stuff 2". So it should look something like this:
//Users
Aneszej
Test321
Test123
//Other stuff
//Other stuff2
What I have so far:
$config = 'test.txt';
$file=fopen($config,"r+") or exit("Unable to open file!");
$date = date("F j, Y");
$time = date("H:i:s");
$username = "user";
$password = "pass";
$email = "email";
$newuser = $username . " " . $password . " " . $email . " " . $date . " " . $time;
while (!feof($file)) {
$line=fgets($file);
if (strpos($line, '//Users')!==false) {
$newline = PHP_EOL . $newuser;
}
}
fwrite($file, $newline);
fclose($file);
test.txt file
//Users
//Something Else
//Something Else 2
But this only writes users to the end of the .txt file.
Thanks a lot everyone for your help! It's solved.
I modified your code, I think follows is what you need, and I also put comment, function below will keep adding new user, you can add condition that to check user exist.
$config = 'test.txt';
$file=fopen($config,"r+") or exit("Unable to open file!");
$date = date("F j, Y");
$time = date("H:i:s");
$username = "user";
$password = "pass";
$email = "email";
$newuser = $username . " " . $password . " " . $email . " " . $date . " " . $time."\r\n"; // I added new line after new user
$insertPos=0; // variable for saving //Users position
while (!feof($file)) {
$line=fgets($file);
if (strpos($line, '//Users')!==false) {
$insertPos=ftell($file); // ftell will tell the position where the pointer moved, here is the new line after //Users.
$newline = $newuser;
} else {
$newline.=$line; // append existing data with new data of user
}
}
fseek($file,$insertPos); // move pointer to the file position where we saved above
fwrite($file, $newline);
fclose($file);
You write the new content at the end of the reading, so it has to write at the end of file - the cursor is there after reading all the lines.
Either you store all the content in php-variable and overwrite the file in the end, or you rewind the curser with fseek as mentioned by Robert Rozas comment. That should be done as soon as you read the "Something else" - line.
Try fseek:
<?php
$file = fopen($filename, "c");
fseek($file, -3, SEEK_END);
fwrite($file, "whatever you want to write");
fclose($file);
?>
PHP Doc: http://php.net/manual/en/function.fseek.php
You need to break after you find '//Users'. You keep reading to the end of the file.

Why do I keep getting "directory does not exist?"

I cannot figure out what I am doing wrong here. The permissions for the directory I have for the file being created have write permissions all across the board. I keep getting "directory does not exist" Thanks for the help!
<?
//creates variables and calls the information from the server
$Name = $_POST['name'];
$desc = $_POST['desc'];
$website =$_POST['web'];
$email =$_POST['email'];
$cname =$_POST['cname'];
echo "your registered name is: ". $Name . ".<br/>";
echo "your registered description is: " . $desc . ".<br/>";
echo "your website address is: " . $website . ".<br/>";
echo "your Confirmation email has been sent to: " . $email . ".<br/>";
echo "your information has been stored, thank you! ";
$cname = trim($cname);
$filename = "data/clubinfo/$cname.txt";
$fp = fopen($filename,'a');
fwrite($fp,$Name);
fwrite($fp,"\n");
fwrite($fp,$email);
fwrite($fp,"\n");
fwrite($fp,$desc);
fwrite($fp,"\n");
fwrite($fp, $website);
fwrite($fp, "\n");
fwrite($fp,"__");
fwrite($fp, "\n");
fclose($fp);
?>
Most likely the script is assuming a different working directory to what you're presuming since you're using a relative path.
You'd be better off specifying the path absolutely or at least in relation to $_SERVER['DOCUMENT_ROOT'] even if you do:
$filename = $_SERVER['DOCUMENT_ROOT'] . "../data/clubinfo/$cname.txt";
The advantage of that is that it's outside your document root so it won't be served directly by your Web server. It will also work no matter the location of your script and will work no matter under what directory you install your Webapp, which can be an issue with dev vs prod deployments.
The data/clubinfo folder does not exist in the current directory.
You need to create it first. (By hand or in PHP)
Alternatively, the current directory might not be what you think it is.
Try using file_put_contents() like this:
file_put_contents("data/clubinfo/$cname.txt", implode("\n", $_POST));
If you want to this value by value you should also use the FILE_APPEND flag.
looks like you have not given the path off the root and the server is looking from the current location. try giving the path off the root.

php fopen - name of file

I currently have:
<?php
if (isset($_POST["submitwrite"])) {
$handle = fopen("writetest.txt","w+");
if ($handle) {
fwrite($handle, "Dan"."¬".$_POST["username"]."¬".$_POST["pollname"]."¬".$_POST["ans1"]."¬".$_POST["ans2"]."¬".$_POST["ans3"]."¬".time());
fclose($handle);
}
}
?>
However I need to adjust the filename to be dynamic, instead of 'writetest.txt' I would like it to be: username+pollname+time.txt taking the $_post variables.
I would also like to change the directory these files are stored in to /results.
Help please...
You mean doing something like this?
$filename = '/results/' . $_POST['username'] . '/' . $_POST['pollname'] . '/time.txt';
if (isset($_POST["submitwrite"])) {
$handle = fopen($filename,"w+");
// etc...
Or am I not understanding you?
Edit
To address the issue BalusC pointed out, this is a more complete solution.
It makes sure the $_POST['username'] and $_POST['pollname'] values are valid, so they won't create an invalid or possibly harmful $filename.
<?php
$basedir = '/results';
$basename = 'time.txt';
// Get user and poll names
$username = $_POST['username'];
$pollname = $_POST['pollname'];
// Counteract the old magic_qutoes feature, if needed.
if(get_magic_quotes_gpc()) {
$username = stripslashes($username);
$pollname = stripslashes($pollname);
}
// Validate user and poll names.
$regexp = '/^[\w\d\_\-\. \']+$/iu';
if(!preg_match($regexp, $username) || !preg_match($regexp, $pollname)) {
echo 'Username or pollname is invalid. Aborting!';
}
else {
// Compile the complete file name
$filename = $basedir . '/' . $username . '/' . $pollname . '/' . $basename;
// Write to the file
if (isset($_POST["submitwrite"])) {
$handle = fopen($filename,"w+");
if ($handle) {
fwrite($handle, "Dan"."¬".$_POST["username"]."¬".$_POST["pollname"]."¬".$_POST["ans1"]."¬".$_POST["ans2"]."¬".$_POST["ans3"]."¬".time());
fclose($handle);
}
}
}
?>
fopen creates (at least tries) the file if it does not exist, so
$filename = $username . $pollname . $time . '.txt';
$handle = fopen($filename, 'w+');
will work fine.
By the way, w+ places the pointer at the beginning of the file. If the file already has some data, it will truncate it first. If you want to append data to the file, you may want to use 'a+'

Categories