Git Product home page Git Product logo

php-fileupload's Introduction

PHP-FileUpload

Simple and convenient file uploads — secure by default

Requirements

  • PHP 5.6.0+

Installation

  1. Include the library via Composer [?]:

    $ composer require delight-im/file-upload
    
  2. Include the Composer autoloader:

    require __DIR__ . '/vendor/autoload.php';
  3. Set up your HTML form for the file upload, e.g.:

    <form action="" method="post" enctype="multipart/form-data">
        <input type="hidden" name="MAX_FILE_SIZE" value="1048576">
        <input type="file" name="my-input-name">
        <button type="submit">Upload</button>
    </form>

    The two attributes method="post" and enctype="multipart/form-data" on the <form> element are mandatory. Likewise, there must be at least one <input type="file"> element with a proper name attribute. Finally, some way to submit the form, e.g. the <button type="submit"> element, is required. The hidden input named MAX_FILE_SIZE is an optional hint for the client.

Usage

File uploads

$upload = new \Delight\FileUpload\FileUpload();
$upload->withTargetDirectory('/my-app/users/' . $userId . '/avatars');
$upload->from('my-input-name');

try {
    $uploadedFile = $upload->save();

    // success

    // $uploadedFile->getFilenameWithExtension()
    // $uploadedFile->getFilename()
    // $uploadedFile->getExtension()
    // $uploadedFile->getDirectory()
    // $uploadedFile->getPath()
    // $uploadedFile->getCanonicalPath()
}
catch (\Delight\FileUpload\Throwable\InputNotFoundException $e) {
    // input not found
}
catch (\Delight\FileUpload\Throwable\InvalidFilenameException $e) {
    // invalid filename
}
catch (\Delight\FileUpload\Throwable\InvalidExtensionException $e) {
    // invalid extension
}
catch (\Delight\FileUpload\Throwable\FileTooLargeException $e) {
    // file too large
}
catch (\Delight\FileUpload\Throwable\UploadCancelledException $e) {
    // upload cancelled
}

Limiting the maximum permitted file size

$upload->withMaximumSizeInBytes(4194304);

// or

$upload->withMaximumSizeInKilobytes(4096);

// or

$upload->withMaximumSizeInMegabytes(4);

Reading the maximum permitted file size

// e.g. int(4194304)
$upload->getMaximumSizeInBytes();

// or

// e.g. int(4096)
$upload->getMaximumSizeInKilobytes();

// or

// e.g. int(4)
$upload->getMaximumSizeInMegabytes();

Restricting the allowed file types or extensions

$upload->withAllowedExtensions([ 'jpeg', 'jpg', 'png', 'gif' ]);

Note: By default, a set of filename extensions is used that is relatively safe for PHP applications and common on the web. This may be sufficient for some use cases.

Reading the allowed file types or extensions

// e.g. array(4) { [0]=> string(4) "jpeg" [1]=> string(3) "jpg" [2]=> string(3) "png" [3]=> string(3) "gif" }
$upload->getAllowedExtensionsAsArray();

// or

// e.g. string(16) "jpeg,jpg,png,gif"
$upload->getAllowedExtensionsAsMachineString();

// or

// e.g. string(19) "JPEG, JPG, PNG, GIF"
$upload->getAllowedExtensionsAsHumanString();

// or

// e.g. string(21) "JPEG, JPG, PNG or GIF"
$upload->getAllowedExtensionsAsHumanString(' or ');

Reading the target directory

// e.g. string(24) "/my-app/users/42/avatars"
$upload->getTargetDirectory();

Defining the target filename

$upload->withTargetFilename('my-picture');

Note: By default, a random filename will be used, which is sufficient (and desired) in many cases.

Reading the target filename

// e.g. string(10) "my-picture"
$upload->getTargetFilename();

Reading the name of the input field

// e.g. string(13) "my-input-name"
$upload->getSourceInputName();

Base64 uploads

$upload = new \Delight\FileUpload\Base64Upload();
$upload->withTargetDirectory('/my-app/users/' . $userId . '/avatars');
$upload->withData($_POST['my-base64']);

try {
    $uploadedFile = $upload->save();

    // success

    // $uploadedFile->getFilenameWithExtension()
    // $uploadedFile->getFilename()
    // $uploadedFile->getExtension()
    // $uploadedFile->getDirectory()
    // $uploadedFile->getPath()
    // $uploadedFile->getCanonicalPath()
}
catch (\Delight\FileUpload\Throwable\InputNotFoundException $e) {
    // input not found
}
catch (\Delight\FileUpload\Throwable\InvalidFilenameException $e) {
    // invalid filename
}
catch (\Delight\FileUpload\Throwable\InvalidExtensionException $e) {
    // invalid extension
}
catch (\Delight\FileUpload\Throwable\FileTooLargeException $e) {
    // file too large
}
catch (\Delight\FileUpload\Throwable\UploadCancelledException $e) {
    // upload cancelled
}

