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

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.

Related

Having an issue with the fopen() php function

I have a users directory and a child directory for the login/register system. I have a file, testing.php, to try to figure out how to create a directory in the users directory AND create a PHP file within that same directory. Here's my code:
<?php
$directoryname = "SomeDirectory";
$directory = "../" . $directoryname;
mkdir($directory);
$file = "../" . "ActivationFile";
fopen("$file", "w");
?>
I'm able to get mdkir($directory) to work, but not the fopen("$file", "w").
Try this, this should normally solve your problem.
PHP delivers some functions to manipulate folder & path, it's recommended to use them.
For example to get the current parent folder, you can use dirname function.
$directoryname = dirname(dirname(__FILE__)) . "/SomeDirectory";
if (!is_dir($directoryname)) {
mkdir($directoryname);
}
$file = "ActivationFile";
$handle = fopen($directoryname . '/' . $file, "w");
fputs($handle, 'Your data');
fclose($handle);
This line is equivalent to "../SomeDirectory"
dirname(dirname(__FILE__)) . "/SomeDirectory";
So when you open the file, you open "../SomeDirectory/ActivationFile"
fopen($directoryname . '/' . $file, "w");
You can use the function touch() in order to create a file:
If the file does not exist, it will be created.
You also forgot to re-use $directory when specifying the filepath, so the file was not created in the new directory.
As reported by Fred -ii- in a comment, error reporting should also be enabled. Here is the code with these changes:
<?php
// Enable error output, source: http://php.net/manual/en/function.error-reporting.php#85096
error_reporting(E_ALL);
ini_set("display_errors", 1);
$directoryname = "SomeDirectory";
$directory = "../" . $directoryname;
mkdir($directory);
$file = $directory . "/ActivationFile";
touch($file);
try this:
$dirname = $_POST["DirectoryName"];
$filename = "/folder/{$dirname}/";
if (file_exists($filename)) {
echo "The directory {$dirname} exists";
} else {
mkdir("folder/{$dirname}", 0777);
echo "The directory {$dirname} was successfully created.";
}

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

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?

file_get_contents doesn't write to a log file

I am trying to write content to a log file using form input data. This doesn't seem to work on a server that's is using php version 5.3.14 but when i put the same code on a server that uses 5.3.27 its working. Does any one have an idea on how to fix this?
Below is my code that i am using for my form action. incoming.log is the file that i am trying to write to and is found in the folder path live/lms on the server. Please not that i am not getting any errors.
<?php
$system_path = '/live/lms/';
$fh = fopen($system_path . "incoming.log", "a");
fwrite($fh, "\nReceived:\n" . date("Y-m-d H:i:s") . "\n" . file_get_contents("php://input"));
fclose($fh);
?>
Not exactly an answer, but advise:
You should add more error handling ...and structure the script in a way so you can add more error handling.
For starters (work in progress):
<?php
$system_path = '/live/lms/';
$fhSource = fopen('php://input', 'rb');
if (!$fhSource) {
trigger_error('fopen input: '. print_r(error_get_last(), true), E_USER_ERROR );
}
$fhTarget = fopen($system_path . "incoming.log", 'a');
if (!$fhTarget) {
trigger_error('fopen output: '. print_r(error_get_last(), true), E_USER_ERROR );
}
$cb = stream_copy_to_stream($fhSource, $fhTarget);
var_dump($cb);
fclose($fhSource);
fclose($fhTarget);

how to get the text to go to the next row in a csv?

i am trying to get the text to go to the next row in a csv. this works great for TXT but doesnt foe CSV. do i need to write something diffrent for the csv rows?
<?php
$fp = fopen('wo.csv', 'a');
fwrite($fp, '"' . $_POST['Customer'] . '","' . $_POST['Contact_Name'] . '","' . "\r\n");
fclose($fp);
echo "<h1>Thank you for doing business with!</h1>";
?>
Use the built in CSV functionality!
<?php
$fp = fopen('file.csv', 'w');
fputcsv($fp, array($_POST['Customer'], $_POST['Contact_Name']));
fclose($fp);
?>
Reference
fputcsv
fgetcsv

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