Home » Php » email – Php mail() breaks 650 char long Url

email – Php mail() breaks 650 char long Url

Posted by: admin July 12, 2020 Leave a comment

Questions:

Im using the php mail function to send a link with many many paramaters. The url after being encoded can be 650 or more characters long because its holding variables to repopulate a form.

When I click on the link in my email its broken because a space has been inserted somewhere in the URL.

Heres my sendMail function:

    protected function sendEmail($to, $subject, $body) {
        $headers  = 'MIME-Version: 1.0' . "\r\n";
        $headers .= 'Content-type: text/html; charset=iso-8859-1' . '\r\n';
        $headers .= 'From: Sales Order From <[email protected]>' . '\r\n';
        $headers .= 'X-Mailer: PHP/' . phpversion() . '\r\n';

        $body = '<html><body style="font-size: 10pt; font-family: Arial, Helvetica, sans-serif;">'.$body.'</body></html>';

        return mail($to, $subject, $body, $headers);
    }

Heres the code I call sendMail with. Its the ‘$salesUrl = $this->getSalesFormUrl();’ that is the 650+ character url chock full of encoded paramaters.

    function emailRep() {
        $params = $this->getParamaterArray();
        $shortUrl = $this->getShortUrl();
        $salesUrl = $this->getSalesFormUrl();

        $mailSubject = "Return to the sales order form for ".$params['clientName']." at ".$params['company'].".";

        $mailBody = "The following information is from an order created on, ".date("l, F j, Y \a\t g:i a").",<br/><br/>";
        $mailBody .= "Customer Contact Information:<br/>";
        $mailBody .= "Name: ".$params['clientName'] params['company']."<br/>";
        $mailBody .= "Shortened Url to Send to the Customer:<br/>";
        $mailBody .= ($shortUrl) ? "<a href='".$shortUrl."'>".$shortUrl."</a><br/><br/>" : "There was an error shortening your url.<br/><br/>";
        $mailBody .= "The URL back to the sales form: For sales rep use only, <strong>Do not give to the customer</strong>.:<br/>";
        $mailBody .= "<span style='font-style: italic;'>Some email clients add special characters to long urls. If the link does not work then copy and paste it into your browser.</span><br/>";
        $mailBody .= "<a href='".$salesUrl."'>".$salesUrl."</a><br/><br/>";

        return ($this->sendEmail($params['repEmail'], $mailSubject, $mailBody));
    }

And here’s the URL I receive in my email, you’ll notice the space ‘…BhsNKq Jsd_x4…’ in the middle of the URL. This happens in a different place each time even if I’m sending the exact same url. To prove this I hard coded this url without a space in the emailRep method and sent it multiple times. The space moved around.

http://example.com/admin/index.php?fdJdj9QgFAbgXzPcNJ3AAdbxgotxdk28cNRMjPESW9yihVbKxHR_vaeU7TSZxqSfHDhPX9Jg-lPneu1H9cFHE7yJxUcdfpto_XNxtv6XHkgw_Vk7oy7aFRdnYzONPDltWxV01Zi23glqnU-z91XnpvrnpvNGSXYo4Q0t6UEKUmUp9Sh28JC7Va01Pmaibcc83M8dpCzzKYn5H_rX_BhsNKq Jsd_x4w7e4zHqputSWdc1Uwzezt2LS5xGQJHKxlF98qbzUZMhauxw_k5ebK8YPwDFr776GEb11WPzGtfhjIFE68zL9H2l3FOCFXea5qkHUmO9pCihThlegDLAHamuIeCmTiXSGv8cm_TorL-6q8NnYuvp6nEfpntthgrvx3enkhWP-FJ0P4vYYAvyJ45pbR9slaw9pbPLsnu4d9nNZSuXJZdll2WXJRc2XKYgu0zRvcwuqBSVwuzylQu4ILugxOJCciG7kF1Qx8vjZl5Y8sIqL59dRu9dfnP5yuXJ5dnl2eXJ3crLl7x8lVeoFJWKe1co_uoK_B1eXZFckV2RXaG-fHvazCuWvGKVV84u23DlzZUrVyZXZldmVyZ3K69c8so57z8

