id summary reporter owner description type status priority milestone component version severity resolution keywords cc focuses
18855 get_attached_file( $post_id ) wrongly(?) returns the uploads directory when $post_id is not a valid attachment mikeschinkel nacin "The function `get_attached_file( $post_id )` wrongly(?) returns the uploads directory when `$post_id` is not a valid attachment. For example, if I run the following code:
{{{
$attached_file = get_attached_file(0);
}}}
It might return the following on my machine:
{{{
/Users/mikeschinkel/Sites/mysite/public_html/wp-content/uploads/
}}}
I would instead expect it to simply return `false` indicating that no attached file was found:
{{{
false
}}}
Here is the code I wrote that caused me to recognize the problem:
{{{
function has_valid_file_attached( $attachment_id ) {
return file_exists( get_attached_file( $attachment_id, true ) ) );
}
}}}
Here's the hack I had to write instead:
{{{
function has_valid_file_attached( $attachment_id ) {
$attached_file = get_attached_file( $attachment_id, true );
if ( '/' == substr( $attached_file, -1, 1 ) )
return false;
if ( ! file_exists( $attached_file ) )
return false;
return true;
}
}}}
I have attached a patch that simply returns `false` when the value returned by the internal call to `get_post_meta( $attachment_id, '_wp_attached_file', true )` is an empty string. I would be surprised to find it many people (anyone?) used this function for it's side-effect to return the root upload path so I doubt using this path would break anything.
It's not a critical patch because there is an easy workaround, but it cost me extra time to figure out why my `has_valid_file_attached()` function wasn't reporting `false` when the attachment was missing, so it would be nice to keep someone else from having to waste the same time in the future." defect (bug) closed normal 3.4 Post Thumbnails 3.2.1 normal fixed has-patch needs-unit-tests