how to grab the relative path of a file with php - php

i am trying to catch the relative path to a file to create a share link.
From my httpdocs folder on the webserver, my file is here:
jack/single/uploads/folder1/image.jpg
The var $dir . '/' . $file gives me this output:
uploads/folder1/image.jpg
realpath($dir . '/' . $file gives me this output:
/home/vhosts/example.com/subdomains/develop3/httpdocs/jack/single/uploads/folder1/image.jpg
What i want to achieve is this output:
`http://develop3.example.com/jack/single/uploads/folder1/image.jpg`
How can i achieve this, so that i can create a share link?

You could use preg_replace on the output of realpath to replace everything up to httpdocs with your site's URL:
echo preg_replace('#^' . preg_quote($_SERVER['DOCUMENT_ROOT']) . '[\\\\/]#', "{$_SERVER['HTTP_HOST']}/", realpath('test6.php')) . "\n";

You can use $_SERVER['HTTP_HOST'] to get you site's name:
function get_link($to_file){
return "https://".$_SERVER['HTTP_HOST']."/jack/single/".$to_file;
}
echo get_link($dir . '/' . $file);
Change the function's url parts according to your project (do you use https or http? Will /jack/single always be the parent folder of uploads?)

Related

php rename (move) from one dir to another that is two levels back

my script file path is:
C:\xampp\htdocs\wordpress\wp-content\plugins\test\test.php
I need to run code from this path that will move images from path:
C:\xampp\htdocs\wordpress\wp-content\uploads\2017\04
to:
C:\xampp\htdocs\wordpress\wp-content\uploads\images
My problem is that I have no idea how to force "rename" go two directories back in path.
I was trying something like:
$srcPath = realpath(dirname(__FILE__) . '/../..' . '/uploads/2017/04/obrazek.png');
error I'm getting atm (I've changed my folder permissions, so maybe it is something with path?):
Warning: rename(C:\xampp\htdocs\wordpress\wp-content\uploads\2017\04\obrazek.png,C:\xampp\htdocs\wordpress\wp-content\uploads\images): access denied
. (code: 5) in C:\xampp\htdocs\wordpress\wp-content\plugins\uploadsdir-manager\test.php on line 16
edit rename code:
$srcPath = realpath(dirname(__FILE__) . '/../..' . '/uploads/2017/04/obrazek.png');
$destPath = realpath(dirname(__FILE__) . '/../..' . '/uploads/images');
/*$srcDir = opendir($srcPath);*/
echo $srcPath ;
sleep(1);
rename($srcPath, $destPath);
From looking at it, it looks wrong
$srcPath = realpath(dirname(__FILE__) . '/../..' . '/uploads/2017/04/obrazek.png');
it should be
$srcPath = realpath(dirname(__FILE__) . '../..' . '/uploads/2017/04/obrazek.png');
You have an extra / slash at the beginning.
It seems that you're in a Windows machine, so you're using the wrong type of slashes: /../..' . '/uploads/2017/04/obrazek.png'
You could try to replace them with backslashes:\..\..\uploads\2017\04\obrazek.png'
Or you could try something like this:
$path = substr($srcPath, 0, strrpos($srcPath, '\20'));
// $path now contaits: 'C:\xampp\htdocs\wordpress\wp-content\uploads';
// Then you can do:
$srcPath = $path . '\images';
Regarding the warning error:
Warning: rename(C:\xampp\htdocs\wordpress\wp-content\uploads\2017\04\obrazek.png,C:\xampp\htdocs\wordpress\wp-content\uploads\images): access denied. (code: 5) in C:\xampp\htdocs\wordpress\wp-content\plugins\uploadsdir-manager\test.php on line 16
It seems that you try to rename a file to directory, so probably you forgot to append the file name to the new path.
$srcPath contains a file. $destPath contains a directory, but it should contain the file name.
I've finally after many hours.. find out how to fix it so here you go:
$srcPath = (realpath (dirname(__FILE__) . '\..\..' . '\uploads\2017\04') . '\obrazek2.png');
$destPath = (realpath (dirname(__FILE__) . '\..\..' . '\uploads\images') . '\obrazek2.png');
rename ($srcPath , $destPath );
The key was adding file name . '\obrazek2.png' after dirname (), because if filename is inside dirname () and it is destination path in rename, then it returns empty... :)
Not sure if I'm clear enough, because of my English, but it works and hopes it will help someone.

