Php temporary file cache

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.

Simple PHP caching class that uses the /tmp/ folder of a Linux system.

cajogos/php-temp-cache

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

A simple PHP caching class that uses the temporary files ( /tmp/ ) folder of a Linux distribution.

Main caching library of Biscuit Link framework.

The class has been written to be dead easy to use and should be familiar to anyone who has used any caching before. However, beware that the main aim of this cache is not to be the fastest caching mechanism out there, but to simplify the lives of those who just want to have a simple caching system in place to avoid hitting API limits, although from my experience it is pretty fast!

// $expire is time in seconds for validity. TempCache::put($key, $value, $expire);

Источник

Читайте также:  Matlab to python code converter

Кэширование контента в файлы PHP

Кэширование контента в файлы PHP

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

Код файла cache.php

 else < self::$keys[] = $name; return false; >> else < return ''; >> /** * Отправка данных в кэш. */ public static function set($content) < if (self::$enable) < $name = array_pop(self::$keys); $dir = __DIR__ . self::$path . '/'; if (!is_dir($dir)) < @mkdir($dir, 0777, true); >file_put_contents($dir . '/' . $name . '.tmp', $content); > return $content; > /** * Начало кэширования фрагмента. */ public static function begin($name) < if ($content = self::get($name)) < echo $content; return false; >else < ob_start(); return true; >> /** * Завершение кэширования фрагмента. */ public static function end() < echo self::set(ob_get_clean()); >/** * Очистка кэша. */ public static function clear() < $dir = __DIR__ . self::$path; foreach (glob($dir . '/*') as $file) < if (is_file($file)) < unlink($file); >> > >

Использование

// Подключаем файл класса require_once ‘/cache.php’; // Кэшируем фрагмент кода if (Cache::begin(‘test’)) < ?>

Теперь, если в папке cache нет файла test.tmp, то условие выполнится, контент выведется и сохранится в файле. В другом случаи контент всегда будет выводится из файла кэша.

Источник

tmpfile

Creates a temporary file with a unique name in read-write-binary (w+b) mode and returns a file handle.

The file is automatically removed when closed (for example, by calling fclose() , or when there are no remaining references to the file handle returned by tmpfile() ), or when the script ends.

If the script terminates unexpectedly, the temporary file may not be deleted.

Читайте также:  Foxpdf html to pdf converter portable

Parameters

This function has no parameters.

Return Values

Returns a file handle, similar to the one returned by fopen() , for the new file or false on failure.

Examples

Example #1 tmpfile() example

$temp = tmpfile ();
fwrite ( $temp , «writing to tempfile» );
fseek ( $temp , 0 );
echo fread ( $temp , 1024 );
fclose ( $temp ); // this removes the file
?>

The above example will output:

See Also

  • tempnam() — Create file with unique file name
  • sys_get_temp_dir() — Returns directory path used for temporary files

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’

Читайте также:  Build graph with python

(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 );
>
>
?>

Источник

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