2017-06-19 33 views
0

後面的輸出。在url中使用查詢srting向api發送請求,並使用php

  • 我在我的網站腳本,將前綴所有外部鏈接 像mywebsite.com/redirect_to/?url=externallink.com
  • 因此,假設你正在瀏覽的網頁
    mywebsite.com/redirect_to/?url=gooogle.com

我創建.htaccess規則來處理請求redirect_to.php包含

<a href="<?php $url = $_GET["url"]; echo htmlspecialchars($url); ?>">External Link</a>

  1. 整個過程都很好。

現在,我想我們在redirect_to.php看到,原來的外部鏈接轉換爲短網址

短URL API的工作原理是這樣的:

,當我們瀏覽someurlshortener.com/api.php?url=http://google.com我們得到http://someurlshortener.com/6421

同樣地,我提出<a href="<?php $var = file_get_contents('http://someurlshortener.com/api.php?url=https://google.com'); $output = preg_replace('/<script\b[^>]*>(.*?)<\/script>/is', "", $var); print $output; ?>">Shortened Link</a>

這給了輸出http://someurlshortener.com/34566

  1. 此API請求也正常工作。

然後我試着將這兩個代碼結合起來。像

<a href="<?php $var = file_get_contents('http://someurlshortener.com/api.php?url=<?php $url = $_GET["url"]; echo htmlspecialchars($url); ?>'); $output = preg_replace('/<script\b[^>]*>(.*?)<\/script>/is', "", $var); print $output; ?>">Is it shortened?</a> 

這給出了一個鏈接到http://mywebsite.com/redirect_to/?url=https://google.com這是頁面本身的輸出。

  1. 這不符合我的要求。

所以,請幫我解決這個問題。

回答

0

在實際的鏈接中做了這麼多內聯只會使代碼難以閱讀,重用和容易犯錯誤。例如:file_get_contents('http://someurlshortener.com/api.php?url=<?php $url = ... < ==這裏您試圖打開一個php-塊,這並沒有真正的工作。

我的建議是創建一個這樣做的函數,它將使讀取,重用和維護變得更容易。改變一次,它會改變無處不在。

添加下面的某個地方在腳本中,你要使用它之前:

function buildUrl($url) 
{ 
    // Url encode the link so we can use it in the 
    // query string without breaking anything. 
    $url = urlencode($url); 

    // Get the short url 
    $url = file_get_contents('http://someurlshortener.com/api.php?url=' . $url); 

    // Parse the result 
    $url = preg_replace('/<script\b[^>]*>(.*?)<\/script>/is', "", $url); 

    // Return the result 
    return $url; 
} 

然後,在你的HTML,你只需要調用的函數,就像這樣:

<a href="<?= buildUrl($_GET['url']) ?>">Some link</a> 
+0

作品,像魅力, 順便說一句,不要介意。我是新來的PHP。 –

+0

@SatishNetha不用擔心。每個人都在某個方面對它有所瞭解。只要堅持下去,不要猶豫,問問你是否卡住了。這就是爲什麼這個網站存在。 :-) –