PHP: File cannot be downloaded ("404 Not Found" message)

I am working on a website of a client for which I didn't write the code. I have troubles making files downloadable.
It is about a subdomain where users can download course files.
The website files are contained in the folder "courses" (on the root level).
The file for displaying the downloadable course files is contained in
"courses/displayfiles.php".
The downloadable files are contained in a folder in "courses/downloadfolder". Inside this folder, each user has his own
files folder which as its name has the user id.
displayfiles.php: The following code successfully displays all files that can be downloaded by the logged-in user:
$path = "downloadfolder/" . $_SESSION['userId'] . "/";
$files = array();
$output = #opendir($path) or die("$path could not be found");
while ($file = readdir($output)) {
if (($file != "..") and ($file != ".")) {
array_push($files, $file);
}
}
closedir($output);
sort($files);
foreach ($files as $file) {
echo '<a class="imtext" href="downloadfolder/' . $_SESSION['userId'] . '/' . $file . '/">' . $file . '</a><br/>';
}
So what does not work about this code: When a user clicks on a file, I get a "404 Not Found" message that the file was not found. How can this be?
Why does displaying the files totally works fine, but at the same time I get a 404 error when clicking a file? The files path ($path) must be correct, or not? What further investigations do I need to take in order to solve this problem?
* UPDATE *
I decided to modify the files loop as followed (changing the href):
foreach ($files as $file) {
echo '<a class="imtext" href="http://'.$_SERVER['HTTP_HOST']. '/downloadfolder/' . $_SESSION['courseId'] . '/' . $file . '/">' . $file . '</a><br/>';
}
Still, when I click on a file, I get a 404 Not Found error. How can this be?
You have to look where the webroot of your page is, where the php file generating the list is located and wherer the files are.
Your generated link is relative to the php file generating the link, which might not be corresponding to the URL in the browser. I'd try to make this link relative to the webroot (note the leading slash!)
echo '<a class="imtext" href="/courses/downloadfolder/' . $_SESSION['userId'] . '/' . $file . '/">' . $file . '</a><br/>';
If that guessed solution doesn't work please provide the current URL of the page where this links are generated and one generated link, so we can help you better.

file_exists() not working codeigniter

