codesuck codesuck - 1 month ago 5
PHP Question

Replacing php realpth when outputing to users

I used php

real path
to get actual path of files and directory to delete and after deleted i will print all deleted
items. But my problem is that it also show the real path where the file source is and i don't want to show it to users
is there any way i can hide the pay and only show the file example.

I don't like it to look like this


[File]: /mnt/wef66/d2/81/557642661/htdocs/useruploads/myfiles/imagefolder/mosaic_1.jpg

[File]: /mnt/wef66/d2/81/557642661/htdocs/useruploads/myfiles/imagefolder/room_home_1.jpg

[Directory]: /mnt/wef66/d2/81/557642661/htdocs/useruploads/myfiles/imagefolder


Is there anyway i can make it look this way using rejex or any method please i need help i have to remove
/mnt/wef66/d2/81/557642661/htdocs/



[File]: www.example.com/useruploads/myfiles/imagefolder/mosaic_1.jpg

[File]: www.example.com/useruploads/myfiles/imagefolder/room_home_1.jpg

[Directory]: www.example.com/useruploads/myfiles/imagefolder


Maybe using something like this

echo preg_replace("/mnt/wef66/d2/81/557642661/htdocs", "www.example.com", "[File]: /mnt/wef66/d2/81/557642661/htdocs/useruploads/myfiles/imagefolder/mosaic_1.jpg");


$path = realpath($parentBas);

Answer

I would use configuration variables $privatePath and $publicPath.

So you can concat whichever you want to the relative paths to your directories or files.

For your example:

$privatePath = '/mnt/wef66/d2/81/557642661/htdocs/';
$publicPath = 'www.example.com/';

$pic1RelativePath = 'useruploads/myfiles/imagefolder/mosaic_1.jpg';

$pic1privatePath = $privatePath . $pic1RelativePath;
// /mnt/wef66/d2/81/557642661/htdocs/useruploads/myfiles/imagefolder/mosaic_1.jpg

$pic1publicPath = $publicPath . $pic1RelativePath;
// www.example.com/useruploads/myfiles/imagefolder/mosaic_1.jpg

I think this is easier and more efficient than replacing the paths with regex.

EDIT:

If you have all the real paths in an array, you can loop through it and replace easily all the private paths with the public paths this way:

$paths = [
'/mnt/wef66/d2/81/557642661/htdocs/useruploads/myfiles/imagefolder/mosaic_1.jpg',
'/mnt/wef66/d2/81/557642661/htdocs/useruploads/myfiles/imagefolder/room_home_1.jpg',
'/mnt/wef66/d2/81/557642661/htdocs/useruploads/myfiles/imagefolder'
];

foreach ($paths as &$path) {
  $path = str_replace($privatePath, $publicPath, $path);
}

print_r($paths);
Comments