PHP: Cannot see upload directory - php

I have been struggling for a few days trying to find out how come I cannot move a file(move_uploaded_file) from temp to the directory I have setup (/img/uploads/photos).
After alot of testing and head scratching, I decided to write into CakePHP's CakeLog whatever is happening in the upload function.
Although I have physically created :/img/uploads/photos, when I use CakeLog::write('debug', 'Does directory exist?: '.json_encode(file_exists('/img/uploads/photos/'))); it logs false. Or is_dir, also returns false
Why is this happening... Can anyone help me out!

I doubt you have made a directory /img/uploads/photos/ ? It is probably inside the same dir as your other files, somewhere like /var/www/yoursite/img/uploads/photos/ or something like that.
You can use some tricks like $_SERVER{'DOCUMENT_ROOT'}, as you can see over at http://php.net/manual/en/function.file-exists.php

I don't believe you when you say you have created the /img/uploads/photos/ directory. That's an absolute path, counting from the root of the machine. It's more probable that you have created the folder in the web directory somewhere (such as /var/www/img/uploads/photos/ or /home/caboone/public_html/img/uploads/photos/).

The path /img/... means the path is relative to the disk root, i.e. it denotes the img directory in the very top level of your hard disk. I doubt that's where the directory is. Don't start the path with a / to make it relative to the file you're working in. File paths are not URLs!

Use absolute path when moving files from one directory to another.
Use dirname(__FILE__) to get the absolute current working directory, then add
the rest of the path.
Set appropriate permission to the directory, as suggested by #Alex. use chmod() and
set permission to 777 (ugo+w) [user+group+others world-writeable].

Related

php move_uploaded_file always ends up in webroot

