Mutlak url almak için nasıl

4 Cevap php

src <img> mutlak url almak için genel işlevinin nasıl uygulanacağını, http://test.com/directory/hi.html gibi, hedef web sayfasının url yanı sıra, bilinen Görüntünün?

4 Cevap

I would:

  1. Img URL bir konak değeri ile başladı kontrol edin, ve eğer öyleyse zaten mutlak olduğu gibi, geri
  2. Baz konak değerini almak için web sayfası URL ayrıştırma
  3. Img src kök veya dizine göreli olup olmadığını kontrol edin ve uygun şekilde taban konak değerine eklenecek.

parse_url() burada seçim fonksiyonu olacak. Ben cesur hissediyordum, bu yüzden senin için uygulanan:

function getAbsoluteImageUrl($pageUrl,$imgSrc)
{
    $imgInfo = parse_url($imgSrc);
    if (! empty($imgInfo['host'])) {
        //img src is already an absolute URL
        return $imgSrc;
    }
    else {
        $urlInfo = parse_url($pageUrl);
        $base = $urlInfo['scheme'].'//'.$urlInfo['host'];
        if (substr($imgSrc,0,1) == '/') {
            //img src is relative from the root URL
            return $base . $imgSrc;
        }
        else {
            //img src is relative from the current directory
               return 
                    $base
                    . substr($urlInfo['path'],0,strrpos($urlInfo['path'],'/'))
                    . '/' . $imgSrc;
        }
    }
}

//tests

$host = 'http://test.com/directory/hi.html';
$imgSrc = '/images/lolcat.jpg';
echo getAbsoluteImageUrl($host,$imgSrc);
//echos  http//test.com/images/lolcat.jpg 

$host = 'http://test.com/directory/hi.html';
$imgSrc = 'images/lolcat.jpg';
echo getAbsoluteImageUrl($host,$imgSrc);
//echos  http//test.com/directory/images/lolcat.jpg

$host = 'http://test.com/directory/hi.html';
$imgSrc = 'http://images.com/lolcat.jpg';
echo getAbsoluteImageUrl($host,$imgSrc);
//echos  http://images.com/lolcat.jpg

Ben de soruyu anlamak Eğer aşağıdaki gibi uygulama kök APPLICATION_PATH tanımlamak ve daha sonra kullanabilirsiniz:

define('APPLICATION_PATH', realpath(dirname(__FILE__)));
...
<img src="<?php APPLICATION_PATH ?>/path/to/image.png" alt="" />
...

parse_url, sen böyle bir şey yapabilirsiniz:

  1. Parçaları (düzeni, etki, yol, dosya, sorgu, fragmanı) içine page url Ayrıştırma
  2. Rebuild the url for the img url, depending on how the img url is.
    • Img url '/', mutlak bir url var ile başlar, bu yüzden "$scheme://$domain$img_url" gibi img url oluşturmak
    • Img url '/' ile başlamayan, bu yüzden göreceli, yani biz "$scheme://$domain/$path/$img_url" gibi img url oluşturmak. Bu sunucu tarafından çözümlenen olacak çünkü img_url, ".. /. /" Tarzı ise, bu da çalışır.

Ayrıca bir programa veya etki alanı ('xx :/ /' veya 'xx.x /') ile başlayan img adresler hariç isteyebilirsiniz.