I am working with codeigniter. I want to display images but if some image is not exist it should show image-not-found-medium.jpg which is dummy image..
below is my code
<?php
$image_path_medium = site_url('assets/images-products/medium');
$image_not_found_medium = $image_path_medium . "/" . "image-not-found-medium.jpg";
$image_name_with_path = $image_path_medium . "/" . $home_technology[$key]->product_sku . "-" . "a" . "-medium.jpg";
if (file_exists($image_name_with_path)) {
echo $image_name_with_path;
} else {
echo $image_not_found_medium;
}
?>
but it always shows $image_not_found_medium i think there is problem with my if condition.
Please help.
<?php
$image_path_medium = site_url('assets/images-products/medium');
$image_not_found_medium = $image_path_medium . "/" . "image-not-found-medium.jpg";
$image_name_with_path = $image_path_medium . "/" . $home_technology[$key]->product_sku . "-" . "a" . "-medium.jpg";//this is your image url
$image_file_path=FCPATH.'assets/images-products/medium'. $home_technology[$key]->product_sku . "-" . "a" . "-medium.jpg";//this is your file path
if (file_exists($image_file_path)) //file_exists of a url returns false.It should be real file path
{
echo $image_name_with_path;
}
else
{
echo $image_not_found_medium;
}
?>
You are using absolute path for file existence which is wrong. You have to use real path because the file_exists() function checks whether or not a file or directory exists on the current server.
If your assets folder is placed in root then just use getcwd() - Gets the current working directory as
$image_path_medium = getcwd().'assets/images-products/medium';
Otherwise give the proper path to the assets folder like
$image_path_medium = getcwd().'application/views/assets/images-products/medium';
Instead of file_exists() prefer is_file() when checking files, as file_exists() returns true on directories. In addition, you might want to see if getimagesize() returns FALSE to make sure you have an image.
Use like this.
$g = base_url().'upload/image.jpg';
if(file_exists($g) !== null){//your code..}
This is works for me in CI.

Load Different config file based on domain name

I want to be able to load a different config file based on the domain name using purely PHP.
Currently my config file loads using the following
# Look for a config.php in the /themes/themeName/ folder
if ( ! defined('MULTI') && file_exists($tmp = WWW_ROOT . '/themes/' . $CONFIG['theme'] . '/config.php') ) {
But i need to be able to add if domain is domain1.com load config from /theme/domain1 or if it is domain2.com load from /theme/domain2 and if it is not either of these domains loads from /theme/default.
This is used when a domain name is parked ontop of another domain so the content is all the same except for the config files.
I was thinking something along the lines of
if ($_SERVER['HTTP_HOST']="domain1.com")
else if ($_SERVER['HTTP_HOST']="domain2.com")
else
Just not sure how to properly format that or it that would be the best way to do it.
$themes_path=array(
'domain1.com'=>'foldername1',
'domain2.com'=>'foldername2'
);
if (isset($_SERVER['HTTP_HOST']) && file_exists(WWW_ROOT . '/themes/' . $themes_path[$_SERVER['HTTP_HOST']] . '/config.php'){
include(WWW_ROOT . '/themes/' . $themes_path[$_SERVER['HTTP_HOST']] . '/config.php');
}
i think direct include $_SERVER['HTTP_HOST'] not very good.
if (isset($_SERVER['HTTP_HOST']) && file_exists(WWW_ROOT . '/themes/' . $_SERVER['HTTP_HOST'] . '/config.php')
include(WWW_ROOT . '/themes/' . $_SERVER['HTTP_HOST'] . '/config.php');
else
include(WWW_ROOT . '/themes/default/config.php');

symlink directory

Can I get an eyeball on my symlink?
I'm trying to download a file from one directory, while the file actually exists in another.
I've got the actual file, and the symlink in seperate subdirectories, but both reside in the public html(both are web accessible).
I've verified the file and file location on my (shared Linux) server by going to the file directly.
The link is being created (I've used readlink, is_link, and linkinfo), and I can see it when I FTP in.
I believe I am probably just having a misunderstanding of the directory structure.
I put the file here: ./testdownload/
I put the symlink here: ./testDelivery/
<?php
$fileName = "testfiledownload.zip";//Name of File
$fileRepository = "./testdownload/";//Where the actual file lives
$downloadDirectory = "./testDelivery/";//Where the symlink lives
unlink($downloadDirectory . $fileName); // Deletes any previously exsisting symlink (required)
symlink($fileRepository . $fileName, $downloadDirectory . $fileName);
$checkLink = ($downloadDirectory . $fileName);
if (is_link($checkLink))
{
echo ("<br>Symlink reads: " .readlink($checkLink) . "<br>");
echo ("<br>LinkeInfo reads: " . linkinfo($checkLink));
}
?>
<p><a href="<?php echo ("/testDelivery/" . $fileName); ?>"</a>SymLink</p>
<p><a href="<?php echo ("/testdownload/" . $fileName); ?>"</a>regular link</p>
Everything looks right to me....but the link won't work.
Help?
Ultimately, I will put the source data outside the public area...this is just for testing.
(I'm trying to find a better solution for download than chunking out fread which fails for poor connections. (200-400MB files))
My problem (appears) to be not providing the absolute path for the symlink.
I've added the absolute path below to the same code above, to give a working copy:
<?php
$absolutepath = ( $_SERVER['DOCUMENT_ROOT']);
$fileName = "testfiledownload.zip";//Name of File
$fileRepository = "/testdownload/";//Where the actual file lives
$downloadDirectory = "/testDelivery/";//Where the symlink lives
unlink($absolutepath .$downloadDirectory . $fileName); // Deletes any previously exsisting symlink (required)
symlink($absolutepath . $fileRepository . $fileName, $absolutepath. $downloadDirectory . $fileName);
$checkLink = ($absolutepath . $downloadDirectory . $fileName);
if (is_link($checkLink))
{
echo ("<br>Symlink reads: " .readlink($checkLink) . "<br>");
echo ("<br>LinkeInfo reads: " . linkinfo($checkLink));
}
?>
<p><a href="<?php echo ("/testDelivery/" . $fileName); ?>"</a>SymLink</p>
<p><a href="<?php echo ("/testdownload/" . $fileName); ?>"</a>regular link</p>
This original post, is a duplicate (though I didn't see it until now)
Create a valid symlink for PHP file
(Most of the answers given for that question were wrong however--but the original poster figured it out, and it worked for me too)

Categories