Here is the code I use to encode / decode the url paramaters before sending it through the email.

class UrlEncoder {
    function compressUrl($url) {
        return rtrim(strtr(base64_encode(gzdeflate($url, 9)), '+/', '-_'), '=');
    }

    function uncompressUrl($url) {
        $startParams = strrpos($url, "?");

        if($startParams) {
            $paramaterString = substr($url, $startParams);
            $host = substr($url, 0, strrpos($url, "?"));
            $uncompressedParamaters = gzinflate(base64_decode(strtr($paramaterString, '-_', '+/')));
            return $host."?".$uncompressedParamaters;
        } else {
            return NULL;
        }
    }
}

How do I prevent this space? I know I could shorten the URL with something like bit.ly however its an internal tool. I feel like there must be a way to stop the space from being inserted.

How to&Answers:

Who in their right mind uses a 650-character long query string?

My recommendation is to save the query-string server-side. Put it in a database with an AUTO_INCREMENT field, then you can get an ID for it. Then you can just send the URL as http://example.com/?email_key=ID_GOES_HERE, a much shorter URL. Then just look up the query string from the database.

Done.

Answer:

I have what you need, http://www.9lessons.info/2009/01/split-url-from-sentence-using-php.html. Create tinyurl links using API,nothing in the database 🙂

Answer:

Ok,I had same issue. My solution was my own link shrinking… Make new table in database with few rows, few lines of code in your old script, and new page for redirect… This is shortest explanation, if you need some help,just ask 🙂

EDIT:

    function emailRep() {
    $params = $this->getParamaterArray();
    $shortUrl = $this->getShortUrl();
    $salesUrl = $this->getSalesFormUrl();
/***********************************************************************************/   
    $arr = str_split('QWERTYUIOPLKJHGFDSAZXCVBNM123456789qwertyuioplkjhgfdsazxcvbnm'); // get all the characters into an array
    shuffle($arr); // randomize the array
    $arr = array_slice($arr, 0, 6); // get the first six (random) characters out
    $short = implode('', $arr); // smush them back into a string
    mysql_query("INSERT INTO shortlinks VALUES(NULL, '$salesUrl', '$short')");
/*******************************************************************************************/

    $mailSubject = "Return to the sales order form for ".$params['clientName']." at ".$params['company'].".";

    $mailBody = "The following information is from an order created on, ".date("l, F j, Y \a\t g:i a").",<br/><br/>";
    $mailBody .= "Customer Contact Information:<br/>";
    $mailBody .= "Name: ".$params['clientName'] params['company']."<br/>";
    $mailBody .= "Shortened Url to Send to the Customer:<br/>";
    $mailBody .= ($shortUrl) ? "<a href='".$shortUrl."'>".$shortUrl."</a><br/><br/>" : "There was an error shortening your url.<br/><br/>";
    $mailBody .= "The URL back to the sales form: For sales rep use only, <strong>Do not give to the customer</strong>.:<br/>";
    $mailBody .= "<span style='font-style: italic;'>Some email clients add special characters to long urls. If the link does not work then copy and paste it into your browser.</span><br/>";
    $mailBody .= "<a href='".$short."'>".$short."</a><br/><br/>"; // Rename $salesUrl to $short

    return ($this->sendEmail($params['repEmail'], $mailSubject, $mailBody));
}

And redirect page:

$token=$_GET['token']; // like http://example.com/out.php?token=ahgByT or make it cleaner with htaccess
$qry=mysql_query("SELECT * FROM links WHERE short='$token'");
$arr=mysql_fetch_array($qry);
$out=$arr['long_link'];
header("Location: ".$out);
?>