Ввод имени файла php

Форма ввода php

Язык программирования PHP позволяет делать и обрабатывать пользовательские формы фактически любой сложности. В этой статье я научу вас создавать и обрабатывать формы.Для начала рассмотрим принцип работы форм и из чего они состоят. Форма представляет собой html код с различными полями ввода, которые заполняет пользователь. После нажатия кнопки отправки формы происходит передача значений всех полей формы обработчику этой формы. Отправка осуществляется методом POST или GET. По умолчанию используется GET. Рассмотрим простой пример,форма отправки имени,фамилии и номера телефона: Файл forma.html

В теге form указан путь к обработчику и метод передачи данных. Параметр enctype позволяет передавать через форму файлы. Например если нам нужно приложить к форме какой-нибудь документ-то этот атрибут обязателен. Тэги input — это элементу формы. Какой элемент-зависит от атрибута type. Теперь код обработчика. Файл action.php

Это простейший пример php формы.В реал конечно же никому не интересно заполнять форму лишь для того, чтобы потом посмотреть что же вы заполнили. Чаще всего полученную информацию заносят в базу данных,отправляют на почту или записывают в файл. Мы рассмотрим все три случая. Начнем с простого-запись в файл. Менять будем только обработчик.

Форма с записью результата в файл

Форма с записью результата в базу данных MySql

В случае с базой чуть посложнее. Тут очень важен момент безопасности. Данные необходимо профильтровать и лишь потом занести в БД, иначе злоумышленник может провести SQL инъекцию и уничтожить вашу базу данных.Обязательно используйте функцию mysql_real_escape_string. Пишем обработчик:

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

Форма с отправкой e-mail средствами php

Опять правим форму. На этот раз экранируем ненужные символы для безопасного отображения в браузере. Используется для этого функция htmlspecialchars.

Вот и всё. Если делаете форму, доступную для посетителей сайта-обязательно используйте капчу. Качайте исходники, разбирайтесь. Пишите комментарии, задавайте вопросы.

Источник

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

Набор PHP функций для работы с путями и именами файлов.

Получить имя файла

echo basename('path/file.png'); // file.png

Имя файла без расширения

$info = pathinfo('path/file.png'); echo $info['filename']; // file /* или */ echo pathinfo('path/donut.png', PATHINFO_FILENAME); // file

Получить расширение файла

echo mb_strtolower(mb_substr(mb_strrchr('path/file.png', '.'), 1)); // png /* или */ echo pathinfo('path/file.png', PATHINFO_EXTENSION); // png

Заменить расширение файла

Заменить расширение .jpeg на .jpg:

$file_name = 'file.jpeg'; $file_new = preg_replace('/\.jpeg$/', '.jpg', $file_name); echo $file_new; // file.jpg

Заменить несколько расширений на одно (.jpg, .jpeg, .png на .webp):

$file_name = 'file.jpeg'; $file_new = preg_replace('/\.(jpg|jpeg|png)$/', '.webp', $file_name); echo $file_new; // file.webp

Дописать текст в конец названия файла

$info = pathinfo('path/file.png'); $name = $info['dirname'] . '/' . $info['filename'] . '-' . time() . '.' . $info['extension']; echo $name; // path/file-1610877618.png

Безопасное сохранение файла

Чтобы не затереть существующий файл на сервере можно применить данную функцию.

В функцию передаётся путь и имя файла, если на сервере уже существует такой файл, функция к концу файла приписывает префикс. Также если директория не существует, пытается её создать.

function safe_file($filename) < $dir = dirname($filename); if (!is_dir($dir)) < mkdir($dir, 0777, true); >$info = pathinfo($filename); $name = $dir . '/' . $info['filename']; $prefix = ''; $ext = (empty($info['extension'])) ? '' : '.' . $info['extension']; if (is_file($name . $ext)) < $i = 1; $prefix = '_' . $i; while (is_file($name . $prefix . $ext)) < $prefix = '_' . ++$i; >> return $name . $prefix . $ext; > // Если в директории есть файл log.txt, файл будет сохранен с названием log_1.txt file_put_contents(safe_file(__DIR__ . '/log.txt'), $text);

