Absolute URLs with PHP

1

I explain my problem, it's simple, I've solved it, but only locally, it does not work for me if I use this on a normal server.

I modified my .htaccess for friendly URLs, the issue is that I have problems with file paths ( css , images , js , etc).

Because for example, my route is:

  

localhost / project / user / pepito /

So, when I link my CSS or images, normally, it gives me this:

I mean, I'm not taking the file path.

I have this PHP code in a file, to use it to be able to have the absolute URL and not have problems (I already share it with you):

$s = $_SERVER['SERVER_NAME'];
$a = explode('/', $_SERVER['PHP_SELF'], 3);
$completeURL = "http://".$s."/".$a[1];

In this way, you would be saving in the variable completeUrl :

  

link localhost / project

Then, when I'm going to put an image, I would put:

<img src="<?php echo $completeURL; ?>/images/img.png" alt="">

So, if it works, but this in the normal server does not work for me, because it prints me:

  

link

So, what I'm looking for, in a way that I can always print the whole route, without having to change all my codes to work on the server. I have too many routes set in the way I already showed, but if for example, I have an image and use:

<img src="<?php echo $completeURL; ?>/images/img.png" alt="">

This would impress me:

  

link

It would not make sense. How can I solve this problem?

    
asked by Axel Benitez 14.10.2016 в 20:45
source

2 answers

3

There are several ways to do it and you were not that far away.

I leave here a variant with define :

You can create a file, for example: define.php and in that we create the constant defines:

<?php
    define('URL_WEBSITE_COM', 'http://example.com');

    // y otra especialmente para imágenes por ejemplo:
    define('URL_IMAGE', 'http://example.com/images/');

then you include that file in your necessary files and use it in this way:

<img src="<?php echo URL_IMAGE; ?>img.png" alt="">

or

<a href="<?php echo URL_WEBSITE_COM; ?>/Foo">Bar</a>
    
answered by 14.10.2016 в 21:19
0

Well look, I just solved this and that is that xampp is a server simulator so enter as (< src="c: / root / project" >) it does not work with localhost but before any content inside xampp either in the root of the project or whatever but with the notation link so the url can be absolute and you can call it from any php or html from within xampp, ami made me suffer enough to ignore that but now I share to enrich your projects greetings

    
answered by 21.07.2018 в 04:07