Php script to edit files on server

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Small PHP Code Editor for editing text files on a web server

License

simon-thorpe/editor

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Читайте также:  Единицы измерения

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

This project is a single PHP file that can be uploaded to a webserver. It will then allow browsing and editing of files using an HTML5 editor (no browser plugins required).

The purpose of this project is to allow code editing/deleting/uploading on shared web space where FTP or other means of editing is unavailable or not practical (such as a Chromebook).

  • No IDE software needs to be installed
  • No complex firewall rules
  • HTML5 only — perfect for Chrome OS

Upload the editor.php file (in the dist/ directory) to the root of your web space then point your browser to http://yoursite.com/editor.php and login to edit files. Default password is ‘admin’.

cd public_html wget https://raw.githubusercontent.com/simon-thorpe/editor/master/dist/editor.php 

Some content management systems allow creating simple text files. All you need to do is create a file editor.php (or any name you like) then paste the contents of dist/editor.php into that file.

git clone https://github.com/simon-thorpe/editor.git cd editor npm install # edit dev files in src dir grunt # built file is in dist dir 

Uploading a file to the server

curl yoursite.com/editor.php -s -H "Cookie: editor-auth=yourpass" -F p=/home/yoursite/public_html/calendar.json -F 'content= 

About

Small PHP Code Editor for editing text files on a web server

Источник

Edit and save a file on server (PHP)

Script: PHP file: I expect for the C++ file of a text file at this point to get save with the content in the . How can I send back the contents to the script and save it to the same file or to a file with a new name? PHP, HTML file:

Edit and save a file on server (PHP)

I have a page that displays the content of a C++ file into a textarea and I need to be able to save the contents of it using a script. (The C++ file does not have to be configured just saved.)

I'm using a PHP script to load the code from a file to display it on the textarea . How can I send back the contents to the script and save it to the same file or to a file with a new name?

function savefiles() < var contentArea = document.getElementsById('cpp_content'); var cpp_content = contentArea.value; var request = new XMLHttpRequest(); request.open('POST', '/php/save_contents.php', true); request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); request.onload = function() < if (this.status >= 200 && this.status < 400) < console.log("Success"); var resp = this.response; >else < alert ("Target server reached, but it returned an error" ); >>; request.onerror = function() < // There was a connection error of some sort >; request.send(cpp_content); > 

I expect for the C++ file of a text file at this point to get save with the content in the textarea .

 $file = file_get_contents($fn); ?>   

ig @WookieeTyler

">

Another option would be to send the contents to a separated PHP file through an XMLHttpRequest. This way you don't have to reload the page when saving. Something like this:

var request = new XMLHttpRequest(); request.open('POST', '/my/url/save_contents.php', true); request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); request.onload = function() < if (this.status >= 200 && this.status < 400) < // Success! var resp = this.response; >else < // We reached our target server, but it returned an error >>; request.onerror = function() < // There was a connection error of some sort >; request.send('cpp_content=' + cpp_content); 

Uploaded file doesnt get saved in the server in php,

Php Tutorial how to File Upload and save into a folder html5

PHP Beginners tutorial uploading files from pc to remote server folder real time example.
Duration: 10:39

PHP File Upload Example

In this quick PHP file upload example we create an upload form in HTML for the browser to
Duration: 6:35

Saving file to server using PHP and Javascript

I have a data string in Javascript and I would like to store it in a text file in my server.

The normal thing to do is to send the data to a PHP medium file to process it and do the file storage part.

This is the code I used but it looks like it doesn't run at all as the destination file matrice.txt is still blank :

What is the problem and how can I fix it ?

First thing to note: You're calling the callback as many times as there are elements on sort_data array, which I believe it's not the intended functionality.

Also, you should really check if your ajax() call was successful or not. Ajax call has a parameter method (instead of type ) according to the documentation.

Finally, you could write to a file with a one-liner.

So, let's put it all together:

script.js

function finalCoords() < var matrix = []; for(var i = 0; i < sort_data.length; i++) < matrix.push([data.nodes[i].name, sort_data[i].x, sort_data[i].y, sort_data[i].z]); /* This data is collected from other arrays */ >var matrixStr = matrix.join(" "); /* This is the string I want to store */ console.log(matrixStr); $.ajax(< url: "matrice.php", /* This is the PHP Medium */ data: matrixStr, cache: false, async: true, method: 'POST', timeout : 5000 >) .done(function() < console.log("success"); >) .fail(function() < console.log("error"); >) .always(function() < console.log("complete"); >); > 

matrice.php

That should do the trick and tell if there are any errors with the ajax call.

EDIT

Taking a cue from the comment from charlietfl (thanks, btw), we should take the raw post data:

Php save file to specific location?, Try this:

How to collect file and save on server with PHP

I know this similar question is asked before, but I can't find a solution to my specific problem. I have this code, and it saves to a file and downloads it immediately to the desktop when run from the browser. But I need it to save it on a server. How do I do this with this specific code?

Do I need to save the file into a variable e.g. $files first?

Executed, it behaves like we expect:

% php output.php hey F4LLCON! 

Now I'll modify it to add output buffering and save to the file and write to stdout (using regular echo calls!):

After executing, the output in the file catched.txt is equal to what we got earlier (and still get) on stdout:

Now I'll modify it again to show how generators from PHP 5.5 will provide you with an elegant solution that doesn't need to sacrifice performance (the previous solution requires you to save all the intermediate content in one giant output buffer):

; $f = fopen("/tmp/catched2.txt", "wb"); foreach ($main() as $chunk) < fwrite($f, $chunk); echo $chunk; >fclose($f); ?> 

We aren't storing everything in one giant buffer, and we can still output to file and stdout simultaneously.

