PHP Image Upload trouble - php

I am currently working on a Joomla! website. I am using the Jumi extension (which allows custom scripts to be made and executed within Joomla! itself) to create a simple file upload tool. The problem is that I get the following error:
Warning: copy(C:/xampp/htdocs/images/1253889508.jpg) [function.copy]: failed to open stream: No such file or directory in C:\xampp\htdocs\Joomla\components\com_jumi\jumi.php(25) : eval()'d code on line 61
The offending code is as follows:
//we will give an unique name, for example the time in unix time format
$image_name=time().'.'.$extension;
//the new name will be containing the full path where will be stored (images folder)
$newname='C:/xampp/htdocs/images/'.$image_name;
//we verify if the image has been uploaded, and print error instead
$copied = copy($_FILES['image']['tmp_name'], $newname);
The full code is available here. Once I get this working, I will be modifying it to meet the needs of my website.
I'm not sure if the problem is a permissions issue with Jumi or if there is some other problem. The best I can tell is that for whatever reason, the temp file is not being created.
Thanks for any tips you may have!

Try this:
if(move_uploaded_file($_FILES['image']['tmp_name'], $newname)){
// move worked, carry on
}
And use relative paths instead of absolute ones.

does your C:/xampp/htdocs/images directory actually exists?
if not create it manually or with mkdir()
also try to use the constant DIRECTORY_SEPARATOR instead of hardcoding slashes
Also you should use the move_uploaded_file() for this and not the copy() function.
And never hardcode absolute paths into your scripts! instead get the root path and preferibly set it as a constant, this is mostly done with the dirname() function in the entry file, but joomla allready has a constant you can use for this.

Forward slashes in the $namename path rather than backslashes?

Related

passing root path in move_uploaded_file

i have a constant variable named SADMIN
define('SADMIN','http://localhost/synthesis_study_material/student_admin/');
and i am trying to use SADMIN constant in my move_uploaded_file function
move_uploaded_file($_FILES['name']['tmp_name'], SADMIN."include/uploaded/epub/".$_POST['name']);
my current file is in
http://localhost/synthesis_study_material/synthesis_notes_admin/index.php
file is not getting uploaded in expected folder and move_uploaded_file is not giving any warning or error
The destination of move_uploaded_file needs to be a file path, not a url. To clarify this your webserver has a specified folder on the file system set as the web root. This might be something like '/var/www'. This means when you go to 'http://localhost/' it will look for a file such as '/var/www/index.php' or '/var/www/index.php'.
the destination might be an absolute path or relative, so you might supply 'synthesis_study_material/student_admin/' and that might be the same as '/var/www/synthesis_study_material/student_admin/' (depending on your web root and where move_uploaded_file is called from). Note you can use dirname(__FILE__) to get the path of the current php file. Also note that move_uploaded_file will not create directories for you if they don't exist.
I suggest starting with a simple example such as move_uploaded_file($_FILES['name']['tmp_name'], 'test-upload.txt'); to see if anything gets uploaded, and make modifications from there.

../ on URL on php not working

