Блокнот не сохраняет в php

Создание простого блокнота на PHP с названием файла

Я знаю что данный вопрос уже много раз рассматривался на форуме, но свою проблему я так и не нашел здесь, поэтому и пишу вопрос.

Помогите доработать код, который будет создавать TXT файлы с содержимым введенный в textarea, а название сохранял то, что введено в input.
то есть если ввели Теst, то сохраниться Test.txt

По своей сути форма что-то типа такого:

form method="post"> input type="text" value="Название файла"> textarea name="text">Содержимое, которое надо сохранить/textarea> input type="submit" value="кнопка сохранить"/> /form>

Буду очень благодарен за помощь!

P.S.
На страницах форума я нашел PHP код, который создает TXT файл, но у него фиксированное название.
Можно на примере данного кода переработать.
К сожалению моих знаний не достаточно для работы с POST.

 if(isset($_POST['text'])) { $text = trim($_POST['text']); file_put_contents('file.txt', $text); } ?>

Источник

Сохранение данных в txt файл

Сохранение данных регистрации в txt файл
Ребят доброй ночи. Есть форма регистрации HTML Не могу добиться сохранения "хотяб" e-mail в txt.

Сохранение данных регистрации в txt файл
У меня есть php файл регистрации. Не могу сделать так чтобы только емайл и телефон записывались в.

Организация чата, сохранение данных в файл txt
<! DOSTYPE HTML> <html lang="en=ru"> <head> <meta charset="UTF-8"> <title>.

Сохранение данных из форм в .txt при авторизации
Добрый день друзья. Есть форма авторизации за сайте <form method=post name=mainform.

Вообще средствами PHP можно сделать:

$fg = fopen("имя файла","w"); //w+ это режим записи файла $fwrite = ($fg, $text); //предпологается, что форма пришла и мы достали с нее значение из твоих полей в переменную $text. 
 $file = fopen("file.txt","a+"); $text="Вам пришло письмо от пользователя $name\n"; $text="Текст сообщения:\n $mess \n"; $text="Ответить можно на адрес электронной почты $email \n" flock($file, LOCK_EX); fwrite($file, $text); flock($file, LOCK_UN); fclose($file); echo "Сообщение отправленно."; ?>

ЦитатаСообщение от Fool Посмотреть сообщение

 $file = fopen("file.txt","a+"); $text="Вам пришло письмо от пользователя $name\n Текст сообщения:\n $mess \n Ответить можно на адрес электронной почты $email \n"; flock($file, LOCK_EX); fwrite($file, $text); flock($file, LOCK_UN); fclose($file); echo "Сообщение отправленно."; ?>

ЦитатаСообщение от Fool Посмотреть сообщение

file_put_contents('file.txt', $text, FILE_APPEND);

ЦитатаСообщение от Fool Посмотреть сообщение

ЦитатаСообщение от Fool Посмотреть сообщение

Да просто зацетирую и всё))
Записать файл на сервере можно несколькими способами. для этого используется комбинация функций
fopen(), fwrite(), fclose(). В промежутках между этими функциями нужно делать блокировку, иначе высока вероятность совместного доступа. То есть если два юзера одновременно захотят записать данные, начнется путаница. Для начала мы воспользуемся безопасной комбинацией функций file_get_contents() и file_put_contents(). Один момент — функция file_put_contents() доступна только в 5 (и выше) версии php. А функция file_get_contents() умеет читать файл частично только начиная с 5.1 версии. Но пока нам файл нужен целиком, а дальше видно будет.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
 /** * The guest book * Гостевая книга * @author IT studio IRBIS-team * @copyright © 2009 IRBIS-team */ ///////////////////////////////////////////////////////// /** * We establish the charset and level of errors * Устанавливаем кодировку и уровень ошибок */ header("Content-Type: text/html; charset=utf-8"); error_reporting(E_ALL); $text1 = !empty($_POST['text1'])?$_POST['text1']:null; $text2 = !empty($_POST['text2'])?$_POST['text2']:null; ?> 
echo htmlspecialchars($text1) ?>"/>

