Simple File Upload Script

simple file upload script

You lack enctype="multipart/form-data" in your <form> element.

What's the best way to create a single-file upload form using PHP?

File Upload Tutorial

HTML

<form enctype="multipart/form-data" action="action.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
<input name="userfile" type="file" />
<input type="submit" value="Go" />
</form>
  • action.php is the name of a PHP file that will process the upload (shown below)
  • MAX_FILE_SIZE must appear immediately before the input with type file. This value can easily be manipulated on the client so should not be relied upon. Its main benefit is to provide the user with early warning that their file is too large, before they've uploaded it.
  • You can change the name of the input with type file, but make sure it doesn't contain any spaces. You must also update the corresponding value in the PHP file (below).

PHP

<?php
$uploaddir = "/www/uploads/";
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "Success.\n";
} else {
echo "Failure.\n";
}

echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>

The upload-to folder should not be located in a place that's accessible via HTTP, otherwise it would be possible to upload a PHP script and execute it upon the server.

Printing the value of $_FILES can give a hint as to what's going on. For example:


Array
(
[userfile] => Array
(
[name] => Filename.ext
[type] =>
[tmp_name] =>
[error] => 2
[size] => 0
)
)

This structure gives some information as to the file's name, MIME type, size and error code.

Error Codes

0 Indicates that there was no errors and file has been uploaded successfully

1 Indicates that the file exceeds the maximum file size defined in php.ini. If you would like to change the maximum file size, you need to open your php.ini file, identify the line which reads: upload_max_filesize = 2M and change the value from 2M (2MB) to whatever you need

2 Indicates that the maximum file size defined manually, within an on page script has been exceeded

3 Indicates that file has only been uploaded partially

4 Indicates that the file hasn't been specified (empty file field)

5 Not defined yet

6 Indicates that there´s no temporary folder

7 Indicates that the file cannot be written to the disk

php.ini Configuration

When running this setup with larger files you may receive errors. Check your php.ini file for these keys:

max_execution_time = 30
upload_max_filesize = 2M

Increasing these values as appropriate may help. When using Apache, changes to this file require a restart.

The maximum memory permitted value (set via memory_limit) does not play a role here as the file is written to the tmp directory as it is uploaded. The location of the tmp directory is optionally controlled via upload_tmp_dir.

Checking file mimetypes

You should check the filetype of what the user is uploading - the best practice is to validate against a list of allowed filetypes. A potential risk of allowing any file is that a user could potentially upload PHP code to the server and then run it.

You can use the very useful fileinfo extension (that supersedes the older mime_content_type function) to validate mime-types.

// FILEINFO_MIME set to return MIME types, will return string of info otherwise
$fileinfo = new finfo(FILEINFO_MIME);
$file = $fileinfo->file($_FILE['filename']);

$allowed_types = array('image/jpeg', 'image/png');
if(!in_array($file, $allowed_types))
{
die('Files of type' . $file . ' are not allowed to be uploaded.');
}
// Continue

More Information

You can read more on handling file uploads at the PHP.net manual.

For PHP 5.3+

//For those who are using PHP 5.3, the code varies.
$fileinfo = new finfo(FILEINFO_MIME_TYPE);
$file = $fileinfo->file($_FILE['filename']['tmp_name']);
$allowed_types = array('image/jpeg', 'image/png');
if(!in_array($file, $allowed_types))
{
die('Files of type' . $file . ' are not allowed to be uploaded.');
}
// Continue

More Information

You can read more on FILEINFO_MIME_TYPE at the PHP.net documentation.

How to upload any type of file to the server using PHP 5?

=> Try this code for upload any type of file ..

//HTML PAGE

<li class="text">File Upload </li>
<li><input type="file" name="file" value="" class="input" ></li>

try this to all file upload..
//PHP PAGE

if(isset($_POST['submit'])!=""){
$name=$_FILES['file']['name'];
$size=$_FILES['file']['size'];
$type=$_FILES['file']['type'];
$temp=$_FILES['file']['tmp_name'];
$caption1=$_POST['caption'];
$link=$_POST['link'];
move_uploaded_file($temp,"upload/".$name);// set your folder name to store all file.

Why is my PHP file upload code not working?

You are working on windows and you've told PHP a location that is inaccessible (i.e. /uploads linux path).

Since you are working in windows and your document root is C:\wamp\www\simpleupload

Which means, your files are located like this:

  • C:\wamp\www\simpleupload\index.php (your upload script)
  • C:\wamp\www\simpleupload\uploads (where the files should be uploaded)

Why don't you use absolute path like this:

$uploads_dir = getcwd() . DIRECTORY_SEPARATOR . 'uploads';

The getcwd() function will return the current working directory for the executing PHP script (in your case index.php), so the $uploads_dir will now look like this: C:\wamp\www\simpleupload\uploads

Try this.

Angular File Upload

Here is a working example for file upload to api:

Step 1: HTML Template (file-upload.component.html)

Define simple input tag of type file. Add a function to (change)-event for handling choosing files.

<div class="form-group">
<label for="file">Choose File</label>
<input type="file"
id="file"
(change)="handleFileInput($event.target.files)">
</div>

Step 2: Upload Handling in TypeScript (file-upload.component.ts)

Define a default variable for selected file.

fileToUpload: File | null = null;

Create function which you use in (change)-event of your file input tag:

handleFileInput(files: FileList) {
this.fileToUpload = files.item(0);
}

If you want to handle multifile selection, than you can iterate through this files array.

Now create file upload function by calling you file-upload.service:

uploadFileToActivity() {
this.fileUploadService.postFile(this.fileToUpload).subscribe(data => {
// do something, if upload success
}, error => {
console.log(error);
});
}

Step 3: File-Upload Service (file-upload.service.ts)

By uploading a file via POST-method you should use FormData, because so you can add file to http request.

postFile(fileToUpload: File): Observable<boolean> {
const endpoint = 'your-destination-url';
const formData: FormData = new FormData();
formData.append('fileKey', fileToUpload, fileToUpload.name);
return this.httpClient
.post(endpoint, formData, { headers: yourHeadersConfig })
.map(() => { return true; })
.catch((e) => this.handleError(e));
}

So, This is very simple working example, which I use everyday in my work.

Upload a file using PHP

Below is one way to upload files, there are many other ways.

As @nordenheim said, $HTTP_POST_FILES has been deprecated since PHP 4.1.0, thus not advisable to use so.

PHP Code (upload.php)

<?php
$target_dir = "upload/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
$allowedTypes = ['jpg', 'png'];

if (isset($_POST["submit"])) {
// check type
if (!in_array($imageFileType, $allowedTypes)) {
$msg = "Type is not allowed";
} // Check if file already exists
elseif (file_exists($target_file)) {
$msg = "Sorry, file already exists.";
} // Check file size
elseif ($_FILES["fileToUpload"]["size"] > 5000000) {
$msg = "Sorry, your file is too large.";
} elseif (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
$msg = "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded.";
}
}

?>

HTML Code to start function

<form action="upload.php" method="post" id="myForm" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<button name="submit" class="btn btn-primary" type="submit" value="submit">Upload File</button>
</form>

Hope this helps.



Related Topics



Leave a reply



Submit