this is kind of a silly question, but as I can't sort it out I thought it might be good to get some help. The point is that the ".. /" to go back directory is not working.
The file I'm executing is in a folder that's on the main route and I need to go back to the main route and then enter another folder to load this other PHP file but it's not working what could be causing this issue.
ERRORS:
Warning: require_once(../PHPMailer/PHPMailerAutoload.php): failed to open stream: No such file or directory in things/public_html/classes/Mail.php on line 3
Fatal error: require_once(): Failed opening required '../PHPMailer/PHPMailerAutoload.php' (include_path='.:/opt/alt/php71/usr/share/pear') in things/public_html/classes/Mail.php on line 3
DIRECTORY STRUCTURE:
File where the requiere once is:
/public_html/classes/filethatwantstoacces.php
File where it wants to get:
/public_html/PHPMailer/PHPMailerAutoload.php
require_once('../PHPMailer/PHPMailerAutoload.php');
What you should be using is the $_SERVER['DOCUMENT_ROOT'] variable. Please read this answer to another question for details.
If you are using PHP you should get into a habit of NOT using relative file paths at all but to use absolute paths, which will guarentee to succeed every time (As long as the target file exists and is reachable, etc.).
so; use $_SERVER['DOCUMENT_ROOT']
As a side note, you do not need to use brackets for your includes/requires, it's simply giving the server more work to do for no extra benefit.
The $_SERVER['DOCUMENT_ROOT'] is the base directory of your PHP/web application, typically the contents of the folder /public_html.
Using correct syntax and the above $_SERVER value (which will point to the /public_html folder you will have:
require_once $_SERVER['DOCUMENT_ROOT'].'/PHPMailer/PHPMailerAutoload.php';
This will work from any script within your directory structure, if the file (PHPMailerAutoload.php) exists and is reachable at that given location
Given your location
/public_html/classes/filethatwantstoacces.php
doing ../ gives you
/public_html/classes
so ../PHPMailer/PHPMailerAutoload.php evaluates to
/public_html/classes/PHPMailer/PHPMailerAutoload.php
As #Martin has pointed out, using $_SERVER['DOCUMENT_ROOT'] to construct an absolute path to your file is the easiest way to avoid relative directory navigation errors such as this:
require_once $_SERVER['DOCUMENT_ROOT'].'/PHPMailer/PHPMailerAutoload.php';

Weird behaviour of rename() in PHP

I am having a weird problem with my php. Whenever I try to move a file with rename(), not only the file is not moved, but also the directory to which it should be copied is deleted, together with all files within it. The original code is:
rename('temp.odt', 'tmp/report.odt');
but I have already tried other path delimiters like
rename('temp.odt', 'tmp\report.odt');
rename('temp.odt', 'tmp\\report.odt');
rename('temp.odt', 'tmp' . DIRECTORY_SEPARATOR . 'report.odt');
rename('C:\wamp\www\zaiko\temp.odt', 'C:\wamp\www\zaiko\tmp\report.odt');
all to no avail. The code comes from a 3rd-party module which is used in the system I am working on.
Points well checked:
The file 'temp.odt' does exist in the current directory;
The directory 'tmp' does exist and there are several files in it. Also it is not read only.
The target file does not already exist (the actual file name has a timestamp, I reduced it here for simplicity)
After running rename(), the 'temp.odt' file is intact in its original location, while the folder 'tmp' is vanished as well as everything inside it. The following warning is issued:
( ! ) Warning: rename(temp.odt,tmp\report.odt) [function.rename]: The system couldn't find the specified path*. (code: 3) in C:\wamp\www\zaiko\modules\mod_deliver.php on line 192
*translated from Portuguese
Running: Apache 2.2.17 with PHP 5.3.5 on Windows XP with NTFS
Editing:
Just found the cause of the problem. It turns out that the module used by the application uses, in turn, a compression library; this library uses a temporary folder with exactly the same name as the one used by the application.
It must use some sort of cache, which would explain why the error didn't appear 100% times.
Problem solved by changing the name of the 'tmp' folder to anything else.
Thank you all for your time, and sorry for bothering you with such a stupid thing that, as it turns out, had absolutely nothing to do with my initial guess and, consequently, with the question formulated.
The example on PHP.net tells you exactly what to do - use the ROOT PATH to the file - normally this can be got by using $_SERVER['DOCUMENT_ROOT'] (but this only goes to the htdocs/public_html directory - you need to specify the rest) or by manually typing the path in (but try to avoid this).
<?php
rename("/tmp/tmp_file.txt", "/home/user/login/docs/my_file.txt");
?>
At a guess, the following should work (assuming this is your path) - this also checks that your file actually exists so it can be renamed - you need to make sure that tmp/ actually exists in the first place, but you will get an error popping out if it didn't:
<?php
$root = getcwd().DIRECTORY_SEPARATOR; // Obtain the current working dir
$srcpath = $root."temp.odt"; // The file you want to rename
$destpath = $root."tmp/report.odt"; // Where you want to rename the file to
// make sure file exists and its movable
if(is_writable($srcpath)){
// if it exists, rename it
rename($srcpath, $dstpath);
echo "File was renamed!";
} else {
echo "It seems that the specified file doesn't exist!";
}
?>
You were escaping characters by using backslashes - always use forward slashes (I know this is within a single quote, which is ok, but if you use double quote then you would wonder what's gone wrong)!

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 to upload a file using php to the parent directory

Hopefully easy question, I have a desktop application that allows the user to upload a file to a server using a form, the form sends the data to a protected file on the site like this. Site_root/protected_folder/myfile.php . If you use php file upload commands normally you'd be operating in the 'protected_folder' directory, which I don't want.
I want to add stuff to the images file on the root directory like this Site_root/images/ , how would you go about doing this without going the ftp root?
The usual method is to call move_uploaded_file(), where you set the destination path to your liking. The file name in $_FILES['tmp_name'] normally points to a temporary folder and it's subject to be removed without prior notice.
You can either use an absolute path like /path/to/images/ or use a relative path like ../images/
Assuming you're using move_uploaded_file the second paramater takes the directory that you wish to upload to. Perhaps showing you code may help if this post doesn't.
move_uploaded_file() will allow you to place uploads relative to the root directory if you simply start your path with a slash like
$newFileDir = '/username/public_html/websiteroot/subdir/yourfile.jpg';
move_uploaded_file($_FILES['postname']['tmp_name'],$newfileDir);
you can simply use copy() and double dot (../) in path to specify root directory to copy the uploaded file. I'm using the same. You may want to change the file name so that there will be unique filename in the directory error will occur. extension will also be same.
//
$filename = stripslashes($_FILES['postname']['name']);
$extension = getExtension($filename);
$newfilename ='photo_your_filename'.time().'.'.$extension;
$newFileDir = '../subdir/'.$newfilename;
copy($_FILES['postname']['tmp_name'],$newfileDir);

Categories