File
File
The Hazaar File class.
Represents a file and provides methods for file manipulation, metadata handling, content filtering, encryption, and various utility functions. Supports integration with different storage backends via a Manager.
Properties
sourceFile
public string $sourceFiledefaultCipher
public string $defaultCipher = 'aes-256-ctr'defaultKey
public string $defaultKey = 'hazaar_secret_badass_key'manager
protected Manager $managerinfo
protected array $infomimeContentType
public string $mimeContentTypecontents
Any overridden file contents.
protected string $contentsThis is normally used when performing operations on the file in memory, such as resizing an image.
csvContents
public array $csvContentsresource
protected mixed $resourcerelativePath
public string $relativePathstream
private mixed $streamencrypted
private bool $encrypted__media_url
public URL $__media_urlfilters
Content filters.
private array $filtersMethods
__construct
Constructs a new File instance.
public __construct(mixed $file, ?Manager $manager, ?string $relativePath): voidParameters
| Parameter | Type | Description |
|---|---|---|
$file | mixed | The file to be managed. Can be an instance of File, a resource, or a file path. If null or empty, a temporary file path will be generated. |
$manager | Manager | Optional. The Manager instance to use for file operations. If not provided, a new Manager will be created. |
$relativePath | string | Optional. The relative path to associate with the file. |
__toString
Returns the string representation of the object.
public __toString(): stringThis magic method is called when the object is treated as a string. It delegates the conversion to the toString() method.
toString
Returns the full path of the file as a string.
public toString(): stringbackend
Retrieves the name of the backend used by the file manager.
public backend(): stringgetManager
Retrieves the associated Manager instance.
public getManager(): Managerget
Retrieves a file from the specified URL using an optional HTTP client.
public get(string $url, ?Client $client): FileThis method sends a GET request to the provided URL and, if successful, returns a File object containing the downloaded content. If the response includes a 'content-disposition' header with a filename, it will be used as the file's name. Otherwise, the filename is extracted from the URL.
Parameters
| Parameter | Type | Description |
|---|---|---|
$url | string | The URL to fetch the file from. Must include a scheme (e.g., http:// or https://). |
$client | Client | Optional HTTP client to use for the request. If not provided, a new Client is instantiated. |
registerFilter
Registers a filter callback for a specific filter type.
public registerFilter(int $type, string $callable): boolParameters
| Parameter | Type | Description |
|---|---|---|
$type | int | the filter type identifier |
$callable | string | the filter callback, either as a Closure or the name of a method on this object |
setMeta
Sets metadata for the current file.
public setMeta(array $values): boolParameters
| Parameter | Type | Description |
|---|---|---|
$values | array |
getMeta
Retrieves metadata associated with the file.
public getMeta(?string $key): mixedIf a key is provided, returns the value for that specific metadata key. If no key is provided, returns all metadata for the file.
Parameters
| Parameter | Type | Description |
|---|---|---|
$key | string | the metadata key to retrieve, or null to retrieve all metadata |
baseName
Returns the base name of the source file.
public baseName(string $suffix): stringThis method extracts the file name from the full path stored in $this->sourceFile. Optionally, a suffix can be provided to be removed from the end of the file name.
Parameters
| Parameter | Type | Description |
|---|---|---|
$suffix | string | optional suffix to remove from the file name |
dirName
Returns the directory name of the source file with consistent directory separators.
public dirName(): stringThis method replaces all backslashes with forward slashes to ensure consistency across different operating systems. It is intended for use outside of the local backend, where DIRECTORY_SEPARATOR should be used instead.
name
Retrieves the filename without its extension from the source file path.
public name(): stringfullPath
Returns the full path of the file by concatenating the directory name and the base name.
public fullPath(): stringrelativePath
Get the relative path of the file.
public relativePath(NULL $path): voidIf the file was returned from a Hazaar\File\Dir object, then it will have a stored relative path. Otherwise any file/path can be provided in the form of another Hazaar\File object, Hazaar\File\Dir object, or string path, and the relative path to the file will be returned.
Parameters
| Parameter | Type | Description |
|---|---|---|
$path | NULL | optional path to use as the relative path |
setRelativePath
Sets the relative path for the file.
public setRelativePath(string $path): voidParameters
| Parameter | Type | Description |
|---|---|---|
$path | string | the relative path to set |
extension
Retrieves the file extension from the source file path.
public extension(): stringsize
Gets the size of the file in bytes.
public size(): ?intIf the file contents are already loaded, returns the length of the contents. If the file does not exist, returns null. Otherwise, retrieves the file size from the file manager.
exists
Checks if the source file exists using the file manager.
public exists(): boolrealPath
Returns the absolute path to the source file.
public realPath(): stringisReadable
Checks if the file is readable.
public isReadable(): boolThis method first verifies if the file exists. If it does not exist, it returns false. If the file exists, it delegates the readability check to the file manager.
isWritable
Checks if the source file is writable.
public isWritable(): boolisFile
Determines if the current source represents a regular file.
public isFile(): boolChecks if the file exists and then delegates to the manager to verify if the source is a file.
isDir
Determines if the current file is a directory.
public isDir(): boolChecks if the file exists and then verifies if it is a directory using the file manager.
isLink
Determines if the current file is a symbolic link.
public isLink(): boolChecks if the file exists and then delegates to the file manager to verify if the source file is a symbolic link.
dir
Returns a Dir object representing the current file if it is a directory,
public dir(): ?Dirotherwise returns the parent directory.
parent
Returns the parent directory of the current file as a Dir object.
public parent(): Dirtype
Gets the MIME type or file type of the current file.
public type(): ?stringctime
Gets the creation time of the file.
public ctime(): ?intmtime
Gets the last modification time of the file.
public mtime(): ?inttouch
Updates the modification time of the file.
public touch(): boolChecks if the file exists before attempting to update its modification time. If the file does not exist, the method returns false. Otherwise, it delegates the operation to the file manager.
atime
Gets the last access time of the file.
public atime(): ?inthasContents
Checks if the file has any contents.
public hasContents(): boolThis method first checks if the contents property is set. If so, it returns true. If the file does not exist, it returns false. Otherwise, it checks if the file size is greater than zero to determine if the file has contents.
getContents
Retrieves the contents of the file, optionally starting from a given offset and up to a maximum length.
public getContents(int $offset = -1, ?int $maxlen): stringIf the contents have already been loaded, returns the cached contents. Otherwise, reads the contents from the source file using the manager, applies input filters, caches the result, and returns it.
Parameters
| Parameter | Type | Description |
|---|---|---|
$offset | int | The position in the file to start reading from. Defaults to -1 (read from the beginning). |
$maxlen | int | The maximum number of bytes to read. If null, reads to the end of the file. |
putContents
Put contents directly writes data to the storage backend without storing it in the file object itself.
public putContents(string $data, bool $overwrite = true): ?intNOTE: This function is called internally to save data that has been updated in the file object.
Parameters
| Parameter | Type | Description |
|---|---|---|
$data | string | The data to write |
$overwrite | bool | Overwrite data if it exists |
setContents
Sets the current contents of the file in memory.
public setContents(?string $bytes): ?intCalling this function does not directly update the content of the file "on disk". To do that you must call the File::save() method which will commit the data to storage.
Parameters
| Parameter | Type | Description |
|---|---|---|
$bytes | string | The data to set as the content |
setDecodedContents
Set the contents from an encoded string.
public setDecodedContents(string $bytes): boolCurrently this supports only data URI encoded strings. I have made this generic in case I come across other types of encodings that will work with this method.
Parameters
| Parameter | Type | Description |
|---|---|---|
$bytes | string |
getEncodedContents
Return the contents of the file as a data URI encoded string.
public getEncodedContents(): voidThis function is basically the opposite of Hazaar\File::set_decoded_contents() and will generate a data URI based on the current MIME content type and the contents of the file.
save
Saves the current in-memory content to the storage backend.
public save(): ?intInternally this calls File::putContents() to write the data to the backend.
saveAs
Saves this file objects content to another file name.
public saveAs(string $filename, bool $overwrite): ?intParameters
| Parameter | Type | Description |
|---|---|---|
$filename | string | The filename to save as |
$overwrite | bool | Boolean flag to indicate that the destination should be overwritten if it exists |
unlink
Deletes the file or directory represented by this instance.
public unlink(): boolIf the file does not exist, the method returns false. If the path is a directory, it attempts to remove the directory and its contents recursively. If the path is a file, it attempts to delete the file.
md5
Calculates and returns the MD5 checksum of the file.
public md5(): stringThis method first attempts to retrieve the MD5 checksum using the backend manager, which may provide a more efficient way to compute the checksum (e.g., for remote storage providers like Dropbox). If the backend does not provide a checksum, it falls back to calculating the MD5 hash of the file's contents directly.
base64
Returns the contents of the file encoded in base64.
public base64(): stringparseJSON
Returns the contents as decoded JSON.
public parseJSON(bool $assoc, \stdClass $): voidIf the content is a JSON encoded string, this will decode the string and return it as a stdClass object, or an associative array if the $assoc parameter is TRUE.
If the content can not be decoded because it is not a valid JSON string, this method will return FALSE.
Parameters
| Parameter | Type | Description |
|---|---|---|
$assoc | bool | Return as an associative array. Default is to use stdClass. |
$ | \stdClass |
moveTo
Moves the current file to a new destination.
public moveTo(string $destination, bool $overwrite, bool $createDest, ?Manager $dstManager): FileThis method copies the file to the specified destination and, if successful, deletes the original file. Optionally, it can overwrite existing files and create the destination directory if it does not exist. A different file manager can be specified for the destination.
Parameters
| Parameter | Type | Description |
|---|---|---|
$destination | string | the path to move the file to |
$overwrite | bool | Whether to overwrite the destination file if it exists. Default is false. |
$createDest | bool | Whether to create the destination directory if it does not exist. Default is false. |
$dstManager | Manager | optional file manager for the destination |
copyTo
Copy the file to another folder.
public copyTo(string $destination, bool $overwrite, bool $createDest, ?Manager $dstManager): FileThis differs to copy() which expects the target to be the full new file pathname.
Parameters
| Parameter | Type | Description |
|---|---|---|
$destination | string | The destination folder to copy the file into |
$overwrite | bool | overwrite the destination file if it exists |
$createDest | bool | Flag that indicates if the destination folder should be created. If the destination does not exist an error will be thrown. |
$dstManager | Manager | The destination file manager. Defaults to the same manager as the source. |
copy
Copy the file to another folder and filename.
public copy(string $destination, boolean $overwrite, boolean $createDest, NULL $dstManager): FileThis differs from copyTo which expects the target to be a folder
Parameters
| Parameter | Type | Description |
|---|---|---|
$destination | string | The destination folder and file name to copy the file into |
$overwrite | boolean | overwrite the destination file if it exists |
$createDest | boolean | Flag that indicates if the destination folder should be created. If the destination does not exist an error will be thrown. |
$dstManager | NULL | The destination file manager. Defaults to the same manager as the source. |
mimeContentType
Retrieves the MIME content type of the file.
public mimeContentType(): ?stringIf the MIME type has not been determined yet, it will be detected using the file manager and cached for future calls.
setMimeContentType
Sets the MIME content type for the file.
public setMimeContentType(string $type): voidParameters
| Parameter | Type | Description |
|---|---|---|
$type | string | The MIME content type to set (e.g., 'image/jpeg', 'application/pdf'). |
thumbnailURL
Generates a URL for the thumbnail version of the file.
public thumbnailURL(int $width = 100, int $height = 100, string $format = 'jpeg', array $params): ?stringParameters
| Parameter | Type | Description |
|---|---|---|
$width | int | The width of the thumbnail in pixels. Defaults to 100. |
$height | int | The height of the thumbnail in pixels. Defaults to 100. |
$format | string | The image format for the thumbnail (e.g., 'jpeg'). Defaults to 'jpeg'. |
$params | array | additional parameters for thumbnail generation |
previewURL
Generates a preview URL for the current file.
public previewURL(array $params): ?stringParameters
| Parameter | Type | Description |
|---|---|---|
$params | array | optional parameters to customize the preview URL |
directURL
Retrieves the direct URL to access the file.
public directURL(): ?stringmediaURL
Returns or sets the media URL for the file.
public mediaURL(null $setPath): URLIf a URL or string is provided as the parameter, it sets the media URL for the file. If no parameter is provided, it returns the current media URL if set, otherwise it generates and returns a URL based on the file's full path using the manager.
Parameters
| Parameter | Type | Description |
|---|---|---|
$setPath | null | Optional. The URL or path to set as the media URL. |
toArray
Converts the contents of the file into an array by splitting it using the specified delimiter.
public toArray(string $delimiter = '"\n"'): voidParameters
| Parameter | Type | Description |
|---|---|---|
$delimiter | string | The delimiter used to split the file contents. Defaults to a newline character ("\n"). |
readCSV
Return the CSV content as a parsed array.
public readCSV(bool $useHeader_row): voidParameters
| Parameter | Type | Description |
|---|---|---|
$useHeader_row | bool | Indicates if a header row should be parsed and used to build an associative array. In this case the keys in the returned array will be the values from the first row, which is normally a header row. |
getCSV
Returns a line from the file pointer and parse for CSV fields.
public getCSV(int $length, string $delimiter = ',', string $enclosure = '"', string $escape = '\\'): voidParameters
| Parameter | Type | Description |
|---|---|---|
$length | int | Must be greater than the longest line (in characters) to be found in the CSV file (allowing for trailing line-end characters). Otherwise the line is split in chunks of length characters, unless the split would occur inside an enclosure. Omitting this parameter (or setting it to 0 in PHP 5.1.0 and later) the maximum line length is not limited, which is slightly slower. |
$delimiter | string | the optional delimiter parameter sets the field delimiter (one character only) |
$enclosure | string | the optional enclosure parameter sets the field enclosure character (one character only) |
$escape | string | the optional escape parameter sets the escape character (one character only) |
putCSV
Writes an array to the file in CSV format.
public putCSV(array $fields, string $delimiter = ',', string $enclosure = '"', string $escape = '\\'): voidParameters
| Parameter | Type | Description |
|---|---|---|
$fields | array | Must be greater than the longest line (in characters) to be found in the CSV file (allowing for trailing line-end characters). Otherwise the line is split in chunks of length characters, unless the split would occur inside an enclosure. Omitting this parameter (or setting it to 0 in PHP 5.1.0 and later) the maximum line length is not limited, which is slightly slower. |
$delimiter | string | the optional delimiter parameter sets the field delimiter (one character only) |
$enclosure | string | the optional enclosure parameter sets the field enclosure character (one character only) |
$escape | string | the optional escape parameter sets the escape character (one character only) |
rename
Renames a file or directory.
public rename(string $newname): boolNOTE: This will not work if the file is currently opened by another process.
Parameters
| Parameter | Type | Description |
|---|---|---|
$newname | string | The new name. Must not be an absolute/relative path. If you want to move the file use File::moveTo(). |
delete
Deletes the file at the specified path.
public delete(string $path): boolCreates a new File instance for the given path and attempts to delete it.
Parameters
| Parameter | Type | Description |
|---|---|---|
$path | string | the path to the file to be deleted |
jsonSerialize
Specify data which should be serialized to JSON.
public jsonSerialize(): mixedThis method is called when an instance of this class is encoded with json_encode(). It returns the encoded contents of the file.
perms
Retrieves the permissions of the source file.
public perms(): ?intchmod
Changes the permissions of the source file to the specified mode.
public chmod(int $mode): boolParameters
| Parameter | Type | Description |
|---|---|---|
$mode | int | the new permissions mode (in octal) |
isEncrypted
Checks if the file is encrypted by verifying its BOM (Byte Order Mark).
public isEncrypted(): boolThis method attempts to open the file and read the first three bytes. If the bytes match the expected BOM (packed from the hex string 'BADA55'), the file is considered encrypted.
encrypt
Encrypts the file by setting the encrypted flag and saving the file.
public encrypt(): booldecrypt
Decrypts the file contents.
public decrypt(): boolRetrieves the current contents of the file, marks the file as not encrypted, and writes the contents back to the file. Returns true if the operation was successful.
isOpen
Checks if the file stream is currently open.
public isOpen(): boolopen
Opens a file stream with the specified mode.
public open(string $mode): mixedParameters
| Parameter | Type | Description |
|---|---|---|
$mode | string | The mode in which to open the file (e.g., 'r', 'w', 'a'). |
read
Reads a specified number of bytes from the file stream.
public read(int $length): stringParameters
| Parameter | Type | Description |
|---|---|---|
$length | int | the number of bytes to read from the stream |
write
Writes data to the file stream.
public write(string $bytes, int $length): intParameters
| Parameter | Type | Description |
|---|---|---|
$bytes | string | the data to write to the stream |
$length | int | the number of bytes to write |
seek
Seeks to a specific position in the file stream.
public seek(int $offset, int $whence = 'SEEK_SET'): intParameters
| Parameter | Type | Description |
|---|---|---|
$offset | int | the offset to seek to |
$whence | int | The seek method. Defaults to SEEK_SET. Possible values: - SEEK_SET: Set position equal to offset bytes. - SEEK_CUR: Set position to current location plus offset. - SEEK_END: Set position to end-of-file plus offset. |
tell
Returns the current position of the file pointer.
public tell(): inteof
Checks if the end of the file (EOF) has been reached for the current stream.
public eof(): booltruncate
Truncates the file stream to the specified size.
public truncate(int $size): boolParameters
| Parameter | Type | Description |
|---|---|---|
$size | int | the size, in bytes, to truncate the file to |
lock
Attempts to acquire a lock on the file stream.
public lock(int $operation, ?int $wouldblock): boolParameters
| Parameter | Type | Description |
|---|---|---|
$operation | int | The locking operation (e.g., LOCK_SH, LOCK_EX). |
$wouldblock | int |
flush
Flushes the current file stream.
public flush(): boolIf the stream is not initialized, the method returns false. Otherwise, it attempts to flush the stream using the manager.
gets
Reads a line from the file stream.
public gets(?int $length): stringIf a length is specified, reads up to that number of bytes from the stream. Returns the read string, or false if the stream is not available.
Parameters
| Parameter | Type | Description |
|---|---|---|
$length | int | Optional. Maximum number of bytes to read. |
close
Closes the file stream if it is open.
public close(): boolgetResponseObject
Returns a Response object for this file.
public getResponseObject(): ResponseThis method creates and returns a new Response\File object, which can be used to send the file as an HTTP response.
filterIn
Internal content filter.
protected filterIn(string $content): boolChecks if the content is modified in some way using a BOM mask. Currently this is used to determine if a file is encrypted and automatically decrypts it if an encryption key is available.
Parameters
| Parameter | Type | Description |
|---|---|---|
$content | string |
filterOut
Internal content filter.
protected filterOut(string $content): boolChecks if the content is modified in some way using a BOM mask. Currently this is used to determine if a file is encrypted and automatically decrypts it if an encryption key is available.
Parameters
| Parameter | Type | Description |
|---|---|---|
$content | string |
getEncryptionKey
Retrieves the encryption key used for file operations.
private getEncryptionKey(): stringThis method attempts to load the encryption key from a configuration file named '.key'. If the file exists, its contents are read and trimmed for whitespace. If the file does not exist, a default key defined in the File class is used instead. The resulting key is then hashed using MD5 before being returned.
Generated by Hazaar API Doc Generator on Sun, 01 Mar 2026 09:22:26 +0000