Источник

Читайте также:  Html header content length

fopen

fopen() binds a named resource, specified by filename , to a stream.

Parameters

If filename is of the form «scheme://. «, it is assumed to be a URL and PHP will search for a protocol handler (also known as a wrapper) for that scheme. If no wrappers for that protocol are registered, PHP will emit a notice to help you track potential problems in your script and then continue as though filename specifies a regular file.

If PHP has decided that filename specifies a local file, then it will try to open a stream on that file. The file must be accessible to PHP, so you need to ensure that the file access permissions allow this access. If you have enabled open_basedir further restrictions may apply.

If PHP has decided that filename specifies a registered protocol, and that protocol is registered as a network URL, PHP will check to make sure that allow_url_fopen is enabled. If it is switched off, PHP will emit a warning and the fopen call will fail.

Note:

The list of supported protocols can be found in Supported Protocols and Wrappers. Some protocols (also referred to as wrappers ) support context and/or php.ini options. Refer to the specific page for the protocol in use for a list of options which can be set. (e.g. php.ini value user_agent used by the http wrapper).

On the Windows platform, be careful to escape any backslashes used in the path to the file, or use forward slashes.

The mode parameter specifies the type of access you require to the stream. It may be any of the following:

A list of possible modes for fopen() using mode
mode Description
‘r’ Open for reading only; place the file pointer at the beginning of the file.
‘r+’ Open for reading and writing; place the file pointer at the beginning of the file.
‘w’ Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
‘w+’ Open for reading and writing; otherwise it has the same behavior as ‘w’ .
‘a’ Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() has no effect, writes are always appended.
‘a+’ Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() only affects the reading position, writes are always appended.
‘x’ Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning false and generating an error of level E_WARNING . If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call.
‘x+’ Create and open for reading and writing; otherwise it has the same behavior as ‘x’ .
‘c’ Open the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to ‘w’ ), nor the call to this function fails (as is the case with ‘x’ ). The file pointer is positioned on the beginning of the file. This may be useful if it’s desired to get an advisory lock (see flock() ) before attempting to modify the file, as using ‘w’ could truncate the file before the lock was obtained (if truncation is desired, ftruncate() can be used after the lock is requested).
‘c+’ Open the file for reading and writing; otherwise it has the same behavior as ‘c’ .
‘e’ Set close-on-exec flag on the opened file descriptor. Only available in PHP compiled on POSIX.1-2008 conform systems.

Note:

Different operating system families have different line-ending conventions. When you write a text file and want to insert a line break, you need to use the correct line-ending character(s) for your operating system. Unix based systems use \n as the line ending character, Windows based systems use \r\n as the line ending characters and Macintosh based systems (Mac OS Classic) used \r as the line ending character.

If you use the wrong line ending characters when writing your files, you might find that other applications that open those files will «look funny».

Windows offers a text-mode translation flag ( ‘t’ ) which will transparently translate \n to \r\n when working with the file. In contrast, you can also use ‘b’ to force binary mode, which will not translate your data. To use these flags, specify either ‘b’ or ‘t’ as the last character of the mode parameter.

The default translation mode is ‘b’ . You can use the ‘t’ mode if you are working with plain-text files and you use \n to delimit your line endings in your script, but expect your files to be readable with applications such as old versions of notepad. You should use the ‘b’ in all other cases.

If you specify the ‘t’ flag when working with binary files, you may experience strange problems with your data, including broken image files and strange problems with \r\n characters.

Note:

For portability, it is also strongly recommended that you re-write code that uses or relies upon the ‘t’ mode so that it uses the correct line endings and ‘b’ mode instead.

Note: The mode is ignored for php://output , php://input , php://stdin , php://stdout , php://stderr and php://fd stream wrappers.

The optional third use_include_path parameter can be set to ‘1’ or true if you want to search for the file in the include_path, too.

Читайте также:  Java main return error

Источник

Ввод имени файла php

