Search code examples
phphyperlinkpreg-matchportal

PHP how to make an uploaded file link is internal ip when internally and public ip when in public with this snippet i got?


I am doing a php portal.

i did an announcement section where user can post message and attach a file.

so in this situation, a user has uploaded one and at the page, there will be a hyperlink for the attachment. if i hover on it, i can see this "192.168.0.100/Announcement/file.pdf"

so logically if im in the internal network and click on that it would not be a problem as it can get the file from that ip.

next situation is i have forwarded the server ip so that public can access from outside. now i'm as a user accessing from outside.

so if i were to go to the announcement location and hover on it again it will show the same link "192.168.0.100/Announcement/file.pdf". I will definitely wont be able to open it as that ip is internal.

so i am thinking how can i make it when i'm internal, the ip is the internal one and when im outside,the ip link would be the public?

i got this snippet from a ex colleague but i dont really know what the code does. Can someone help me explain this? i tried searching this thing i want to do on the net,but i dont have a proper keyword for it.

below is the snippet:

<?php
//filename constant.php

define('SERVERIP',((preg_match("/^192\.168/i",$_SERVER['REMOTE_ADDR']))?'192.168.0.100':'175.136.xxx.xxx'),true);
?> 

And below is part of the code in the page for the announcement and attachment:

include('_include/constant.php');
$dir = "C:/Inetpub/wwwroot/Announcement/";
$http = sprintf('http://%s/Announcement/',SERVERIP);

print '<td class="middle '.$CLASS.'" align="left" height="20">'.'<a href="http://'.SERVERIP.'/Announcement/'.$filename.'" target="_blank">'.$filename .'</a></td>';

Can any php pros here help me to understand whats happening so that next time i know what i'am actually implementing?


Solution

  • What you have is a ternary operation, the results of which are being assigned to the constant SERVERIP. It is using a regex to match against the $_SERVER['REMOTE_ADDR'], if it begins with 192.168, then it gets the 192.168 value, otherwise it gets the 175.136 value. And for some reason it is passing true to enforce a case insensitive search.

    You can read more on define within the PHP docs.

    Lighter example of ternary op:

    $overlyComplex = true;
    
    $thatDudesCodeSucks = (true === $overlyComplex) ? 'yes' : 'no';
    
    // Shorthand for
    if (true === $overlyComplex) {
        $thatDudesCodeSucks = 'yes';
    } else {
        $thatDudesCodeSucks = 'no';
    }
    
    var_dump($thatDudesCodeSucks); // echos yes