Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,20 +36,24 @@ use InitPHP\Upload\File;
use InitPHP\Upload\Adapters\LocalAdapter;

$adapter = new LocalAdapter([
'dir' => __DIR__ . '/uploads/',
'url' => 'https://example.com/uploads/',
'dir' => '/var/app/storage/uploads/', // outside the web root
'url' => 'https://example.com/uploads/', // served read-only, scripts never executed
], [
'allowed_extensions' => ['jpg', 'jpeg', 'png', 'webp'],
'allowed_mime_types' => ['image/jpeg', 'image/png', 'image/webp'], // real type, via finfo
'allowed_max_size' => 2 * 1024 * 1024, // 2 MB, in bytes
]);

$upload = new Upload($adapter);

foreach (File::setPost('photos') as $file) {
// Never store under the client's file name: generate one (the extension is kept).
$file->rename(bin2hex(random_bytes(16)));

$stored = $upload->setFile($file)->to();

if ($stored !== false) {
echo 'Uploaded to: ' . $stored->getURL();
echo 'Uploaded to: ' . htmlspecialchars((string) $stored->getURL(), ENT_QUOTES, 'UTF-8');
}
}
```
Expand Down Expand Up @@ -107,6 +111,12 @@ Pass these as the second constructor argument of any adapter (an empty array or
A file that violates any restriction — or whose upload errored — makes `to()`
throw an `UploadException`.

> **Security:** with no options set, **every** extension and type is accepted, and
> the file is stored under the name the client sent. Always set
> `allowed_extensions` and `allowed_mime_types` to an allow-list, `rename()` each
> file, and keep `dir` outside the web root. See
> [Security Best Practices](docs/Security-Best-Practices.md).

## Renaming

```php
Expand Down
2 changes: 1 addition & 1 deletion docs/Error-Handling.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ use InitPHP\Upload\Adapters\FTPAdapter;
use InitPHP\Upload\Exceptions\UnsupportedException;

try {
$adapter = new FTPAdapter($credentials);
$adapter = new FTPAdapter($credentials, $options); // $options: your allow-lists, see Validation
} catch (UnsupportedException $e) {
// ext-ftp is not installed: "FTP adapter cannot be used on your server."
}
Expand Down
16 changes: 14 additions & 2 deletions docs/FTP-Adapter.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,11 @@ $adapter = new FTPAdapter(
'passive' => true,
],
[
'allowed_max_size' => 10 * 1024 * 1024,
// With no allow-list, every extension is accepted and the file lands in
// the publicly served `url` tree. Always restrict what can be stored.
'allowed_extensions' => ['jpg', 'jpeg', 'png', 'webp'],
'allowed_mime_types' => ['image/jpeg', 'image/png', 'image/webp'], // real type, via finfo
'allowed_max_size' => 10 * 1024 * 1024,
]
);

Expand All @@ -42,10 +46,12 @@ $upload = new Upload($adapter);

```php
foreach (File::setPost('photos') as $file) {
$file->rename(bin2hex(random_bytes(16))); // never use the client's file name

$stored = $upload->setFile($file)->to('gallery');

if ($stored !== false) {
echo $stored->getURL(); // https://cdn.example.com/gallery/<name>
echo htmlspecialchars((string) $stored->getURL(), ENT_QUOTES, 'UTF-8'); // https://cdn.example.com/gallery/<32hex>.jpg
}
}
```
Expand Down Expand Up @@ -79,6 +85,12 @@ $adapter = new FTPAdapter([
'url' => 'https://cdn.example.com/',
'ssl' => true, // explicit FTPS
'passive' => true,
], [
// FTPS protects the transfer, not the content: without an allow-list every
// extension is accepted. Use the same options as in the example above.
'allowed_extensions' => ['jpg', 'jpeg', 'png', 'webp'],
'allowed_mime_types' => ['image/jpeg', 'image/png', 'image/webp'],
'allowed_max_size' => 10 * 1024 * 1024,
]);
```

Expand Down
9 changes: 6 additions & 3 deletions docs/Home.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,21 @@ use InitPHP\Upload\File;
use InitPHP\Upload\Adapters\LocalAdapter;

$upload = new Upload(new LocalAdapter([
'dir' => __DIR__ . '/uploads/',
'url' => 'https://example.com/uploads/',
'dir' => '/var/app/storage/uploads/', // outside the web root
'url' => 'https://example.com/uploads/', // served read-only, scripts never executed
], [
'allowed_extensions' => ['jpg', 'png', 'webp'],
'allowed_mime_types' => ['image/jpeg', 'image/png', 'image/webp'], // real type, via finfo
'allowed_max_size' => 2 * 1024 * 1024, // 2 MB
]));

foreach (File::setPost('photos') as $file) {
$file->rename(bin2hex(random_bytes(16))); // never keep the client's file name

$stored = $upload->setFile($file)->to();

if ($stored !== false) {
echo $stored->getURL(); // https://example.com/uploads/<name>
echo htmlspecialchars((string) $stored->getURL(), ENT_QUOTES, 'UTF-8'); // https://example.com/uploads/<32hex>.jpg
}
}
```
Expand Down
13 changes: 9 additions & 4 deletions docs/Local-Adapter.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,29 +17,34 @@ use InitPHP\Upload\Adapters\LocalAdapter;