If you don't understand generators, here's a solution where we pass a callback "print" function to main(), and that function is used every time we want to output (only one time here).

; $f = fopen("/tmp/catched3.txt", "wb"); $main(function($output) use ($f) < fwrite($f, $output); echo $output; >); fclose($f); ?> 

Load a file, edit it and the save it (server side) PHP, Try it out yourself, and consider this as the base for a more complex system. If you want to create a new file, just enter a new filename in the

Источник

Работа с файлами в PHP

С помощью функции file_get_contents() можно получить содержимое файла:

Также мы можем получить html-код какой-либо страницы в интернете:

'; echo file_get_contents('https://ya.ru'); echo '';

Но работает это далеко не для всех сайтов, у многих есть защита от такого примитивного парсинга.

Чтение файла: file()

Функция file() позволяет получить содержимое файла в виде массива. Разделителем элементов является символ переноса строки.

Создадим в корне сайта файл data.txt со следующим содержимым:

Теперь запустим скрипт index.php со следующим кодом:

При запуске этого скрипта мы получим в браузере:

array(3) < [0]=>string(7) "Vasya " [1]=> string(7) "Petya " [2]=> string(5) "Gosha" >

Заметили, что у первых двух строк длина 7 символов вместо пяти? Это из-за того, что каждая строка содержит в конце символы переноса строки.

Чаще всего они нам не нужны, поэтому их можно убрать, передав вторым параметром константу FILE_IGNORE_NEW_LINES :

Теперь у всех строк будет по 5 символов.

Если нам необходимо получить только заполненные строки в файле и пропустить пустые, можно передать вторым параметром константу FILE_SKIP_EMPTY_LINES :

Разумеется, мы можем передать сразу две константы:

Создание файла и запись в файл: file_put_contents()

Функция file_put_contents() позволяет создать файл и заполнить его данными.

Первым параметром функция принимает путь к файлу, вторым - строку с данными. Для создания пустого файла нужно передать вторым параметром пустую строку.

Если файла не существует - он будет создан. Если существует - данные в файле будут перезаписаны.

Чтобы не перезаписывать данные, а добавить их в конец файла, нужно передать третьим параметром константу FILE_APPEND :

Также вторым параметром можно передать массив:

Но этот вариант не очень удобен, поскольку все элементы массива запишутся подряд, без каких-либо разделителей. Чтобы их добавить, можно использовать функцию implode:

Создание папки или структуры папок

Создать папку можно с помощью функции mkdir() (make directory):

Вторым параметром указываются права доступа к файлу в виде восьмеричного числа, по-умолчанию это 0777 , что означает самые широкие права. Для Windows этот аргумент игнорируется.

Кроме этого, второй параметр может игнорироваться при заданной umask (пользовательская маска (user mask), которая нужна для определения конечных прав доступа). В этом случае принудительно сменить права можно функцией chmod() :

Также мы можем создать структуру папок рекурсивно, для этого нужно третьим параметром передать true :

Но в этом случае права доступа будут заданы только для конечной папки. Для изменения прав у каждой из папок придётся указывать права вручную:

Права доступа - это отдельная объёмная тема, поэтому сейчас мы её пока рассматривать не будем.

Проверка существования файла или папки

Проверить существование папки или файла можно с помощью функции file_exists() :

Если вы хотите проверить существование только папки или только файла, для этого есть специальные функции is_dir() и is_file() :

Проверка прав доступа

Функции is_readable() и is_writable() проверяют, есть ли у пользователя, от имени которого запущен PHP, права на чтение и запись файла или папки:

Копирование, перенос и удаление файла

Для удаления файлов используется функция unlink() :

Чтобы скопировать файл, используем функцию copy() :

Для переименования и переноса файла в другую папку используется функция rename() :

Работа с файлами с помощью fopen()

Функций file() , file_get_contents() и file_put_contents() достаточно для решения большинства задач, связанных с управлением файлами.

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

Итак, открыть (или создать и открыть) файл можно с помощью функции fopen() :

Функция fopen() возвращает так называемый лескриптор. Это ссылка, указатель на файл, его мы будем передавать в другие функции. Кстати, тип данных этого дескриптора - resource .

Первым параметром мы передаём путь к файлу, вторым - модификатор доступа к файлу. Ниже перечислены наиболее популярные модификаторы:

  • r - открытие для чтения, указатель переходит в начало файла.
  • r+ - открытие для чтения и записи, указатель переходит в начало файла.
  • w - открытие для записи, указатель переходит в начало файла. Если файла нет - создаётся, если есть - очищается от данных.
  • w+ - открытие для чтения и записи, в остальном аналогичен w .
  • a - открытие для записи, указатель переходит в конец файла. Если файла нет - создаётся.
  • a+ - открытие для чтения и записи, в остальном аналогичен a .
  • x - создание и открытие для записи, указатель переходит в начало файла. Если файл существует - PHP покажет ошибку.
  • x+ - создание и открытие для чтения и записи, в остальном аналогичен x .

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

Для записи данных в файл существует функция fwrite() . Давайте попробуем создать файл и записать в него какие-нибудь данные:

Заметьте, из-за модификатора w при каждом запуске скрипта данные в файле стираются и добавляются заново. Если модификатор заменить на a , данные будут не перезаписываться, а добавляться в конец файла.

Для построчного чтения файла используется функция fgets() :

При каждом запуске fgets получает следующую строку и возвращает её в $line . Вторым параметром передаётся максимальная длина строки. Это означает, что если строка слишком длинная, она будет обрезана.

Также в PHP существует множество других полезных функций, работающих с дескриптором файла. Почитать о них можно в документации.

Источник

Оцените статью