HTML that lets user enter files on frontend:
<html>
<body>
<form id="upload" enctype="multipart/form-data" method="post">
<input id="fileupload" name="myfile" type="file" />
<input type="submit" value="Submit" id="submit" />
<?php
$db = new wpdb('username','password','db','localhost');
if( ! empty( $_FILES ) ){
$filename = $_FILES['myfile']['name'];
$file_url = "https://website-name/wp-content/uploads/$filename";
$url_exists = is_200($file_url);
$sql = "INSERT INTO column (name, url) VALUES ('$filename', '$file_url');";
if($url_exists){
echo "This file already exists within the database.";
} else{
foreach( $_FILES as $file ) {
if( is_array( $file ) ) {
$filename = $_FILES['myfile']['name'];
$file_url = "https://website-name/wp-content/uploads/$filename";
$attachment_id = upload_user_file( $file );
$db->query($sql);
echo "Your file has been added.";
}
}
}
}
?>
</form>
</body>
</html>
PHP Function to upload files to media library:
<?php
function upload_user_file( $file = array() ) {
require_once( ABSPATH . 'wp-admin/includes/admin.php' );
$file_return = wp_handle_upload( $file, array('test_form' => false ) );
if( isset( $file_return['error'] ) || isset( $file_return['upload_error_handler'] ) ) {
return false;
} else {
$filename = $file_return['file'];
$attachment = array(
'post_mime_type' => $file_return['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit',
'guid' => $file_return['url']
);
$attachment_id = wp_insert_attachment( $attachment, $file_return['url'] );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
if( 0 < intval( $attachment_id ) ) {
return $attachment_id;
}
}
return false;
}
?>
It works, but when I attempt to delete the files added with this method by using the media libary, the file still remains in the upload folder. (Sorry for late reply.)