Limiting the maximum permitted file size

$upload->withMaximumSizeInBytes(4194304);

// or

$upload->withMaximumSizeInKilobytes(4096);

// or

$upload->withMaximumSizeInMegabytes(4);

Reading the maximum permitted file size

// e.g. int(4194304)
$upload->getMaximumSizeInBytes();

// or

// e.g. int(4096)
$upload->getMaximumSizeInKilobytes();

// or

// e.g. int(4)
$upload->getMaximumSizeInMegabytes();

Defining the filename extension

$upload->withFilenameExtension('png');

Note: This defines the filename extension of the file to be uploaded, which is a property of the FileUpload instance. It does not change the extension of any file already uploaded, which would be represented in a File instance. By default, the filename extension bin for arbitrary (binary) data will be used, which may be sufficient in some cases.

Reading the filename extension

// e.g. string(3) "png"
$upload->getFilenameExtension();

Note: This retrieves the filename extension of the file to be uploaded, which is a property of the FileUpload instance. It does not read the extension of any file already uploaded, which would be represented in a File instance.

Reading the target directory

// e.g. string(24) "/my-app/users/42/avatars"
$upload->getTargetDirectory();

Defining the target filename

$upload->withTargetFilename('my-picture');

Note: By default, a random filename will be used, which is sufficient (and desired) in many cases.

Reading the target filename

// e.g. string(10) "my-picture"
$upload->getTargetFilename();

Reading the Base64 data

// e.g. string(20) "SGVsbG8sIFdvcmxkIQ=="
$upload->getData();

Data URI uploads

$upload = new \Delight\FileUpload\DataUriUpload();
$upload->withTargetDirectory('/my-app/users/' . $userId . '/avatars');
$upload->withUri($_POST['my-data-uri']);

try {
    $uploadedFile = $upload->save();

    // success

    // $uploadedFile->getFilenameWithExtension()
    // $uploadedFile->getFilename()
    // $uploadedFile->getExtension()
    // $uploadedFile->getDirectory()
    // $uploadedFile->getPath()
    // $uploadedFile->getCanonicalPath()
}
catch (\Delight\FileUpload\Throwable\InputNotFoundException $e) {
    // input not found
}
catch (\Delight\FileUpload\Throwable\InvalidFilenameException $e) {
    // invalid filename
}
catch (\Delight\FileUpload\Throwable\InvalidExtensionException $e) {
    // invalid extension
}
catch (\Delight\FileUpload\Throwable\FileTooLargeException $e) {
    // file too large
}
catch (\Delight\FileUpload\Throwable\UploadCancelledException $e) {
    // upload cancelled
}

Limiting the maximum permitted file size

$upload->withMaximumSizeInBytes(4194304);

// or

$upload->withMaximumSizeInKilobytes(4096);

// or

$upload->withMaximumSizeInMegabytes(4);

Reading the maximum permitted file size

// e.g. int(4194304)
$upload->getMaximumSizeInBytes();

// or

// e.g. int(4096)
$upload->getMaximumSizeInKilobytes();

// or

// e.g. int(4)
$upload->getMaximumSizeInMegabytes();

Restricting the allowed MIME types and extensions

$upload->withAllowedMimeTypesAndExtensions([
    'image/jpeg' => 'jpg',
    'image/png' => 'png',
    'image/gif' => 'gif'
]);

Note: By default, a set of MIME types is used that is relatively safe for PHP applications and common on the web. This may be sufficient for some use cases.

Reading the allowed MIME types and extensions

// e.g. array(3) { [0]=> string(10) "image/jpeg" [1]=> string(9) "image/png" [2]=> string(9) "image/gif" }
$upload->getAllowedMimeTypesAsArray();

// or

// e.g. string(30) "image/jpeg,image/png,image/gif"
$upload->getAllowedMimeTypesAsMachineString();

// or

// e.g. string(32) "image/jpeg, image/png, image/gif"
$upload->getAllowedMimeTypesAsHumanString();

// or

// e.g. string(34) "image/jpeg, image/png or image/gif"
$upload->getAllowedMimeTypesAsHumanString(' or ');

// or

// e.g. array(3) { [0]=> string(3) "jpg" [1]=> string(3) "png" [2]=> string(3) "gif" }
$upload->getAllowedExtensionsAsArray();

// or

