Introduction
When it comes to securing file downloads, you might want to ensure that only the user who submitted a specific entry can access their uploaded files.
In this guide, we’ll walk through how to use filters to limit file access to the original submitter of a Gravity Forms entry.
Examples
add_filter( 'gform_pre_replace_merge_tags', function ( $text, $form, $entry ) {
if ( empty( $entry['id'] ) || empty( $entry['created_by'] ) ) {
return $text;
}
foreach ( $form['fields'] as $field ) {
if ( ! $field instanceof GF_Field_FileUpload ) {
continue;
}
$field->set_context_property( 'entry_id', $entry['id'] );
$field->set_context_property( 'entry_created_by', $entry['created_by'] );
}
return $text;
}, 10, 3 );
add_filter( 'gform_secure_file_download_url', function ( $download_url, $field ) {
if ( GFCommon::is_entry_detail() ) {
$entry = GFEntryDetail::get_current_entry();
$entry_id = rgar( $entry, 'id' );
$created_by = rgar( $entry, 'created_by' );
} else {
$entry_id = $field->get_context_property( 'entry_id' );
$created_by = $field->get_context_property( 'entry_created_by' );
}
if ( empty( $entry_id ) || empty( $created_by ) ) {
return $download_url;
}
return add_query_arg( array( 'id-e' => $entry_id, 'id-c' => $created_by ), $download_url );
}, 10, 2 );
add_filter( 'gform_require_login_pre_download', function ( $require_login ) {
$require_login = true;
if ( ! is_user_logged_in() ) {
auth_redirect();
}
return $require_login;
} );
add_filter( 'gform_permission_granted_pre_download', function ( $permission_granted, $form_id, $field_id ) {
$entry_id = rgget( 'id-e' );
$created_by = rgget( 'id-c' );
if ( empty( $entry_id ) || empty( $created_by ) ) {
return false;
}
$entry = GFAPI::get_entry( $entry_id );
if ( is_wp_error( $entry ) || rgar( $entry, 'created_by' ) !== $created_by || empty( $entry[ $field_id ] ) ) {
return false;
}
return get_current_user_id() == $created_by;
}, 10, 3 );
Placement
This code can be used in the functions.php file of the active theme, a custom functions plugin, a custom add-on, or with a code snippets plugin.
See also the PHP section in this article: Where Do I Put This Code?