当页面作为电子邮件发送时,链接中的空格或%20将变为+符号

时间:2010-04-25 10:39:01

标签: php url

我正在创建一个接受新闻项目(标题,文章,网址)输入的网络应用程序。它有一个页面news.php,它创建了为指定日期输入的所有新闻项的摘要,如下所示:

News
4/25/2010

Title 1
[URL 1]
Article 1

Title 2
[URL 2]
Article 2

依旧......

我还有另外两个页面,即preview.phpsend.php,两者都通过file_get_contents()调用来调用news.php。

除非URL包含空格,否则一切正常。在预览期间,URL将被打开(FF:空格是空格,Chrome:空格是%20)。但是,在发送期间,当作为电子邮件收到时,网址不会被打开,因为空格会转换为+符号。

例如:

  
      
  1. 预览FF:http://www.example.com/this是   link.html
  2.   
  3. 在Chrome中预览:http://www.example.com/this%20is%20the%20link.html
  4.   
  5. 在两种浏览器中均视为电子邮件:http://www.example.com/this+is+the+link.html
  6.   

只有#3不起作用(链接无法打开)。

为什么在预览时网址中的空格是正确的(空格或%20),但在电子邮件中收到时不正确(+),实际上同一页面是由同一个news.php生成的?

任何帮助表示赞赏:)


编辑:

preview.php:

$HTML_version = file_get_contents('news.php');
echo $HTML_version;

send.php

$HTML_version = file_get_contents('news.php');
$body = "$notice_text

--$mime_boundary
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit

$TEXT_version

--$mime_boundary
Content-Type: text/html; charset=us-ascii
Content-Transfer-Encoding: 7bit

$HTML_version

--$mime_boundary--";
//some other code here to send the email

news.php:

<a href="<?php echo $url ?>">attachment</a>
//the $url there contains spaces

2 个答案:

答案 0 :(得分:2)

+符号是空间或%20的遗留替代品,因此它们应该可以正常工作。由于他们不这样做,我建议您手动将URL中的所有空格转换为%20。这应该可以解决问题。

答案 1 :(得分:1)

您使用的是哪个邮件客户端?邮件客户端对HTML的处理受到极端限制和错误的影响。

<a href="<?php echo $url ?>">attachment</a>
//the $url there contains spaces
根据定义,

URL不包含空格。如果您在HTML中的链接中包含空格:

<a href="x y.z">

浏览器通常会通过编码为x%20y.z来修复您的错误。然而,这不是标准化的行为,您不应该依赖它。我想,可能有些狡猾的邮件客户端可能被错误地“修改”到x+y.z,而这不起作用,因为URL的路径部分中的+ 表示空格。

使用rawurlencode()进行网址编码。使用此函数,空格将转换为%20,这适用于URL路径部分查询字符串。 PHP错误命名的urlencode()函数改为编码为+,这仅适用于查询字符串中的表单数据。

每次将字符串输出为HTML时,您还需要使用htmlspecialchars()

$name= 'this is the link';
$url= 'http://www.example.com/'.rawurlencode($name).'.html';

<a href="<?php echo htmlspecialchars($url); ?>">link</a>