Php путь до временных файлов

Vesta Control Panel — Forum

Например я загружаю фал на сервер.
В php.ini не указана папка хранения временных файлов при загрузке.

В итоге временные файлы находятся по данным возвращаемым скриптом php в:

/home/admin/web/мойсайт.ru/public_html/

Мне нужно чтобы временные файлы и итоговый файл были в одной папке ( она у меня ramdisk) по адресу:

/home/admin/web/мойсайт.ru/public_html/memory_cards_server/

1)Как это правильно сделать в php.ini для временных файлов
2)Как указать путь в скрипте php для сохранения файла.

Нужно для увеличения скорости работы за счет использования Ramdisk так как будут приходить постоянно новые файлы и их загружать с сервера будут достаточно активно.

Mr.Erbutw Posts: 1040 Joined: Tue Apr 29, 2014 10:05 pm
Os: CentOS 6x Web: apache + nginx

Re: Как правильно указывать пути в php.ini

Post by Mr.Erbutw » Thu Jun 25, 2015 8:04 pm

illusion wrote: Например я загружаю фал на сервер.
В php.ini не указана папка хранения временных файлов при загрузке.

upload_tmp_dir string

Временная директория, используемая для хранения файлов во время закачивания. Должна быть доступна для записи пользователю, от имени которого запущен PHP. Если не указана, используется директория по умолчанию для вашей системы.

Re: Как правильно указывать пути в php.ini

Post by illusion » Thu Jun 25, 2015 8:52 pm

Я хотел узнать как мне путь указывать в upload_tmp_dir , а также путь в php скрипте, который принимает файл:
1) так

 /home/admin/web/мойсайт.ru/public_html/memory_cards_server/

или еще как то по другому?

Источник

sys_get_temp_dir

Возвращает путь к директории, где PHP по умолчанию хранит временные файлы.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Возвращает путь к директории временных файлов.

Примеры

Пример #1 Пример использования sys_get_temp_dir()

// Создание временного файла в директории
// временных файлов, используя sys_get_temp_dir()
$temp_file = tempnam ( sys_get_temp_dir (), ‘Tux’ );

Результатом выполнения данного примера будет что-то подобное:

Смотрите также

User Contributed Notes 11 notes

If running on a Linux system where systemd has PrivateTmp=true (which is the default on CentOS 7 and perhaps other newer distros), this function will simply return «/tmp», not the true, much longer, somewhat dynamic path.

As of PHP 5.5.0, you can set the sys_temp_dir INI setting so that this function will return a useful value when the default temporary directory is not an option.

This function does not always add trailing slash. This behaviour is inconsistent across systems, so you have keep an eye on it.

It’s not documented but this function does not send the path with trailing spaces, actually it drops the slash if it exists.

it should be mentioned that the return value of sys_get_temp_dir() can be set using the ini-directive ‘sys_temp_dir’ globally as well as per directory by using
php_admin_value sys_temp_dir /path/to/tmp

A very helpful thing to note when on Linux:

If you are running PHP from the commandline you can use the environment variable: TMPDIR — to change the location without touching php.ini. — This should work on most versions of PHP.

Example file: test.php
echo sys_get_temp_dir () . PHP_EOL ;
?>

And then running:

TMPDIR=/custom/location php test.php
/custom/location

This function does not account for virtualhost-specific modifications to the temp path and/or open_basedir:


php_admin_value open_basedir /home/user
php_admin_value upload_tmp_dir /home/user/tmp
php_admin_value session.save_path /home/user/tmp

Within this config it still returns /tmp

That is important for the purposes of building paths through concatenation to know that sys_get_temp_dir does not include a path separator at the end.

So, sys_get_temp_dir() will return whatever your temp dir is set to, by default:

If you attempted to concatenate another dir name temp and use the following:

That would actually attempt to generate:
/tmpsome_dir

It would likely result in a permission error unless you are running a php script as a super user.

Instead you would want to do:
mkdir( sys_get_temp_dir() . DIRECTORY_SEPARATOR. ‘some_dir’ );

which would create:
/tmp/some_dir

I don’t know if Windows or other platforms include a directory separator at the end. So if you are writing something a bit more general you may want to check for the path separator at the end and if it is not there append it.