I think the way an array of attachments works is kind of cumbersome. Usually the PHP guys are right on the money, but this is just counter-intuitive. It should have been more like:

Array
(
[0] => Array
(
[name] => facepalm.jpg
[type] => image/jpeg
[tmp_name] => /tmp/phpn3FmFr
[error] => 0
[size] => 15476
)

Anyways, here is a fuller example than the sparce one in the documentation above:

foreach ( $_FILES [ «attachment» ][ «error» ] as $key => $error )
$tmp_name = $_FILES [ «attachment» ][ «tmp_name» ][ $key ];
if (! $tmp_name ) continue;

$name = basename ( $_FILES [ «attachment» ][ «name» ][ $key ]);

if ( $error == UPLOAD_ERR_OK )
if ( move_uploaded_file ( $tmp_name , «/tmp/» . $name ) )
$uploaded_array [] .= «Uploaded file ‘» . $name . «‘.
\n» ;
else
$errormsg .= «Could not move uploaded file ‘» . $tmp_name . «‘ to ‘» . $name . «‘
\n» ;
>
else $errormsg .= «Upload error. [» . $error . «] on file ‘» . $name . «‘
\n» ;
>
?>

Do not use Coreywelch or Daevid’s way, because their methods can handle only within two-dimensional structure. $_FILES can consist of any hierarchy, such as 3d or 4d structure.

The following example form breaks their codes:

As the solution, you should use PSR-7 based zendframework/zend-diactoros.

use Psr \ Http \ Message \ UploadedFileInterface ;
use Zend \ Diactoros \ ServerRequestFactory ;

$request = ServerRequestFactory :: fromGlobals ();

if ( $request -> getMethod () !== ‘POST’ ) http_response_code ( 405 );
exit( ‘Use POST method.’ );
>

$uploaded_files = $request -> getUploadedFiles ();

if (
!isset( $uploaded_files [ ‘files’ ][ ‘x’ ][ ‘y’ ][ ‘z’ ]) ||
! $uploaded_files [ ‘files’ ][ ‘x’ ][ ‘y’ ][ ‘z’ ] instanceof UploadedFileInterface
) http_response_code ( 400 );
exit( ‘Invalid request body.’ );
>

Читайте также:  Php warning module ldap already loaded in unknown on line 0

$file = $uploaded_files [ ‘files’ ][ ‘x’ ][ ‘y’ ][ ‘z’ ];

if ( $file -> getError () !== UPLOAD_ERR_OK ) http_response_code ( 400 );
exit( ‘File uploading failed.’ );
>

$file -> moveTo ( ‘/path/to/new/file’ );

The documentation doesn’t have any details about how the HTML array feature formats the $_FILES array.

Array
(
[document] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)
)

Multi-files with HTML array feature —

Array
(
[documents] => Array
(
[name] => Array
(
[0] => sample-file.doc
[1] => sample-file.doc
)

[type] => Array
(
[0] => application/msword
[1] => application/msword
) [tmp_name] => Array
(
[0] => /tmp/path/phpVGCDAJ
[1] => /tmp/path/phpVGCDAJ
)

The problem occurs when you have a form that uses both single file and HTML array feature. The array isn’t normalized and tends to make coding for it really sloppy. I have included a nice method to normalize the $_FILES array.

function normalize_files_array ( $files = [])

foreach( $files as $index => $file )

if (! is_array ( $file [ ‘name’ ])) $normalized_array [ $index ][] = $file ;
continue;
>

foreach( $file [ ‘name’ ] as $idx => $name ) $normalized_array [ $index ][ $idx ] = [
‘name’ => $name ,
‘type’ => $file [ ‘type’ ][ $idx ],
‘tmp_name’ => $file [ ‘tmp_name’ ][ $idx ],
‘error’ => $file [ ‘error’ ][ $idx ],
‘size’ => $file [ ‘size’ ][ $idx ]
];
>

?>

The following is the output from the above method.

Array
(
[document] => Array
(
[0] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)

[documents] => Array
(
[0] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
) [1] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)

Источник

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