0

Right now I'm creating a plugin to sideload images from an external source.

The UI allows me to select files on the external server then downloads them via AJAX & media_sideload_image. Everything is working great. After the images is loaded I clean up the attachment's title by replacing the dashes and underscores with spaces in addition to separating alpha/numerics for legibility.

// sideload the image
$src = media_sideload_image(esc_url($url), $post_id, $desc, $return);

// convert to attachment src -> ID -> post
$id = attachment_url_to_postid($src);
$post = get_post($id);

// clean the title
// BEFORE: BB-SH-YongKang20Road-6
// AFTER: BB SH YongKang 20 Road 6

$title = $post->post_title;
$title = str_replace('-', ' ', $title);
$title = str_replace('_', ' ', $title);
$title = preg_replace("/[^a-zA-Z0-9\s\p{P}]/", "", $title);
$title = preg_replace('/(?<=[a-z])(?=\d)|(?<=\d)(?=[a-z])/i', ' ', $title);

My problem is the random 20 which I know is because of an encoded space %20. Now all titles and filenames have this random 20.

How can I clean the source url and still make it valid or modify the final filename to exclude %20/20?


UPDATED SOLUTION

$src = media_sideload_image(rawurldecode($url), $post_id, $desc, $return);
3
  • I think you want esc_url_raw so the input URLs aren't html encoded.
    – Milo
    Jan 2 '16 at 0:05
  • At first blush I didn't see any change. I'll test more to make sure because this seems like a good idea.
    – jgraup
    Jan 2 '16 at 4:52
  • rawurldecode is the only one that worked and I can't see any change with esc_url_raw. Is there a way to make sure the url is clean if it's decoded? I don't imagine the external url can be tampered with but I'm not a security expert.
    – jgraup
    Jan 4 '16 at 21:59
1

rawurldecode fixes the issue.

$src = media_sideload_image(rawurldecode($url), $post_id, $desc, $return);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.