Cara menggunakan get file information php
CodeIgniter makes working with files uploaded through a form much simpler and more secure than using PHP’s Show Note This is not the same as the File Uploading class in CodeIgniter v3.x. This provides a raw interface to the uploaded files with a few small features. The ProcessUploading a file involves the following general process:
To demonstrate this process here is brief tutorial. Afterward you’ll find reference information. Creating the Upload FormUsing a text editor, create a form called upload_form.php. In it, place this code and save it to your app/Views/ directory: DOCTYPE html>
<html lang="en">
<head>
<title>Upload Formtitle>
head>
<body>
php foreach ($errors as $error): ?>
<li>= esc($error) ?>li>
endforeach ?>
= form_open_multipart('upload/upload') ?>
<input type="file" name="userfile" size="20" />
<br /><br />
<input type="submit" value="upload" />
form>
body>
html>
You’ll notice we are using a form helper to create the opening form tag. File uploads require a multipart form, so the helper creates the proper syntax for you. You’ll also notice we have an The Success PageUsing a text editor, create a form called upload_success.php. In it, place this code and save it to your app/Views/ directory: DOCTYPE html>
<html lang="en">
<head>
<title>Upload Formtitle>
head>
<body>
<h3>Your file was successfully uploaded!h3>
<ul>
<li>name: esc($uploaded_flleinfo->getBasename()) ?>li>
<li>size: = esc($uploaded_flleinfo->getSizeByUnit('kb')) ?> KBli>
<li>extension: = esc($uploaded_flleinfo->guessExtension()) ?>li>
ul>
<p>= anchor('upload', 'Upload Another File!') ?>p>
body>
html>
The ControllerUsing a text editor, create a controller called Upload.php. In it, place this code and save it to your app/Controllers/ directory: php
namespace App\Controllers;
use CodeIgniter\Files\File;
class Upload extends BaseController
{
protected $helpers = ['form'];
public function index()
{
return view('upload_form', ['errors' => []]);
}
public function upload()
{
$validationRule = [
'userfile' => [
'label' => 'Image File',
'rules' => 'uploaded[userfile]'
. '|is_image[userfile]'
. '|mime_in[userfile,image/jpg,image/jpeg,image/gif,image/png,image/webp]'
. '|max_size[userfile,100]'
. '|max_dims[userfile,1024,768]',
],
];
if (! $this->validate($validationRule)) {
$data = ['errors' => $this->validator->getErrors()];
return view('upload_form', $data);
}
$img = $this->request->getFile('userfile');
if (! $img->hasMoved()) {
$filepath = WRITEPATH . 'uploads/' . $img->store();
$data = ['uploaded_flleinfo' => new File($filepath)];
return view('upload_success', $data);
}
$data = ['errors' => 'The file has already been moved.'];
return view('upload_form', $data);
}
}
Note Since the value of a file upload HTML field doesn’t exist, and is stored in the The RoutesUsing a text editor, open app/Config/Routes.php. In it, add the following two routes: php
// ...
/*
* --------------------------------------------------------------------
* Route Definitions
* --------------------------------------------------------------------
*/
// We get a performance increase by specifying the default
// route since we don't have to scan directories.
$routes->get('/', 'Home::index');
$routes->get('upload', 'Upload::index'); // Add this line.
$routes->post('upload/upload', 'Upload::upload'); // Add this line.
// ...
The Upload DirectoryThe uploaded files are stored in the writable/uploads/ directory. Try it!To try your form, visit your site using a URL similar to this one: example.com/index.php/upload/ You should see an upload form. Try uploading an image file (either a jpg, gif, png, or webp). If the path in your controller is correct it should work. Accessing FilesAll FilesWhen you upload files they can be accessed natively in PHP through the Files are accessed through the current php
$files = $this->request->getFiles();
Of course, there are multiple ways to name the file input, and anything but the simplest can create strange results. The array returns in a manner that you would expect. With the simplest usage, a single file might be submitted like: <input type="file" name="avatar" /> Which would return a simple array like: [ 'avatar' => // UploadedFile instance, ]; Note The UploadedFile instance corresponds to If you used an array notation for the name, the input would look something like: <input type="file" name="my-form[details][avatar]" /> The array returned by [ 'my-form' => [ 'details' => [ 'avatar' => // UploadedFile instance ], ], ] In some cases, you may specify an array of files to upload: Upload an avatar: <input type="file" name="my-form[details][avatars][]" /> Upload an avatar: <input type="file" name="my-form[details][avatars][]" /> In this case, the returned array of files would be more like: [ 'my-form' => [ 'details' => [ 'avatar' => [ 0 => // UploadedFile instance, 1 => // UploadedFile instance, ], ], ], ] Single FileIf you just need to access a single file, you can use Simplest usageWith the simplest usage, a single file might be submitted like: <input type="file" name="userfile" /> Which would return a simple file instance like: php
$file = $this->request->getFile('userfile');
Array notationIf you used an array notation for the name, the input would look something like: <input type="file" name="my-form[details][avatar]" /> For get the file instance: php
$file = $this->request->getFile('my-form.details.avatar');
Multiple files<input type="file" name="images[]" multiple /> In controller: php
if ($imagefile = $this->request->getFiles()) {
foreach ($imagefile['images'] as $img) {
if ($img->isValid() && ! $img->hasMoved()) {
$newName = $img->getRandomName();
$img->move(WRITEPATH . 'uploads', $newName);
}
}
}
where the If there are multiple files with the same name you can use In controller: php
$file1 = $this->request->getFile('images.0');
$file2 = $this->request->getFile('images.1');
You might find it easier to use php
$files = $this->request->getFileMultiple('images');
Another example: Upload an avatar: <input type="file" name="my-form[details][avatars][]" /> Upload an avatar: <input type="file" name="my-form[details][avatars][]" /> In controller: php
$file1 = $this->request->getFile('my-form.details.avatars.0');
$file2 = $this->request->getFile('my-form.details.avatars.1');
Note Using Working With the FileOnce you’ve retrieved the UploadedFile instance, you can retrieve information about the file in safe ways, as well as move the file to a new location. Verify a FileYou can check that a file was actually uploaded via HTTP with no errors by calling the php
if (! $file->isValid()) {
throw new \RuntimeException($file->getErrorString() . '(' . $file->getError() . ')');
}
As seen in this example, if a file had an upload error, you can retrieve the error code (an integer) and the error message with the
File NamesgetName()You can retrieve the original
filename provided by the client with the php
$name = $file->getName();
getClientName()Always returns the original name of the uploaded file as sent by the client, even if the file has been moved: php
$originalName = $file->getClientName();
getTempName()To get the full path of the temp file that was created during the upload, you can use the php
$tempfile = $file->getTempName();
Other File InfogetClientExtension()Returns the original file extension, based on the file name that was uploaded: php
$ext = $file->getClientExtension();
Warning This is NOT a trusted source. For a trusted version, use getClientMimeType()Returns the mime type (mime type) of the file as
provided by the client. This is NOT a trusted value. For a trusted version, use php
$type = $file->getClientMimeType();
echo $type; // image/png
Moving FilesEach file can be moved to its new location with
the aptly named php
$file->move(WRITEPATH . 'uploads');
By default, the original filename was used. You can specify a new filename by passing it as the second parameter: php
$newName = $file->getRandomName();
$file->move(WRITEPATH . 'uploads', $newName);
Once the file has been removed the temporary file is deleted. You can check if a file has been moved already with the php
if ($file->isValid() && ! $file->hasMoved()) {
$file->move($path);
}
Moving an uploaded file can fail, with an HTTPException, under several circumstances:
Store FilesEach file can be moved to its new location with the aptly named With the simplest usage, a single file might be submitted like: <input type="file" name="userfile" /> By default, upload files are saved in writable/uploads directory. The YYYYMMDD folder and random file name will be created. Returns a file path: php
$path = $this->request->getFile('userfile')->store();
You can specify a directory to move the file to as the first parameter. A new filename by passing it as the second parameter: php
$path = $this->request->getFile('userfile')->store('head_img/', 'user_name.jpg');
Moving an uploaded file can fail, with an
|