PHP unlink file from root-relative path - php

My script is in http://localhost/path/test/index.php and the file I want to delete is in http://localhost/path/media/test.txt.
I want to have the path of the project as a constant PATH which would be path/ in this example. So I tried it with the root-relative path unlink("/" . PATH . "media/test.txt"), which didn't work.
Any ideas how to solve this path problem?

By putting a / at the begining of the unlink, you are telling PHP to dlete from the root of the server's file system, which is unlikely to be the same folder as your localhost (probably /var/www/)
Ideally in web applications, you should define the root of your application in the filesystem, e.g.:
$root = '/var/www/sites/project/';
Then you can unlink like:
unlink( $root . "media/test.txt" );
Alternatively you can unlink by relative, rather than absolute path (as above:)
unlink( '../media/test.txt' );
To get your root, see: this

Related

How to upload file in any directory with PHP

I have created image uploading codes and they're only allowing me to upload image into only directory that is in the same directory as PHP file.
$profile = 'profiles/'.$_FILES['profile']['name'];
if I change it like this:
$profile = 'php_codes/profiles/'.$_FILES['profile']['name'];
it shows me error. I'm using copy() function to upload it.
Please help me to get to know how to upload it in any directory even into any other partition. Thanks for your help.
You will need to provide the error, but it's very likely that the error you are getting is that the directory that you are attempting to copy the file to does not exist. It could also be permission problems, but your confusion seems to be over building a path.
The problem with your code is that your path is relative to the PHP file's location, rather than being a direct path from your root directory. You should read a little bit about how to navigate file structures, but these are the three key things to remember when working in a *nix file system (such as Linux):
If your file path does not start with a slash, then the path will be relative to the directory that the PHP script is in.
If you start your file path with a slash, the path will be relative to the root directory.
You start a path with one or more ../, to traverse to a parent directory.
So for example, let's say you have these three directories, with your PHP script residing in /php_codes:
/php_codes
/php_codes/code_snippets
/profiles
If you wanted to copy the file to php_codes, your path would be relative to the PHP script:
$profiles = $_FILES['profile']['name'];
If you wanted to copy the file to php_codes/code_snippets, again you could just do it relative to your PHP script:
$profiles = "code_snippets/" . $_FILES['profile']['name'];
However, this is an opportunity to also show how you might do it with an absolute path from the root directory. You could use this (note the slash at the beginning of the path):
$profiles = "/php_scripts/code_snippets/" . $_FILES['profile']['name'];
If you want to copy the file to /profiles, which is outside of the /php_codes directory, there are two ways you can do it.
The first way is with an absolute path from the root directory (path begins with a slash), just like the example above:
$profiles = "/profiles/ " . $_FILES['profile']['name'];
Or, you can make it relative, by using ../ to go up one level to the parent directory:
$profiles = "../profiles/ " . $_FILES['profile']['name'];
A quick note about using ../ to go up one directory: you can repeat that as many times as needed, to continue going up a level. For example, if your PHP script was located inside of /php_codes/code_snippets, but you wanted to copy a file to /profiles, then you would have to go up two levels:
$profiles = "../../profiles/ " . $_FILES['profile']['name'];
you can use
$profiles=__DIR__ . "/profiles/" . $_FILES['profile']['name'];
that will work as DIR will be your script directory and then it will be absolute path
I have finally got it! Just using ../profiles and then directory is making it. You just write dots (2) then times you want to go back. If two times, ../../profiles. Thanks for your help.

php check file_exists() out of the third level to the root dir

