I’m trying to create an upload form from my admin page via a plugin.
I’ve cobbled together some code from a few sources, including this one:
https://www.htmlgoodies.com/beyond/cms/create-a-file-uploader-in-wordpress.html
I get a 500 error when I submit the form and don’t understand why or how to debug further.
Is this the wrong way to do a file upload form?
My plugin has two files:
wp-content/plugins/test_upload/test_upload.php
<?php
/*
Plugin Name: test_upload
Version: 1.0
*/
add_action('admin_menu', 'test_plugin_setup_menu');
function test_plugin_setup_menu(){
add_menu_page(
'Test Upload', 'Test Upload', 'manage_options', 'test-upload', 'upload_page'
);
}
function upload_page(){
?>
<h1>Test Upload Form</h1>
<form id="upload_form" action="/wp-content/plugins/test_upload/main.php" enctype="multipart/form-data" method="post" target="messages">
<p><input name="upload" id="upload" type="file" accept="text/csv" /></p>
<p><input id="btnSubmit" type="submit" value="Upload selected csv file" /></p>
<iframe name="messages" id="messages"></iframe>
</form>
<?php
}
wp-content/plugins/test_upload/main.php
<?php
//provides access to WP environment
require_once($_SERVER['DOCUMENT_ROOT'] . '/wp-load.php');
/* import
you get the following information for each file:
$_FILES['field_name']['name']
$_FILES['field_name']['size']
$_FILES['field_name']['type']
$_FILES['field_name']['tmp_name']
*/
if($_FILES['upload']['name']) {
if(!$_FILES['upload']['error']) {
//validate the file
$new_file_name = strtolower($_FILES['upload']['tmp_name']);
//can't be larger than 300 KB
if($_FILES['upload']['size'] > (300000)) {
//wp_die generates a visually appealing message element
wp_die('Your file size is to large.');
}
else {
//the file has passed the test
//These files need to be included as dependencies when on the front end.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
// Let WordPress handle the upload.
// Remember, 'upload' is the name of our file input in our form above.
$file_id = media_handle_upload( 'upload', 0 );
if ( is_wp_error( $file_id ) ) {
wp_die('Error loading file!');
} else {
wp_die('Your menu was successfully imported.');
}
}
}
else {
//set that to be the returned message
wp_die('Error: '.$_FILES['upload']['error']);
}
}
?>