if(!empty($_POST['ok'])) { if(!$text1) echo 'Текстовое поле не заполнено.'; elseif(!$text2) echo 'Текстовая область не заполнена.'; else // Записываем информацию в файл, заканчивая символом переноса строки \n file_put_contents('text.txt', $text2 ."\n", FILE_APPEND); } else { echo 'Напишите что-нибудь'; }

Нажмите кнопку и посмотрите, что теперь находится рядом с этим скриптом. Появился новый файл? Откройте его в блокноте и посмотрите, что в нём. Вот так сохраняются данные на сервере.

Источник

file_put_contents not creating txt file

I currently have a php script that is running when a browser browser browses to the webpage. What I’m trying to do is write a text file when the script runs that stores a variable. The owner of the folder is apache, but everyone has read write, strictly for testing purposes. (I thought it might be a permissions issue) SELINUX is enabled on the server, and when I run the script from console it creates the text file just fine, and in the right directory.

file_put_contents("My working file location", $myString); 

I’m using this line to try to write and create the text file, I know that my file location works becaus I can run it and create it in offline mode, I.E. running it through console. The problem is that the variable I’m trying to write is populated through HTTP Post, and when I run the script through the browser, or when apache runs the script, it does not write or create the file. What do I need to do to allow access to write/change syntax wise to get this script to write this text file?

your apache user should have rights to directory — just try to execute the script as apache user from the command line to see if that works

I’m running it from browser, and it’s not flagging any errors, or I should say more accurately I don’t know where to get the error messages in browser. @user1914292 I have tried multiple locations including the webroot with apache is the owner of, so I’m not sure if that’s necessarily the issue. @CooPer `$myString = strReplace(of an xml string), so it’s just a string value

5 Answers 5

Your problem is likely due to apache not having permissions to write to the file location you specified. Go to that directory and check the permissions and group ownership with the ls command:

cd "My working file location" ls -l . 

There are three columns in the output that show the permissions, owner, and group for the directory. Most likely they are owned by root and don’t have permissions for apache to write to the directory.

If this is the case, then you will see an error appear in your apache log when it tries to create the file. Try tailing your logs while running the script in your browser:

tail -f /var/log/apache2/error.log 

@VenderAeloth Looks like choppyfireballs isn’t very active here, but he if he doesn’t respond then make sure you share your answer with us when you find it!

I’m not sure it’s the best way to fix it but i added this : setsebool -P allow_httpd_anon_write true in the directory when i need to write files.

I had the same trouble recently and stumbled upon this question. Unfortunately choppyfireballs the OP said in a comment he found his own solution and just accepted an answer that wasn’t helping any of us. Then after a search and a success to make file_put_contents work again I decided to share my solution.

The permissions of my files and directories were ok to accept any writing (make sure your directories are chmod 757 this will give the root and others the grant to write files in the location). If it still doesn’t work like it didn’t for me, that’s because your system is probably SELinux (Security Enhanced Linux) system.

If you want to make sure write setenforce 0 this will turn selinux to permissive mode, run your script again, if it works then it means the problem is well described.

In that case turn selinux on back setenforce 1 and try ls -Zl in the directory where the directory of your project is. this will give you a line like

drwx---r-x. 9 root root system_u:object_r:httpd_sys_content_t:s0 4096 Dec 8 00:25 project 

or something different but httpd_sys_content_t if you used chcon to transfer the context from one directory to this one. but if you don’t have httpd_sys_content_t it’s ok because we need to change the context of that directory anyways.

first you need to accept any public_content_rw_t contexts to write file. Type

setsebool -P httpd_anon_write on 

This will set (P)ermanently SELinux boolean httpd_anon_write to true and any context dubbed as public_content_rw_t will have the rights to write any files in their own location.

Now you have to say SELinux that your project directory is public_content_rw_t or you’ll still not be able to write files. Type :

semanage fcontext --add --type public_content_rw_t "/project(/.*)?" 

and restorecon -RvF /project to tell selinux to apply the above specifications.

Now your directory is public_content_rw_t and you should be able to write files.

Источник

Читайте также:  Принцип подстановки барбары лисков пример java
Оцените статью