// e.g. string(11) "jpg,png,gif"
$upload->getAllowedExtensionsAsMachineString();

// or

// e.g. string(13) "JPG, PNG, GIF"
$upload->getAllowedExtensionsAsHumanString();

// or

// e.g. string(15) "JPG, PNG or GIF"
$upload->getAllowedExtensionsAsHumanString(' or ');

Reading the target directory

// e.g. string(24) "/my-app/users/42/avatars"
$upload->getTargetDirectory();

Defining the target filename

$upload->withTargetFilename('my-picture');

Note: By default, a random filename will be used, which is sufficient (and desired) in many cases.

Reading the target filename

// e.g. string(10) "my-picture"
$upload->getTargetFilename();

Reading the data URI

// e.g. string(43) "data:text/plain;base64,SGVsbG8sIFdvcmxkIQ=="
$upload->getUri();

Contributing

All contributions are welcome! If you wish to contribute, please create an issue first so that your feature, problem or question can be discussed.

License

This project is licensed under the terms of the MIT License.

php-fileupload's People

Contributors

ocram avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

php-fileupload's Issues

Multiple File Uploads

Hey,

is it possible to upload mutiple files from an file input with multiple attribute?

I've tried it like this:

**
$upload->from('file1');
$upload->from('file2');
$upload->from('file3');
$upload->from('file4');
**
but the library keeps uploading just one single file.

undefined method Delight\FileUpload\File::getFilenameExtension()

$upload = new \Delight\FileUpload\FileUpload();
$uploadedFile = $upload->save();
$uploadedFile->getFilenameExtension();

undefined method Delight\FileUpload\File::getFilenameExtension()

but if i prent_r($uploadedFile); i can see the extention in the protected opject.

Getting Delight\FileUpload\Throwable\TargetFileWriteError

I am getting the throwable error TargetFileWriteError. Is this something to do with my server settings?

Here is my image upload code:

$checkProfileImg = $db->selectValue('SELECT user_profileimage FROM users WHERE id = ?',[$user_id]);
$uploadPath = "/images/user-uploads/images";
$upload = new \Delight\FileUpload\FileUpload();
$upload->withMaximumSizeInKilobytes(1000);
$upload->withAllowedExtensions([ 'jpeg', 'jpg', 'png', 'gif' ]);
$upload->withTargetDirectory($uploadPath);
$upload->from('image');

if(strlen($checkProfileImg) === 0) {
    // If new person, reset to random string
    $checkProfileImg = randString("95", "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
}

$upload->withTargetFilename($checkProfileImg);

try {
    $upload->save();
    $GLOBALS['JSONresponse']['status'] = "success";
    $GLOBALS['JSONresponse']['message'] = "profile image updated";
    $GLOBALS['JSONresponse']['data']['image'] = $checkProfileImg;
    refreshData();
}
catch (\Delight\FileUpload\Throwable\InputNotFoundException $e) {
    // input not found
    $GLOBALS['JSONresponse']['message'] = "image not found";
}
catch (\Delight\FileUpload\Throwable\InvalidFilenameException $e) {
    // invalid filename
    $GLOBALS['JSONresponse']['message'] = "invalid file name";
}
catch (\Delight\FileUpload\Throwable\InvalidExtensionException $e) {
    // invalid extension
    $GLOBALS['JSONresponse']['message'] = "invalid extension";
}
catch (\Delight\FileUpload\Throwable\FileTooLargeException $e) {
    // file too large
    $GLOBALS['JSONresponse']['message'] = "image too large";
}
catch (\Delight\FileUpload\Throwable\UploadCancelledException $e) {
    // upload cancelled
    $GLOBALS['JSONresponse']['message'] = "update cancelled";
}

getTargetFilename() error

If withTargetFilename() is not set on upload, getTargetFilename() don't return the random name generated

How to go back when setting a directory

Hello, I am using the library in a subdomain (admin.example.com) and I want to store the files in the public folder (public_html), but for this I must go back at least one directory backwards, and I have tried this but it doesn't work:

$upload->withTargetDirectory('/../public_html/uploads/');

How could I do it correctly? (Sorry for the translator's English)

FileTooLargeException when user set ini setting to -1 value

File uploader throw exception when user set limit resources to unlimited (-1).

example :

if ($data['size'] > $this->maxIndividualSize) {
      : \tthrow new FileTooLargeException();
      : }

maybe something like that:

	public function withMaximumSizeInBytes($size) {
		$size = (int) $size;
		if ($size > $this->maxTotalSize &&($this->maxTotalSize != -1)) {
			throw new TotalSizeExceededError();
		}

		$this->maxIndividualSize = $size;

		return $this;
	}

?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.