Reputation: 1247
I have a custom page template. This template have a custom form that user can upload a file. Now, the uploaded file/s will not upload in the MySQL but in the file system/local folder (local computer).
I already have a PHP snippet, but the code is not working I'm getting an errors.
How to fix this?
Snippet:
if(isset($_POST['submit'])){
$lastName = isset($_POST['lastName']) ? $_POST['lastName'] : '';
$resumeFile = isset($_FILE['resumeFile']['name']) ? $_FILE['resumeFile']['name']: '';
$info = pathinfo($_FILES['resumeFile']['name']);
$ext = $info['extension'];
$file_rename= $lastName.$ext;
$target = 'C://xampp/htdocs/files/'.$file_rename;
move_uploaded_file($_FILES['resumeFile']['tmp_name'], $target);
}
Errors:
Notice: Undefined index: resumeFile .... on line 130
Notice: Undefined index: extension .... on line 131
Notice: Undefined index: resumeFile .... on line 135
Upvotes: 2
Views: 1843
Reputation: 4546
Try the following snippet, to upload files on different directory other than default uploads
directory.
function change_my_upload_directory( $dir ) {
return array (
'path' => WP_CONTENT_DIR . '/your-custom-dir',
'url' => $dir['baseurl'] . '/wp-content/your-custom-dir',
'subdir' => '/your-custom-dir',
) + $dir;
}
if( isset( $_FILES[ "resumeFile" ] ) ) {
if ( !function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
// Overrides the uploads directory location
add_filter( 'upload_dir', 'change_my_upload_directory' );
$movefile = wp_handle_upload( $_FILES[ "resumeFile" ], array( 'test_form' => false ) );
// Remove the filter, so that subsequant uploads will be dsent to default uploads directory
remove_filter( 'upload_dir', 'change_my_upload_directory' );
return $movefile;
}
return false;
wp_handle_upload
will return an object which contains the following properties
$movefile[ 'file' ] // uploaded file object
$movefile[ 'url' ] // current url ( file location ) of the file
$movefile[ 'type' ] // uploaded file type
If wp_handle_upload
fails it will return error object, you can check for failed upload like this
if( isset( $movefile[ 'error' ] ) ) {
// handle the error
}
Upvotes: 1