On windows, when PHP is used as CLI, this function will return the temp directory for the current user e.g. C:\Users\JohnSmith\AppData\Local\Temp\9 instead of C:\Windows\Temp.

Источник

tmpfile

Создаёт временный файл с уникальным именем, открывая его в режиме бинарного чтения и записи (w+b) и возвращает файловый указатель.

Этот файл автоматически удаляется после закрытия (например, путём вызова функции fclose() или если не осталось ни одной ссылки на указатель файла, возвращаемый tmpfile() ), или при завершении работы скрипта.

Если скрипт неожиданно завершится, временный файл не может быть удалён.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Возвращает дескриптор файла, аналогичный тому, который возвращает функция fopen() для новых файлов или false в случае возникновения ошибки.

Примеры

Пример #1 Пример использования функции tmpfile()

$temp = tmpfile ();
fwrite ( $temp , «записываем во временный файл» );
fseek ( $temp , 0 );
echo fread ( $temp , 1024 );
fclose ( $temp ); // происходит удаление файла
?>

Результат выполнения данного примера:

записываем во временный файл

Смотрите также

User Contributed Notes 7 notes

To get the underlying file path of a tmpfile file pointer:

$file = tmpfile ();
$path = stream_get_meta_data ( $file )[ ‘uri’ ]; // eg: /tmp/phpFx0513a

I found this function useful when uploading a file through FTP. One of the files I was uploading was input from a textarea on the previous page, so really there was no «file» to upload, this solved the problem nicely:

# Upload setup.inc
$fSetup = tmpfile ();
fwrite ( $fSetup , $setup );
fseek ( $fSetup , 0 );
if (! ftp_fput ( $ftp , «inc/setup.inc» , $fSetup , FTP_ASCII )) echo «
Setup file NOT inserted

» ;
>
fclose ( $fSetup );
?>

The $setup variable is the contents of the textarea.

And I’m not sure if you need the fseek($temp,0); in there either, just leave it unless you know it doesn’t effect it.

Since this function may not be working in some environments, here is a simple workaround:

function temporaryFile($name, $content)
$file = DIRECTORY_SEPARATOR .
trim(sys_get_temp_dir(), DIRECTORY_SEPARATOR) .
DIRECTORY_SEPARATOR .
ltrim($name, DIRECTORY_SEPARATOR);

register_shutdown_function(function() use($file) unlink($file);
>);

at least on Windows 10 with php 7.3.7, and Debian Linux with php 7.4.2,

the mode is not (as the documentation states) ‘w+’ , it is ‘w+b’

(an important distinction when working on Windows systems)

To get tmpfile contents:
$tmpfile = tmpfile ();
$tmpfile_path = stream_get_meta_data ( $tmpfile )[ ‘uri’ ];
// . write to tmpfile .
$tmpfile_content = file_get_contents ( $tmpfile_path );
?>

Perhaps not the best way for production code, but good enough for logging or a quick var_dump() debug run.

No, the fseek() is necessary — after writing to the file, the file pointer (I’ll use «file pointer» to refer to the current position in the file, the thing you change with fseek()) is at the end of the file, and reading at the end of the file gives you EOF right away, which manifests itself as an empty upload.

Where you might be getting confused is in some systems’ requirement that one seek or flush between reading and writing the same file. fflush() satisfies that prerequisite, but it doesn’t do anything about the file pointer, and in this case the file pointer needs moving.

Beware that PHP’s tmpfile is not an equivalent of unix’ tmpfile.
PHP (at least v. 5.3.17/linux I’m using now) creates a file in /tmp with prefix «php», and deletes that file on fclose or script termination.
So, if you want to be sure that you don’t leave garbage even in case of a fatal error, or killed process, you shouldn’t rely on this function.
Use the classical method of deleting the file after creation:
$fn = tempnam ( ‘/tmp’ , ‘some-prefix-‘ );
if ( $fn )
$f = fopen ( $fn , ‘w+’ );
unlink ( $fn ); // even if fopen failed, because tempnam created the file
if ( $f )
do_something_with_file_handle ( $f );
>
>
?>

Источник

Читайте также:  Как сократить число после запятой python
Оцените статью