$adapter = new LocalAdapter(
[
'dir' => __DIR__ . '/uploads/',
'url' => 'https://example.com/uploads/',
'dir' => '/var/app/storage/uploads/', // outside the web root
'url' => 'https://example.com/uploads/', // served read-only, scripts never executed
],
[
'allowed_extensions' => ['jpg', 'png', 'pdf'],
'allowed_mime_types' => ['image/jpeg', 'image/png', 'application/pdf'], // real type, via finfo
'allowed_max_size' => 5 * 1024 * 1024,
]
);

$upload = new Upload($adapter);
```

`dir` should usually point **outside the web root** — see
`dir` should point **outside the web root** — see
[Security Best Practices](Security-Best-Practices.md#2-keep-uploads-out-of-the-web-root).

## Storing files

```php
foreach (File::setPost('documents') as $file) {
// Never store under the client's file name: generate one (the extension is kept).
// Two uploads with the same client name would otherwise overwrite each other.
$file->rename(bin2hex(random_bytes(16)));

$stored = $upload->setFile($file)->to();

if ($stored !== false) {
echo $stored->getURL(); // https://example.com/uploads/<name>
echo htmlspecialchars((string) $stored->getURL(), ENT_QUOTES, 'UTF-8'); // https://example.com/uploads/<32hex>.pdf
}
}
```
Expand Down
29 changes: 19 additions & 10 deletions docs/Quick-Start.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ single-file `name="photo"` field.
## 2. Build an adapter

An **adapter** knows *where* files go (`credentials`) and *what* is allowed
(`options`, optional):
(`options` — optional in the API, but always set them for user uploads):

```php
<?php
Expand All @@ -29,15 +29,19 @@ use InitPHP\Upload\Upload;
use InitPHP\Upload\File;
use InitPHP\Upload\Adapters\LocalAdapter;

// options — what is allowed. With none set, every extension and type is accepted.
$options = [
'allowed_extensions' => ['jpg', 'jpeg', 'png', 'webp'],
'allowed_mime_types' => ['image/jpeg', 'image/png', 'image/webp'], // real type, via finfo
'allowed_max_size' => 2 * 1024 * 1024, // 2 MB, in bytes
];

$adapter = new LocalAdapter(
[ // credentials — where files go
'dir' => __DIR__ . '/uploads/',
'url' => 'https://example.com/uploads/',
'dir' => '/var/app/storage/uploads/', // outside the web root
'url' => 'https://example.com/uploads/', // served read-only, scripts never executed
],
[ // options — what is allowed (optional)
'allowed_extensions' => ['jpg', 'jpeg', 'png', 'webp'],
'allowed_max_size' => 2 * 1024 * 1024, // 2 MB, in bytes
]
$options
);

$upload = new Upload($adapter);
Expand All @@ -62,6 +66,9 @@ $results = [];