Whenever I use move_uploaded_file to my an uploaded file, the file always ends up in my web root. What am I doing wrong? Should the path be relative to my web root, or should it be an absolute path on my file system?
Ultimately what I'm trying to do, it have a folder for php to upload/dowload files. I don't want web bots and anyone else just to be able to access the files, i want only authenticated people using my website to be able to download the files. So this is how I have my file structure laid out:
/var/www/website/public_html
and
/var/www/website/files
and my move_uploaded_file command is like this:
move_uploaded_file($_FILES['txtFileSelector']['tmp_name'], "/var/www/website/files/".$_FILES['txtFileSelector']['name']);
but no matter what i've tried, the file always ends up in
/var/www/website/public_html
I've even tried sending the file in other sub folders of public_html but still no luck.
ah-ha! Destination path is relative!
So the solution for me is:
echo move_uploaded_file($_FILES['txtFileSelector']['tmp_name'], "../files/".$_FILES['txtFileSelector']['name']
Because of the relative pathing, use .../ to go up from the web root, and then move it to the desired storage folder.
CORRECTION
Absolute path or relative path either will work. It was a combination of folder permissions (www-data needs to either be owner or group member with read/write permissions) and me being an idiot and discovering a programming bug. My code was in a php class and the uploading was function. In my constructor I had a bug in my code. When doing OO there's a big difference between
$upload_dir = "/path/to/upload";
and
$this->upload_dir = "/path/to/upload";

Find filepath to public_html directory or it's equivalent using PHP

I'm creating a .php file that will be uploaded to the root directory of a server. I need that .php file to then figure out the path to the public_html folder or it's equivalent.
I need to do this because I want my .php file to be able to be uploaded to the root and used on any hosting account. Because many hosting companies use different file paths to the public_html folder or even call it something different, I'm trying to figure out how to detect it.
Preferable there is a server variable or easy test to do this. If not, the public_html folder will always contain a particular file so maybe I could search for this particular file and get the path that way. I'm just worried about a filename search being heavy on memory.
The .php file that is being executed is located inside the ROOT directory and needs to locate the public_html folder.
Like this: /home/user/file.php
needs to detect
/home/user/public_html/ or /home/user/var/www/ or /home/user/website.com/html/ etc.
The challenge with this is that a server can have very many public_html's so outside of the context of a request there is no real way to find out what that is.
One thing that you might be able to do to get this information from a php script (if you know the url to get to the host) is to create a php file called docroot.php that looks like this.
<?php
if ($_SERVER["REMOTE_ADDR"] == '127.0.0.1'){
echo $_SERVER["DOCUMENT_ROOT"];
}
Then within your file.php your would do something like
$docRoot = trim(file_get_contents("http://www.mydomain.com/docroot.php"));
This makes the assumption that the server can resolve to itself via the local interface by name.
I found this website which provided me with the only good solution I have found after scouring the web...
$root = preg_replace("!${_SERVER['SCRIPT_NAME']}$!", "", $_SERVER['SCRIPT_FILENAME']);
The way this works is by getting the full path of the file and then removing the relative path of the file from the full path.

Server Real Path

I wonder whether someone may be able to help me please.
I'm trying to retrieve the file path for an xml file that I use to in a image gallery script I'm building.
My folder structure is as follows:
website/development/UploadedFiles/'username'folder/'location'
folder/file.xml
I've put together this to try and get me the path:
<?php
chdir('var/www/');
echo realpath('./././file.xml');
?>
But I receive the following error:
Warning: chdir() [function.chdir]: No such file or directory (errno 2)
in /homepages/2/d333603417/htdocs/development/real.php on line 2
I'm sure that I'm making a beginners mistake here, but I wanted to have at least given it a try. I just wondered whether someone could possibly take a lok at this please and let me know where I'm going wrong.
Many thanks
it's because there are 2 types of Unix path's:
absolute path: /var/www/ (always begins with /)
relative path: var/www/ (relative to the place where you are. has no / in the beginning)
If you chdir to /var/www/ you get to /var/www/.
If you chdir to var/www/ you chdir to <directory_where_you_are>/var/www/
Also you have a mistake in ./././.
./ - means your current directory. Using ./././ leaves you in current directory.
If you'd like to move up by directory tree use ../ (means parent directory).
If you want to obtain the absolute path of a file relative to your php file, it is usually easier to do something like dirname(__FILE__).'/path/to/file' since it's much more predictable than using chdir with relative paths. You can also just echo it for debugging.
So in your case, it looks like you might want to have something like this:
$file = dirname(__FILE__)."/UploadedFiles/$username/$location/file.xml";
If you need to traverse directories upwards, you do it with multiple dirnames:
$file = dirname(dirname(__FILE__))."/UploadedFiles/$username/$location/file.xml";

Include files from parent or other directory

I'm needing to include a file from the parent directory, and other sub-directories, into a sub-directory. I've done it before by simply using include('/rootdirectory/file.php'); but now it won't seem to work.
Just wondering how I can do this, thanks.
Here's my exact line:
include('/forums/groups.php');
It's giving me this error(the page still runs):
Warning: include(/forums/groups.php) [function.include]: failed to
open stream: No such file or directory in
C:\xampp\htdocs\forums\blog\posts.php on line
Warning: include() [function.include]: Failed opening
'/forums/groups.php' for inclusion
(include_path='.;C:\xampp\php\PEAR') in
C:\xampp\htdocs\forums\blog\posts.php on line 3
include() and its relatives take filesystem paths, not web paths relative to the document root. To get the parent directory, use ../
include('../somefilein_parent.php');
include('../../somefile_2levels_up.php');
If you begin with a /, an absolute system file path will be used:
// Full absolute path...
include('/home/username/sites/project/include/config.php');
If your server is not resolving the file from the parent directory using
include '../somefilein_parent.php'
try this (using the parent directory relative to the script):
include __DIR__ . "/../somefilein_parent.php";
Here's something I wrote with that problem in mind:
<?
function absolute_include($file)
{
/*
$file is the file url relative to the root of your site.
Yourdomain.com/folder/file.inc would be passed as
"folder/file.inc"
*/
$folder_depth = substr_count($_SERVER["PHP_SELF"] , "/");
if($folder_depth == false)
$folder_depth = 1;
include(str_repeat("../", $folder_depth - 1) . $file);
}
?>
hope it helps.
Depends on where the file you are trying to include from is located.
Example:
/rootdir/pages/file.php
/someotherDir/index.php
If you wrote the following in index.php:
include('/rootdir/pages/file.php');it would error becuase it would try to get:
/someotherDir/rootdir/pages/file.php Which of course doesn't exist...
So you would have to use include('../rootdir/pages/file.php');
In laymans terms, and practicality, I see this as an old DOS trick/thing. Whoa! What was that? DOS? Never heard of it!
".." backs you out of the current sub-directory one time to a higher folder/directory, and .. enter typed twice backs you out too 2 higher parent folders. Keep adding the ".. enter" back to back and you will soon find yourself at the top level of the directory.
As for Newbies to understand this better, consider this (in terms of the home PC or "C:\ drive" if you know what that means, rather than the web-servers/host "root directory" ). While your at it, Consider your website existing somewhere on your home PC's hard drive, buried in some folder under the C:\ drive. Lastly, you can think of it as ".." is back one directory and "/" is forward one directory/folder.
Now!
If you are using the command prompt and are within the "myDocuments" folder of your PC you must back out of that folder to get closer to the higher directory "C:\" by typing the "../".
If you wanted to access a file that is located in the widows directory while you are still in the myDocuments folder you would theoretically type ../windows; in reality of DOS command prompt you would simply type .., but I am setting you up for the web. The / redirects forward to another directory naturally.
Using "myDocuments" lets pretend that you created 2 folders within it called "PHP1" and "PHP2", in such we now have the folders:
C:\myDocuments\PHP1
C:\myDocuments\PHP2
In PHP1 you place a file called index.php. and in PHP2 folder you placed a file called Found.php. it now becomes:
C:\myDocuments\PHP1\index.php
C:\myDocuments\PHP2\found.php
Inside the
C:\myDocuments\PHP1\index.php file you would need to edit and type something like:
<?php include ('../php2/found.php')?>
The ../ is positional thus it considers your current file location "C:\myDocuments\PHP1\index.php" and is a directive telling it to back out of PHP1 directory and enter or move forward into PHP2 directory to look for the Found.php file. But does it read it? See my thoughts on trouble shooting below.
Now! suppose you have 1 folder PHP1 and a sub-folder PHP2:
C:\myDocuments\PHP1\PHP2
you would simply reference/code
<?php include('/PHP2/found.php') ?>
as PHP2 exist as a sub-directory, below or within PHP1 directory.
If the above does not work it may have something to do with access/htaccess or permission to the directory or a typo. To enhance this...getting into trouble shooting...If the "found.php" file has errors/typo's within it, it will crash upon rendering at the error, such could be the reason (require/require_once) that you are experiencing the illusion that it is not changing directories or accessing the file.
At last thought on the matter, you may need to instantiate your functions or references in order to use the included/require "whatever" by creating a new variable or object such as
$newObject = new nameobject("origianlThingy");
Remember, just because you are including/requiring something, sometimes means just that, it is included/required to run, but it might need to be recreated to make it active or access it. New will surely re-create an instance of it "if it is readable" and make it available within the current document while preserving the original. However you should reference the newly created variable $newObject in all instances....if its global.
To put this in perspective of some web host account; the web host is some whopping over sized hard-drive (like that on your PC) and your domain is nothing more than a folder they have assigned to you. Your folder is called the root. Inside that folder you can do anything you are allowed to do.
your "one of many ways" to move between directories/folders is to use the ../ however many times to back out of your current in reference to folder position you want to find.
In my drunken state I realize that I know too much to be sane, and not
enough to be insane!"
Any path beginning with a slash will be an absolute path. From the root-folder of the server and not the root-folder of your document root. You can use ../ to go into the parent directory.
You may interest in using php's inbuilt function realpath().
and passing a constant DIR
for example:
$TargetDirectory = realpath(__DIR__."/../.."); //Will take you 2 folder's back
String realpath() :: Returns canonicalized absolute pathname ..
I took inspiration from frank and I added something like this in my "settings.php" file that is then included in all pages when there is a link:
"settings.php"
$folder_depth = substr_count($_SERVER["PHP_SELF"] , "/");
$slash="";
for ($i=1;$i<=($folder_depth-2);++$i){
$slash= $slash."../";
}
in my header.php to be included in all pages:
a href= .... php echo $slash.'index.php'....
seems it works both on local and hosted environment....
(NOTE: I am an absolute beginner )
Had same issue earlier solved like this :
include('/../includes/config.php'); //note '/' appearing before '../includes/config.php'
the root directory (in PHP) is the directory of the file that is pinged. For example, I go to http://localhost/directory/to/file/index.php, the root directory will be "/dictory/to/file", since it's the one that you've made a web request for.
I can't believe none of the answers pointed to the function dirname() (available since PHP 4).
Basically, it returns the full path for the referenced object. If you use a file as a reference, the function returns the full path of the file. If the referenced object is a folder, the function will return the parent folder of that folder.
https://www.php.net/manual/en/function.dirname.php
For the current folder of the current file, use $current = dirname(__FILE__);.
For a parent folder of the current folder, simply use $parent = dirname(__DIR__);.
If your configuration file PHP.ini is set up correctly then you can use:
include($_SERVER["DOCUMENT_ROOT"]."/my_script.php");
// or
require($_SERVER["DOCUMENT_ROOT"]."/my_script.php");

How do I set an absolute include path in PHP?

In HTML, I can find a file starting from the web server's root folder by beginning the filepath with "/". Like:
/images/some_image.jpg
I can put that path in any file in any subdirectory, and it will point to the right image.
With PHP, I tried something similar:
include("/includes/header.php");
...but that doesn't work.
I think that that this page is saying that I can set include_path once and after that, it will be assumed. But I don't quite get the syntax. Both examples start with a period, and it says:
Using a . in the include path allows for relative includes as it means the current directory.
Relative includes are exactly what I don't want.
How do I make sure that all my includes point to the root/includes folder? (Bonus: what if I want to place that folder outside the public directory?)
Clarification
My development files are currently being served by XAMPP/Apache. Does that affect the absolute path? (I'm not sure yet what the production server will be.)
Update
I don't know what my problem was here. The include_path thing I referenced above was exactly what I was looking for, and the syntax isn't really confusing. I just tried it and it works great.
One thing that occurs to me is that some people may have thought that "/some/path" was an "absolute path" because they assumed the OS was Linux. This server is Windows, so an absolute path would have to start with the drive name.
Anyway, problem solved! :)
What I do is put a config.php file in my root directory. This file is included by all PHP files in my project. In that config.php file, I then do the following;
define( 'ROOT_DIR', dirname(__FILE__) );
Then in all files, I know what the root of my project is and can do stuff like this
require_once( ROOT_DIR.'/include/functions.php' );
Sorry, no bonus points for getting outside of the public directory ;) This also has the unfortunate side affect that you still need a relative path for finding config.php, but it makes the rest of your includes much easier.
One strategy
I don't know if this is the best way, but it has worked for me.
$root = $_SERVER['DOCUMENT_ROOT'];
include($root."/path/to/file.php");
The include_path setting works like $PATH in unix (there is a similar setting in Windows too).It contains multiple directory names, seperated by colons (:). When you include or require a file, these directories are searched in order, until a match is found or all directories are searched.
So, to make sure that your application always includes from your path if the file exists there, simply put your include dir first in the list of directories.
ini_set("include_path", "/your_include_path:".ini_get("include_path"));
This way, your include directory is searched first, and then the original search path (by default the current directory, and then PEAR). If you have no problem modifying include_path, then this is the solution for you.
There is nothing in include/require that prohibits you from using absolute an path.
so your example
include('/includes/header.php');
should work just fine. Assuming the path and file are corect and have the correct permissions set.
(and thereby allow you to include whatever file you like, in- or outside your document root)
This behaviour is however considered to be a possible security risk. Therefore, the system administrator can set the open_basedir directive.
This directive configures where you can include/require your files from and it might just be your problem.
Some control panels (plesk for example) set this directive to be the same as the document root by default.
as for the '.' syntax:
/home/username/public_html <- absolute path
public_html <- relative path
./public_html <- same as the path above
../username/public_html <- another relative path
However, I usually use a slightly different option:
require_once(__DIR__ . '/Factories/ViewFactory.php');
With this edition, you specify an absolute path, relative to the file that contains the require_once() statement.
Another option is to create a file in the $_SERVER['DOCUMENT_ROOT'] directory with the definition of your absolute path.
For example, if your $_SERVER['DOCUMENT_ROOT'] directory is
C:\wamp\www\
create a file (i.e. my_paths.php) containing this
<?php if(!defined('MY_ABS_PATH')) define('MY_ABS_PATH',$_SERVER['DOCUMENT_ROOT'].'MyProyect/')
Now you only need to include in every file inside your MyProyect folder this file (my_paths.php), so you can user MY_ABS_PATH as an absolute path for MyProject.
Not directly answering your question but something to remember:
When using includes with allow_url_include on in your ini beware that, when accessing sessions from included files, if from a script you include one file using an absolute file reference and then include a second file from on your local server using a url file reference that they have different variable scope and the same session will not be seen from both included files. The original session won't be seen from the url included file.
from: http://us2.php.net/manual/en/function.include.php#84052
hey all...i had a similar problem with my cms system.
i needed a hard path for some security aspects.
think the best way is like rob wrote. for quick an dirty coding
think this works also..:-)
<?php
$path = getcwd();
$myfile = "/test.inc.php";
/*
getcwd () points to:
/usr/srv/apache/htdocs/myworkingdir (as example)
echo ($path.$myfile);
would return...
/usr/srv/apache/htdocs/myworkingdir/test.inc.php
access outside your working directory is not allowed.
*/
includ_once ($path.$myfile);
//some code
?>
nice day
strtok
I follow Wordpress's example on this one. I go and define a root path, normally the document root, and then go define a bunch of other path's along with that (one for each of my class dirs. IE: database, users, html, etc). Often I will define the root path manually instead of relying on a server variable.
Example
if($_SERVER['SERVERNAME'] == "localhost")
{
define("ABS_PATH", "/path/to/upper/most/directory"); // Manual
}
else
{
define("ABS_PATH, dirname(__FILE__));
// This defines the path as the directory of the containing file, normally a config.php
}
// define other paths...
include(ABS_PATH."/mystuff.php");
Thanks - this is one of 2 links that com up if you google for php apache windows absolute path.
As a newbie to intermed PHP developer I didnt understand why absolute paths on apache windopws systems would be c:\xampp\htdocs (apache document root - XAMPP default) instead of /
thus if in http//localhost/myapp/subfolder1/subfolder2/myfile.php I wanted to include a file from http//localhost/myapp
I would need to specify it as:
include("c:\xampp\htdocs\myapp\includeme.php")
or
include("../../includeme.php")
AND NOT
include("/myapp/includeme.php")
I've come up with a single line of code to set at top of my every php script as to compensate:
<?php if(!$root) for($i=count(explode("/",$_SERVER["PHP_SELF"]));$i>2;$i--) $root .= "../"; ?>
By this building $root to bee "../" steps up in hierarchy from wherever the file is placed.
Whenever I want to include with an absolut path the line will be:
<?php include($root."some/include/directory/file.php"); ?>
I don't really like it, seems as an awkward way to solve it, but it seem to work whatever system php runs on and wherever the file is placed, making it system independent.
To reach files outside the web directory add some more ../ after $root, e.g. $root."../external/file.txt".

Categories