Search code examples
phpimageemailattachmentuploading

Sending an image via an email attachment, which is stored in a string


Say if I had a string which had this text/html stored in it:

Hello. This is a test article. <img src="http://hellotxt.com/image/jpFd.n.jpg" />

I want the image to be uploaded/saved in a temp folder, then sent as an attachment via email. Then preferably have the temp folder deleted. Would this be possible?
I know how to sent the email with an attachment (the easy part), so that's no problem. It's just the uploading of the image into a folder and finding the image in the string.


Solution

  • Ok so this is basically a 2 part question:

    1. How to extract a filename/source from a string
    2. How to upload said file to the server
    1. Check out the preg_match function (use preg_match_all if you have multiple files in the same string)
      
          $matches = array();
      
          $numFound = preg_match( "/src[\s]?=[\s]?[\" | \'](^[\" | \'])*[\" | \']/", $yourInputString, $matches );
      
          echo $matches[1]; //this will print out the source (the part in parens in the regex)
          
      I'm not great with regexp so the one I provided might be wrong, but I think it should work.
    2. Ok now for the uploading part... Assuming this is straight PHP (no HTML, forms available), then I think your best bet is to use cURL and mimic a form submission. You'll need a PHP script that will accept an uploaded file and move it to a location on your server (this should help). The actual uploading will be done like this:
      
          $data = array('file' => '@' . $fileSourceFromPart1); //the '@' is VITAL!
          $ch = curl_init();
      
          curl_setopt($ch, CURLOPT_URL, 'path/to/upload/script.php');
          curl_setopt($ch, CURLOPT_POST, 1);
          curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
      
          curl_exec($ch);
      
          

    Hopefully that does the trick, or at least gets you headed in the right direction!