foreach (File::setPost('photos') as $file) {
try {
// Never store under the client's file name: generate one (the extension is kept).
$file->rename(bin2hex(random_bytes(16)));

$stored = $upload->setFile($file)->to();

if ($stored === false) {
Expand Down Expand Up @@ -89,6 +96,7 @@ thrown as an [`UploadException`](Error-Handling.md), not returned as `false`.
The optional `$target` is a destination path/key prefix:

```php
$file->rename(bin2hex(random_bytes(16))); // as in step 4
$upload->setFile($file)->to('2026/06');
// stored at <dir>/2026/06/<name>
// URL: https://example.com/uploads/2026/06/<name>
Expand All @@ -99,17 +107,18 @@ every adapter — see [Core Concepts](Core-Concepts.md#4-target--the-destination

## 6. Switch the backend

Only the adapter changes; steps 3–5 stay exactly the same.
Only the adapter changes; steps 3–5 stay exactly the same — including the
`$options` from step 2, which you pass as the second argument:

```php
use InitPHP\Upload\Adapters\FTPAdapter;

$upload = new Upload(new FTPAdapter([
'host' => 'ftp.example.com',
'username' => 'user',
'password' => 'secret',
'password' => getenv('FTP_PASSWORD'),
'url' => 'https://cdn.example.com/',
]));
], $options)); // the same allow-lists and size limit as above
```

## What just happened
Expand Down
34 changes: 26 additions & 8 deletions docs/Recipes.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@ use InitPHP\Upload\Exceptions\UploadException;
```php
// upload.php
$upload = new Upload(new LocalAdapter(
['dir' => __DIR__ . '/uploads/', 'url' => 'https://example.com/uploads/'],
[
'dir' => '/var/app/storage/uploads/', // outside the web root
'url' => 'https://example.com/uploads/', // served read-only, scripts never executed
],
[
'allowed_extensions' => ['jpg', 'jpeg', 'png', 'webp'],
'allowed_mime_types' => ['image/jpeg', 'image/png', 'image/webp'],
Expand All @@ -37,15 +40,19 @@ if ($files === []) {
}

try {
// Never store under the client's file name: generate one (the extension is kept).
$files[0]->rename(bin2hex(random_bytes(16)));

$stored = $upload->setFile($files[0])->to();
if ($stored === false) {
http_response_code(500);
exit('Could not store the file.');
}
echo 'Stored at ' . $stored->getURL();
// The URL is derived from the stored name; escape it anyway when it goes into HTML.
echo 'Stored at ' . htmlspecialchars((string) $stored->getURL(), ENT_QUOTES, 'UTF-8');
} catch (UploadException $e) {
http_response_code(422);
echo $e->getMessage();
echo htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8');
}
```

Expand All @@ -57,6 +64,8 @@ header('Content-Type: application/json');
$results = [];
foreach (File::setPost('gallery') as $file) {
try {
$file->rename(bin2hex(random_bytes(16))); // never use the client's file name

$stored = $upload->setFile($file)->to('gallery/' . date('Y/m'));
$results[] = $stored === false
? ['name' => $file->getName(), 'ok' => false, 'error' => 'write failed']
Expand Down Expand Up @@ -101,7 +110,7 @@ $file->rename(strtolower(trim($slug, '-')) . '-' . substr(bin2hex(random_bytes(4
$file = File::setPost('avatar')[0] ?? null;

if ($file !== null) {
$file->rename('avatar'); // avatar.<ext>
$file->rename('avatar'); // avatar.<ext>; $userId must be the authenticated user's id, never request input
$stored = $upload->setFile($file)->to('users/' . $userId);
// stored at <dir>/users/<id>/avatar.<ext>
$user->avatar_url = $stored !== false ? $stored->getURL() : null;
Expand Down Expand Up @@ -145,7 +154,11 @@ Because every adapter shares one interface, only construction differs.
use InitPHP\Upload\Adapters\FTPAdapter;
use InitPHP\Upload\Adapters\S3Adapter;

$options = ['allowed_extensions' => ['jpg', 'png'], 'allowed_max_size' => 2_000_000];
$options = [
'allowed_extensions' => ['jpg', 'png'],
'allowed_mime_types' => ['image/jpeg', 'image/png'],
'allowed_max_size' => 2_000_000,
];

$adapter = match (getenv('UPLOAD_DRIVER') ?: 'local') {
's3' => new S3Adapter([
Expand All @@ -161,8 +174,8 @@ $adapter = match (getenv('UPLOAD_DRIVER') ?: 'local') {
'url' => getenv('FTP_PUBLIC_URL'),
], $options),
default => new LocalAdapter([
'dir' => __DIR__ . '/uploads/',
'url' => getenv('APP_URL') . '/uploads/',
'dir' => '/var/app/storage/uploads/', // outside the web root
'url' => getenv('APP_URL') . '/uploads/', // served read-only, scripts never executed
], $options),
};

Expand Down Expand Up @@ -196,13 +209,18 @@ if ($files === []) {
## Validate a file before deciding what to do with it

```php
// $upload is built with 'allowed_extensions' => ['pdf'] and
// 'allowed_mime_types' => ['application/pdf'].
$file = File::setPost('doc')[0] ?? null;

if ($file !== null && $file->isValid()) {
if ($file->getRealMimeType() === 'application/pdf') {
$file->rename(bin2hex(random_bytes(16)));
$upload->setFile($file)->to('pdfs');
} else {
$upload->setFile($file)->to('other');
// Do not fall back to "store it somewhere else": reject what you do not expect.
http_response_code(422);
exit('Only PDF files are accepted.');
}
}
```
Expand Down
4 changes: 3 additions & 1 deletion docs/S3-Adapter.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,12 @@ $upload = new Upload($adapter);

```php
foreach (File::setPost('photos') as $file) {
$file->rename(bin2hex(random_bytes(16))); // never use the client's file name as the key

$stored = $upload->setFile($file)->to('avatars');

if ($stored !== false) {
echo $stored->getURL(); // the object's public URL
echo htmlspecialchars((string) $stored->getURL(), ENT_QUOTES, 'UTF-8'); // the object's public URL
}
}
```
Expand Down
Loading