I struggle with this, any suggestions?
SERVER HTTPDOCS DIR
/images <--MAINDOMAIN - domain.com
/m <--SUBDOMAIN (Third level) ROOT DIR OF m.domain.com
*FROM m.domain.com/test.php*
$dir="../images"; //Trying to read outside the subdomain root dir
if (is_dir($dir)) {
$oggetto = #opendir($dir);
while (false !== ($files = #readdir($oggetto))) {
if($files != "." && $files != "..") {//print filename}
It does not recognize the directory.
From the PHP docs for is_dir(), regarding the first passed parameter:
Path to the file. If filename is a relative filename, it will be checked relative to the current working directory. If filename is a symbolic or hard link then the link will be resolved and checked. If you have enabled safe mode, or open_basedir further restrictions may apply.
In other words, if you specify a relative path, it will be considered relative to the currently executing script, which is why your script works in the first case, but not in the second. Personally I perfer to use full paths when operating on files and directories to make sure I know what I'm pointing at. To poke around a bit and see what I'm talking about try this:
<?php
$current_dir = dirname(__FILE__);
$path = realpath( $current_dir . '/../images' );
var_dump( $path );
In general, PHP frameworks tend to specify some full paths during their bootstrap, like absolute path to the document root, the application folder, the log folder, etc. and then use those paths whenever specifying a path to a file. This is handy and tends to be very stable because the bootstrap file tends to stay in the same filepath, whereas with the problem you are experiencing, your path resolution breaks when you move the script from folder to folder. I say all this by way of saying you might consider creating a "document root" variable in a header file, for example, include that header file in each of your scripts, and then use that variable when you need to create filepaths.

php mkdir windows relative path

I want to create a directory on windows from a PHP script.
My script is in the www/Test directory of Apache and I want to create a folder (fold1) inside www/downloads directory.
Inside the script, I'm using:
$dirName = "../downloads/fold1";
mkdir("{$dirName}");
If I use the full path of dirName like C:\Apache\www\downloads\fold1, it works fine.
But I want to use a relative path since this code will be sent to the client.
I would guess your current directory is different from your files folder, so you have to use a trick:
mkdir(dirname(__FILE__) . "/" . $relative_path);
dirname(__FILE___) returns the absolute path of your current php file. With this you can build an absolut path.

php paths that work on both local (mac) and remote server

I'm testing a website on my local machine and I'm wondering what would be the best way to write paths to make sure they work when I upload the site to its final location.
In general I'm a bit confused about paths, and in many cases I have to 'tweak' each path until it works, so wouldn't want to be forced to do the same on a production site!
I'm not clear when to use $_SERVER['DOCUMENT_ROOT'].
For example, I have a directory that I want to scan, which is just under the root. So why can't I just use "/dirname"?
$dir = $_SERVER['DOCUMENT_ROOT'] . '/uploads'; //this works
// $dir = "/uploads"; //this doesn't work
if (is_dir($dir)) {
//do something..
}
I'm not clear when to use
$_SERVER['DOCUMENT_ROOT']. For
example, I have a directory that I
want to scan, which is just under the
root. So why can't I just use
"/dirname"?
When you work with paths in the php file the root (/) is the root of the filesystem, not the root you get when you visit your website.
So $dir = "/uploads"; gives you the filesystem root.
To minify your problems I would declare a variable in a configuration file that specifies the root of your php application, and use that path+whatever more is needed.
As adamse mentioned, the reason you can't use the '/path' is because it points to the root of the filesystem.
However, instead of declaring a variable that defines the root, I recommend using dirname(__FILE__) to retrieve the full path to the directory that the calling file is in.
From there, append relative path information to the file you want and you end up with a complete path, fully dynamically.
For example, if you want to include the 'header.php' file in the directory above the file that you wish to include it in use:
include(dirname(__FILE__) . '/../header.php');
The beauty of that is that PHP will always automatically convert the forward slash to the directory separator required for the host OS.
I would define a variable/constant that describes the absolute filesystem path to the application. Something like this:
$appDir = rtrim(str_replace('\\', '/', realpath(dirname(__FILE__))), '/');
Then you have this base path you can address your application’s files from:
include $appDir.'/library/foo/bar.php';
Or you even change your include path to that directory:
set_include_path($appDir);

PHP: Saving files with PHP to different root directory?

OK when I save uploaded files with PHP via move_uploaded_file() I cannot use an absolute URL I have to use a relative one. My site has 2 root directories one for the http side and one for the https side: httpdocs and httpsdocs respectively. So if my script is on the https side how can I save the file to a location on the http side?
Thanks!
UPDATE
OK so it seems like I am using the wrong absolute path convention I am doing it like this:
$dir = 'https://www.mydomain.com/masonic_images/';
move_uploaded_file($_FILES['blue_image']['tmp_name'], $dir.$new_name);
move_uploaded_file() doesn't accept URLs for either parameter. The destination is an absolute path on your filesystem.
<?php
$dir = '/var/www/httpsdocs/'; // Adjust to your configuration
move_uploaded_file($_FILES['blue_image']['tmp_name'], $dir.$new_name);
As #apphacker suggested. you can use realpath(__FILE__) to determine the absolute path to a file.
If you cannot use the absolute path because you don't know what the absolute path is, use PHP's realpath() to figure out what it is and then use it.
Are the httpdocs and httpsdocs directories both located in the same parent folder? If so, just use a relative path for the second parameter in move_uploaded_file to place the file in the other root directory.
For example:
$uploaddir = '../httpdocs/';
$uploadfile = $uploaddir . basename($_FILES['myfile']['name']);
This code assumes that the uploading script is located in the httpsdocs root directory, and that you want to save the file into the httpdocs directory.
Note that since you put uploaded files inside httpdocs it could be possible to upload a php file and execute arbitrary code.

Categories