How fopen file in Users dir from www dir (wamp)? - php

I trying to fopen a dir in Users dir ("C:\Users\MYUSERNAME\AppData\Roaming\SOFTWARENAME\")
I trying do that from a php file that located in www dir (wamp folder in C).
This is my try:
$file = fopen('../../../Users/Myusername/AppData/Roaming/SOFTWARENAME/', 'r');
I get "failed to open stream: No such file or directory".
Help?
Thank and sorry for my english.

I think its generally considered a bad idea to try to access files outside of the root directory of the web application and it may even be completely blocked by php unless you turn off a security check.
But that being said, you can try to use an environment variable to get the full path.
Check out this api for example: $_ENV
So your code may look more like this:
$file = fopen($_ENV['HOMEDRIVE'] + $_ENV['HOMEPATH] + '/' + fileName, 'r');
I'm not sure whats in the environment exactly but those are common environment variables on windows.

Related

mkdir() not creating directory on web server even full path is specified

Please somebody help me, I want to create a folder 'uploads' in 'httpdocs' where my index.php file is placed, I am using Windows hosting with Plesk on Goddady. I went through available content on web but couldn't fix the issue, I am not very good with web servers. I have tried many solutions like full path specification, read - write permission, recursive directory creation using true/false etc but didn't work. It is working on my local server but not on web server. - Thanks in advance.
$path ="/PleskVhosts/abccat.in/httpdocs/uploads";
or
$path ="G:/PleskVhosts/abccat.in/httpdocs/uploads";
or
$path ="/httpdocs/uploads"; or $path ="/uploads";
mkdir($path, 0777, true);
I tried above all paths one by one, but didn't work. It is returning nothing as well. The full path for 'httpdocs' is G:/PleskVhosts/abccat.in/httpdocs.
Any help? Thanks.
PHP docs for mkdir() say that the mode is ignored on windows.
You may want to alter the permissions for the folders using chmod();
http://php.net/manual/en/function.mkdir.php
http://php.net/manual/en/function.chmod.php
Don't forget to set your permission back after you create your file.
chmod($folderPath, 0777); //<--This path would be for the folder you want your file in.
//You may have to do the chmod() for every folder all the way up to you target folder.
mkdir($filePath, 0777, true);
chmod($folderPath, 'mode'); //<---Put in the mode you need it to be. Do this for any folder you previously changed.
Try that and see if it helps.

PHP Unlink Not working

I am trying to delete photo in php using unlink. I have used it earlier on other server but this time it is not working. I have used absolute path for a test but still does not works:
I have used it as:
unlink('img1.jpg');
and :
unlink('http://www.mysite.com/img1.jpg');
Please anyone having such experience?
url not allow in ulink function
can you please used this
It's better, also safety wise to use an absolute path. But you can get this path dynamically.
E.g. using:
getcwd();
Depending on where your PHP script is, your variable could look like this:
$deleteImage = getcwd() . 'img1.jpg';
unlink($deleteImage);
check this
bool unlink ( string $filename [, resource $context ] )
and
filename
Path to the file.
So it only takes a string as filename.
Make sure the file is reachable with the path from the location you execute the script. This is not a problem with absolute paths, but you might have one with relative paths.
Even though unlink() supports URLs (see here) now, http:// is not supported: http wrapper information
use a filesystem path to delete the file.
If you use unlink in a linux or unix you should also check the results of is_writable ( string $filename )
And if the function returns false, you should check the file permissions with fileperms ( string $filename ).
File permissions are usual problems on webspaces, e.g. if you upload an file per ftp with a ftp user, and the webserver is running as an different user.
If this is the problem, you have do to a
chmod o+rwd img1.jpg
or
chmod 777 img1.jpg
to grand write (and delete) permissions for other Users.
unlink($fileName); failed for me.
Then I tried using the realpath($fileName) function as unlink(realpath($fileName)); it worked.
Just posting it, in case if any one finds it useful.
php unlink
use filesystem path,
first define path like this:
define("WEB_ROOT",substr(dirname(__FILE__),0,strlen(dirname(__FILE__))-3));
and check file is exist or not,if exist then unlink the file.
$filename=WEB_ROOT."img1.jpg";
if(file_exists($filename))
{
$img=unlink(WEB_ROOT."img1.jpg");
}
unlink won't work with unlink('http://www.mysite.com/img1.jpg');
use instead
unlink($_SERVER['DOCUMENT_ROOT'].'img1.jpg');//takes the current directory
or,
unlink($_SERVER['DOCUMENT_ROOT'].'dir_name/img1.jpg');
There may be file permission issue.please check for this.
Give relative path from the folder where images are kept to the file where you are writing script.
If file structure is like:
-your php file
-images
-1.jpg
then
unlink(images/1.jpg);
Or there may be some folder permission issue. Your files are on a server or you are running it on localhost? If it is on a server then give 755 permission to the images folder.
you are using url insted of path, here is how you should do it...
i am assuming your are uploading the picture to public_html. i suggest you to create a folder for pictures.
unlink("public_html/img1.jpg");

permission denied - php unlink

I have two files:
b.php and test.txt
<?php
$b = "test.txt";
unlink($b);
?>
and the error is: Warning: unlink(test.txt) [function.unlink]: Permission denied
why? b.php and test.txt is 777 and the same group/login
if I set 777 on the parent directory I can execute unlink but i have to set 777 and back to 755?
You (as in the process that runs b.php, either you through CLI or a webserver) need write access to the directory in which the files are located. You are updating the directory content, so access to the file is not enough.
Note that if you use the PHP chmod() function to set the mode of a file or folder to 777 you should use 0777 to make sure the number is correctly interpreted as an octal number.
You'll first require to close the file using fclose($handle); it's not deleting because the file is in use. So first close the file and then try.
in addition to all the answers that other friends have , if somebody who is looking this post is looking for a way to delete a "Folder" not a "file" , should take care that Folders must delete by php rmdir() function and if u want to delete a "Folder" by unlink() , u will encounter with a wrong Warning message that says "permission denied"
however u can make folders & files by mkdir() but the way u delete folders (rmdir()) is different from the way you delete files(unlink())
eventually as a fact:
in many programming languages, any permission related error may not
directly means an actual permission issue
for example, if you want to readSync a file that doesn't exist with node fs module you will encounter a wrong EPERM error
// Path relative to where the php file is or absolute server path
chdir($FilePath); // Comment this out if you are on the same folder
chown($FileName,465); //Insert an Invalid UserId to set to Nobody Owner; for instance 465
$do = unlink($FileName);
if($do=="1"){
echo "The file was deleted successfully.";
} else { echo "There was an error trying to delete the file."; }
Try this. Hope it helps.
The file permission is okay (0777) but i think your on the shared server, so to delete your file correctly use;
1. create a correct path to your file
// delete from folder
$filename = 'test.txt';
$ifile = '/newy/made/link/uploads/'. $filename; // this is the actual path to the file you want to delete.
unlink($_SERVER['DOCUMENT_ROOT'] .$ifile); // use server document root
// your file will be removed from the folder
That small code will do the magic and remove any selected file you want from any folder provided the actual file path is collect.
In Windows and before PHP version 7.3.0, check that your file has been closed before unlinking it,
as said in https://www.php.net/manual/en/function.unlink.php :
On Windows, it is now possible to unlink() files with handles in use, while formerly that would fail. However, it is still not possible to re-create the unlinked file, until all handles to it have been closed.
As an exemple :
$fullFilePath = 'C:\Users\MyUserName\www\myApp\public\test.txt';
$handle = fopen($fullFilePath , 'w+');
fopen($filePath, 'w+');
fputs($handle, 'Some text in the file');
fclose($handle);
unlink(realpath($insertedLinesFilePath));

Using PHP to create a new directory, and a file in that directory

I recently started to mess around with some HTML and PHP, and have run into what is probably a super easy to solve error, but one I have not for the life of me been able to fix.
In a nutshell, what I'm trying to do is create a directory, then create a .txt file in that directory with the same name, something to the effect of "/number/number.txt". While it seems simple to create a file, or to create a directory, I'm having no end of troubles trying to do both.
Here's my code:
mkdir($postnum, 0777);
chmod($postnum, 0777);
$post = "/" . $postnum . "/" . $postnum . ".txt";
$post = boards(__FILE__) . $post;
$po = fopen($post, 'w+') or die("Can't open file");
chmod($post, 0777);
A few issues I ran into writing this, I read that using mkdir I could set the permissions of the directory I create, but despite doing what I believe to be the right way of doing so, it didn't do anything. So I ran chmod right after.
Then, I had hoped that just /$postnum/$postnum.txt would work for the directory to open, but I get the die text when I try just that, I had to add in the "boards(FILE) part to get it to work. (Side note, "boards" is the directory I'm working in)
Even then, while it doesn't give me "Can't open file", it isn't creating the file or anything.
I've made certain that any file or folder even remotely interacting with the files has had it's permissions set to 0777, so it's likely not an issue with that. (Also, I know that having all my files completely open like that may not be the best idea; once I get this working properly, I'll be sure to set the permissions to something more safe)
Any idea what I'm doing wrong?
making directory and creating path:-
$new_folder=mkdir('uploads\\'.$folder_name, 0777, true);
('uploads\\'.$folder_name)->path where you create folder like www->upload->folder name(whatever you provide)
$path="uploads\\".$folder_name."\\";//if you want to provide path you can provide this way
The mkdir function takes a path relative to the root of the filesystem, not the document root.
If you're on a *nix system, your website document root is likely in a path such as /var/www/sitename/html, but you're trying to create /number/number.txt which your account doesn't have permissions to do. Change the path you pass into mkdir to somewhere in the filesystem you have permissions to create folders and files and your code should work.
Edit:
The code in your question doesn't actually attempt to write anything. By calling fopen you've created a file handle, but you need to call fwrite to actually write data to the file. As suggested by #JamesSwift, you may want to take a look at file_put_contents.
Here, try this :
$root = realpath($_SERVER["DOCUMENT_ROOT"]);
mkdir("$root/root_website_folder/php/testing_folder", 0777);
PHP uses your real path not the virtual one, we assign to $root the real path on your machine than add the virtual path of your website root

PHP fopen() not creating file if it doesn't already exist

As part of application logging, I'm attempting to open a local file, and if that file doesn't already exist, to create the new one. Here's what I have:
$path = '/home/www/phpapp/logs/myawesome_logfile.txt';
$f = (file_exists($path))? fopen($path, "a+") : fopen($path, "w+");
fwrite($f, $msg);
fclose($f);
chmod($path, 0777);
I've double-checked, and the /logs directory is chmod 0777, and I even went the extra step of chown'ing it to apache:apache for good measure. Still, when the script goes to open the file, it gives me the warning that the file doesn't exist and bombs out. No file is ever created.
Do I need to suppress the fopen() warning to get it to create the file?
When you're working with paths in PHP, the context can matter a great deal. If you're working with urls in a redirection context -- then the root directory ('/') refers to your domain's root. The same goes for paths for linking files or images and for include and require directives.
However, when you're dealing with file system commands such as fopen, the root directory ('/') is the system root. Not your domain root.
To fix this, try giving the full path to the log file you want to open from the system root. For example: /var/www/phpapplication/logs/myLogFile.txt
Or you could use $_SERVER['DOCUMENT_ROOT'] as suggested in other answers to access your server's stored value for the path to the document root. The /var/www part.
You can also use the __DIR__ magic constant in some cases. Note that __DIR__ will be the directory the current file is in, which is not necessarily the same as your application's root. So for example, if your application's root is /var/www/application and you're working in /var/www/application/src/controllers/my_controller.php, then __DIR__ will be /var/www/application/src/controllers. See here in the PHP documentation.
Have you tried this?
$msg = "I'm a line that is a message.\n";
$path = $_SERVER['DOCUMENT_ROOT'] . '/logs/myawesome_logfile.txt';
$f = fopen($path, "a+");
fwrite($f, $msg);
fclose($f);
chmod($path, 0777);
The server you're working on could have jailed you to only work in the phpapp's directory and its subdirectories.
One way I got around this problem in UBUNTU 14.04 was by right clicking on the directory where the file is located and changing the permissions of "others" to "create and delete files".
You can always open your file with just "a", it will create a new file as well.
No need to make a condition.
However, the main issue with your code is understanding the difference between physical filesystem and virtual web-server, which have been perfectly explained already.
Note that you should provide your question with exact copy of error message. It contains a ton of extremely useful information, it's not like an oath "I won't create your file, go away!" but it's through explanation of what and why is going wrong. If you don't care of such useful info yourself, you have to provide it to ones whom asking for help.
The path of the file must be with the server root. I could achieve this using the
phpinfo()
method inside the document I wanted to know. So when you use phpinfo() you will see a information document. If you find for
_SERVER["SCRIPT_FILENAME"] you will see the absolute path of your file.
I hope this help someone.
Don't forget to make sure that SELinux isn't blocking you.
[root#yourbox]# audit2allow < /var/log/audit/audit.log
#============= httpd_t ==============
#!!!! This avc can be allowed using the boolean 'httpd_unified'
allow httpd_t httpd_sys_content_t:dir { write add_name };
#!!!! This avc can be allowed using the boolean 'httpd_unified'
allow httpd_t httpd_sys_content_t:file { write create };
[root#yourbox]# audit2allow -a -M my_httpd
Note:
To make this policy package active, execute:
semodule -i my_httpd.pp
[root#yourbox]# semodule -i my_httpd.pp
[root#yourbox]# systemctl restart httpd

Categories