I am trying to get a PHP script to take input from an html form to create a csv file. My PHP script is below:
<?php
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$row = [$fname, $lname, $email];
$file = fopen("mini4.csv", 'w');
for ($i=0; $i<3; $i++){
fwrite($file, $row[$i]);
if($i!=2){
fwrite($file, ", ");
}
}
fclose($file);
$file = fopen("mini4.csv", "r");
$data = fgetcsv($file);
echo file_get_contents( "data.csv" );
fclose($file);
?>
My PHP file has the following permissions : -rw-r--r--. The directory the PHP file is held in has the following permissions: drwxr-xr-x.
From everything I've read, issues like this are due to permissions, although, looking at other posts my permissions on the PHP file and directory above it are correct.
I saw some answers suggesting chmod -R 777 to the directory, but I am worried about potential security issues this might cause.
When I look at the access log on XAMPP, i see the following:
::1 - - [27/Feb/2022:17:23:14 -0500] "POST /mini4/mini4.php HTTP/1.1"
500 -
I turned on screen reporting and I am getting this:
Warning: fopen(mini4.csv): Failed to open stream: Permission denied in /Applications/XAMPP/xamppfiles/htdocs/mini4/mini4.php on line 12.
Although, I do not see how this can be given the permissions my file and directory have.
The permissions assigned to your PHP file are irrelevant. The permissions assigned to the folder your PHP script is trying to write to are important because they must grant read/write access to the user that Apache is using. Typically, that's the user/group apache:apache and that's different from the user you'll be logged in as.
Mostly it's enough to chmod g+rw <myFolder>, but this depends on the existing setup.
FWIW, your code is inordinately convoluted. You could just do this:
$file = fopen("mini4.csv", 'w');
fputcsv($file, [$_POST['fname'], $_POST['lname'], $_POST['email']]);
fclose($file);
readfile("mini4.csv");
Be aware that this need additional validation before using it in anger.
Related
I am using PHP to write information to a text file. I have used this code before, and it worked, but in a new project, it is not working.
I think the problem might be a permissions issue. The server is Ubuntu.
$message = "RESULTS = " . $data . "\n";
$fh = fopen("test.txt", 'a'); //open file and create if does not exist
fwrite($fh, "\n\n******* " . date('l, F j, Y (g:i A)') . " *********\n\n"); //Just for spacing in log file
fwrite($fh, $message); //write data
fclose($fh); //close file
When I debug using Netbeans, fopen() returns a boolean value of 0, which I take to means it failed, but I'm not sure what the reason is.
Is there anything wrong with the code above? If not, what permissions settings do I need on the directories or files involved to ensure I'm not getting blocked by a permission setting?
Is there anything else I should be looking for?
Check your directory
add dot-slash (./) at the beginning of your directory
$fh = fopen("./test.txt",'a'); //open file and create if does not exist
In Ubuntu ,
for a single file :
sudo chmod 777 /var/www/your-path/file.txt
for a directory
sudo chmod -R 777 /var/www/your-path
I'm trying to save some text that comes into a php script via a POST to a file. Here is my script:
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
$file = $path . '\test.txt';
$text = $_POST['text'];
// save it to a file
if (file_exists($file))
chmod($file, 0777);
$handle = fopen($file, 'w');
fwrite($handle, $text);
fclose($handle);
echo "success";
?>
I'm getting this error:
Warning:
fopen(D:\Hosting\11347607\html\test.txt) [function.fopen]: failed to open stream:
Permission denied in
D:\Hosting\11347607\html\test_file_saver.php on line
12
I've tried a number of different attempts and read many posts. The directory is set to RWX permission. How can I get permission to write to this file? Thanks!
If you don't have permissions to even open the file, what makes you think you have permission to change permissions?
That wasn't a question or a comment. You don't have permission to change the permission. Give your PHP process proper permissions.
I ran into a really bizarre problem. I am trying to perform writing to file using fopen().
This is what I tried in writetofile.php:
$fw = fopen('/test.txt', 'w');
fwrite($fw, 'hello world' . "\r\n");
fclose($fw);
This is the error I keep getting:
Warning: fopen(/test.txt):
failed to open stream: Permission denied in C:\inetpub\wwwroot\writetofile.php on line 41
Warning: fwrite() expects parameter 1 to be resource, boolean given...
I am 100% sure I have permissions to the server. I am the Administrator. Furthermore, I temporarily gave full permissions to everyone. I even tried running the php script locally, directly from the server using localhost. I am not using apache, I am using IIS. I tried restarting IIS after modifying permissions. I am not running php in safe mode.
Any idea on what might be causing this issue?
/test.txt would be a file in the ROOT directory of your filesystem, where user accounts generally do NOT have write privileges (unless you're running this code as root). This is especially true of PHP running under the webserver's user account.
You probably want just test.txt (no leading slash)` which will try to put the file into the script's "current working directory" - usually the same directory the script itself is in.
1- when you rollout website, delete all logs folder names
2- inside the code create folder name as below and create the logs insides
3- write at top of file. (during init the web)
$ClientUserName = gethostbyaddr($_SERVER['REMOTE_ADDR']);
function Data_Log($dataline)
{
global $ClientUserName;
$dir = 'UserInputLog' ;
$fileName = $ClientUserName. '_ServerWebLog.txt';
if(is_dir($dir) === false)
mkdir($dir);
$fileName = $dir. '\\'.$fileName;
$myfile = fopen($fileName, "a") or die("Unable to open file!");
fwrite($myfile, "$dataline\r\n");
fclose($myfile);
}
I have a zip file into a directory like this:
drwxr-xr-x 2 salome salome 4096 Dec 16 17:41 staff.zip
When I unzip the file with ZipArchive class, all the upzipped files are owner by nobody user. Is there a way to avoid this owner change?
I am able to use ftp if it is required (only as salome user).
This script eventually will be shared at multiple hosts, so the idea is keep it as generic as possible.
You might consider extending the zipArchive class and override the extractTo method to also perform a chown() on the files in the directory.
Based on the use case you discussed in the comments, you also might want to consider the use of the Phar archive format. php.net/manual/en/intro.phar.php
Phar's would allow your module submitters to submit a file file of executable PHP code that you would not need to extract at all.
Ok, I have resolved the problem of nobody user. I will try to explain all my workaround.
#Mike Brant's answer
Mike suggest to me make use of chown() function overriding extractTo() method. Well, before to willing with it, I tested the chown() function standalone constantly it printed the error:
failed to create stream: Permission denied in ...
Looks like chown will not work for the major shared hostings
FTP functions
So, keeping going I though that FTP functions I made a script that works fine, at least for now xD. This is a resume what the script does for one zipped file:
Create a temp file using tmpfile().
Using ftp_fput() to put the temp file in the current directory with the zipped file.
Give write permissions using ftp_site and CHMOD 0777.
Read the zipped file content with $content = $zip->getFromName('zipped-file.txt');.
Put the content to the new file using fputs($fp, $content);.
Close connections
The code below illustrates the complete process
$zip = new ZipArchive;
$ftp_path_to_unzip = '/public_html/ejemplos/php/ftp/upload/';
$local_path_to_unzip = '/home/user/public_html/ejemplos/php/ftp/upload/';
if ($zip->open('test.zip') == TRUE) {
//connect to the ftp server
$conn_id = ftp_connect('ftp.example.com');
$login_result = ftp_login($conn_id, 'user', 'password');
//if the connection is ok, then...
if ($login_result) {
//iterate each zipped file
for ($i = 0; $i < $zip->numFiles; $i++) {
$filename = $zip->getNameIndex($i);
//create a "local" temp file in order to put it "remotely" in the same machine
$temp = tmpfile();
//create the new file with the same name from the extracted file in question
ftp_fput($conn_id, $ftp_path_to_unzip . $filename, $temp, FTP_ASCII);
//set write permissions, eventually we will put its content
ftp_site($conn_id, "CHMOD 0777 " . $ftp_path_to_unzip . $filename);
//open the new file that we have created
$fp = fopen($local_path_to_unzip . $filename, 'w');
//put the content from zipped file
$content = $zip->getFromName($filename);
fputs($fp, $content);
//close the file
fclose($fp);
//now only the owner can write the file
ftp_site($conn_id, "CHMOD 0644 " . $ftp_path_to_unzip . $filename);
}
}
// close the connection and the file handler
ftp_close($conn_id);
//close the zip file
$zip->close();
}
This is the firt step to start a more complex customization, because the code above is not able to know if the zipped file is a "directory" or "file".
I want to HTTP POST data to a PHP file which will in-turn write the data into a file. The script I used is as follows,
<?php
#error_reporting(E_ERROR | E_PARSE);
$msglen=strlen($_POST["msgarea"]);
$msg=$_POST["msgarea"];
$fp = fopen("dinesh.txt", 'w');
fwrite($fp, $msg);
fclose($fp);
echo "Data Written -> $msg";
?>
I am hosting this script file in sourceforge.
I have already just created the empty file dinesh.txt and placed the file in the same directory as that of the script file. But unfortunately its not written in the file.
What is the reason ?
Thanks in advance
Check that $_POST["msgarea"] is not empty and the file is writeable for the user who tries to write it.
And check the logs for errors of course.
<?php
error_reporting(E_ALL);
var_dump($_POST["msgarea"]);
$msglen=strlen($_POST["msgarea"]);
$msg=$_POST["msgarea"];
$fp = fopen("dinesh.txt", 'w');
$result = fwrite($fp, $msg);
fclose($fp);
if ($result) {
echo "Data Written -> $result";
} else {
echo "Error";
}
I think you are writing in read-only webspace, check file permissions and path
From: http://sourceforge.net/apps/trac/sourceforge/ticket/2772
In generally it is not allowed to write to folders and files that reside in the project's web space. If you need to write to the file system you should use the folder named persistent that is on the same level as htdocs.
I use on my computer:
$ mkdir persistent
$ chmod 0777 persistent
$ scp -r persistent my_account#web.sourceforge.net:/home/project-web/my_project/
And set in PHP:
$fp = fopen("../persistent/dinesh.txt", 'w');
And it works!
Edit:
You can get access for SSH console for 4 hours (https://sourceforge.net/apps/trac/sourceforge/wiki/Shell%20service). And you can go to web directory of your project, make dirs, set privileges, remove files etc. Midnight Commander is available.
you can, check that folder permission, do they have 777 permission
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Bobby Bopper\n";
fwrite($fh, $stringData);
fclose($fh);