【问题标题】:Getting the actual URL, best practices for this case获取实际 URL,此案例的最佳实践
【发布时间】:2011-01-25 07:33:07
【问题描述】:

我需要在这个链接上插入实际的 URL:

<a href="http://www.facebook.com/sharer.php?u=**MY_URL**&t=<?php echo($title); ?>" target="blank">Share on Facebook</a>

什么方法最好?谢谢!

【问题讨论】:

  • location.href 在 JavaScript 中用于 URL(没有最后一个“/”)
  • 你是指当前页面的URL吗?
  • @JCOC611 如何将它插入到上下文中?
  • 是的,最好使用 JS,因为 PHP 可能会被包含在其中。
  • @DomingoSL 那么我同意 thedom 的回答..

标签: php javascript html


【解决方案1】:

您可以使用超全局$_SERVER 数组;-)

<?php
$myURL = 'http://'. $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
?>

您的链接将是...

<a href="http://www.facebook.com/sharer.php?u=<?php echo($myURL); ?>&t=<?php echo($title); ?>" target="blank">Share on Facebook</a>

// EDIT:
$myURL 应该是 urlencode()d 并检查协议 -->

<?php
$protocol = 'http://';

if(!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' || $_SERVER['SERVER_PORT'] == 443) {
  $protocol = 'https://';
}

$myURL = urlencode($protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
?>

【讨论】:

  • $myURL 在将其插入链接之前必须进行 URL 编码。架构不一定是 http(可能是 https)。 $_SERVER['HTTP_HOST'] 应该被验证。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-13
  • 1970-01-01
  • 2013-01-08
  • 1970-01-01
  • 2015-06-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多