rename a file in php on a windows file server (unc path) - php

In PHP I want to rename (move/copy) a file on a windows file server:
"\myserver\folder1\folder2\myfile.pdf"
to
"\myserver\folder1\folder2\OLD\myfile.pdf"
(all folders already exist and destination file does not exist)
I tried this:
copy("\\\\myserver\\folder1\\folder2\\myfile.pdf", "\\\\myserver\\folder1\\folder2\\OLD\\myfile.pdf");
and
copy("//myserver/folder1/folder2/myfile.pdf", "//myserver/folder1/folder2/OLD/myfile.pdf");
I receive:
[function.copy]: failed to open stream: Permission denied
The computer I am on / user logged in as has permissions to rename/move/delete/copy to that share/folder.
I am guessing I need to somehow give php permissions, or run php as my user? OR?

PHP will be running as whatever user your web server runs as. You would need to grant permissions on that folder to whatever user account that is.

Dont use Copy... use move_uploaded instead
This is one example getting the image from a form:
$img = 'sample.jpg;
$path = '//nameofyourpcinyournetwork/sharedfolder/folderyoulike/';
$pathwithimg = $path.$img;
if (!is_dir($path)) {
mkdir($path, 0644, TRUE); // TRUE for make it recursive
}
if (file_exists($pathwithimg)) {
unlink($pathwithimg);
move_uploaded_file($_FILES["file"]["tmp_name"], $pathwithimg);
chmod($pathwithimg, 0644);
}
Change safe_mod to Off if you have it On
P.D. Yeah i know, this post is 5 years ago... but no one said a valid answer and other people (like me) may find this question

Related

How to correctly upload a file to a directory [duplicate]

I am trying to upload files into office network share folder, I have permission to my user account access the shared folder, I used UNC path to directly to upload files by move_upload_file function, It was not working I got this error.
Warning: move_uploaded_file(\\17.105.103.8\History\TQ_Books\1.PDF): failed to open stream: Invalid argument in C:\xampp\htdocs\bookshelfs\app\controllers\Books.php on line 144
after some search I mounted that shared folder on my pc, I directly used that mounted drive name to upload the file then I am getting this error
Warning: move_uploaded_file(Z:\30.PDF): failed to open stream: No such file or directory in C:\xampp\htdocs\bookshelfs\app\controllers\Books.php on line 437
I am not getting what's wrong with it, how to fix this issue? do I need to do some config with apache service? I was trying SMP protocol but It is very hard to understand for me.
UPDATE
$bookExt = pathinfo($_FILES['select_book']['name'], PATHINFO_EXTENSION);
$filename = ltrim($_POST['book_no'], '0') . '.' . $bookExt;
$tmpFilename = $_FILES['select_book']['tmp_name'];
$targetDir = '\\\\17.105.103.8\\History\\TQ_Books\\'; //before mount'
$targetDir = 'Z:'; //after mount
$fileTarget = $targetDir . $filename;
if (move_uploaded_file($tmpFilename, $fileTarget)) {
die("success, uploaded");
} else {
die("not uploaded");
}
After days of research, I got the solution. PHP cannot talk directly to the network share folder in this case you have to mount the network drive to your system. after if you mount the drive still it won't work, because the problem is here Apache server logged in by the local system user account, so you have to change it to your system user account through Apache service. (you can find apache service on windows services) you have to open windows service by admin then only you can change the account.
Then you can run this code on your PHP file to mount. all set (you can see your mounted drive after restart your pc)
exec("net use Z: \\\\netowrk_ip\\folder /user:{sharefolder_domine}\{sharefolder_username} {sharefolder_password} /persistent:no 2>&1", $output, $return_var);
var_dump($output);
I hope this answer helps others.

fopen: failed to open stream: Permission denied in PHP on Mac [duplicate]

This question already has answers here:
PHP - Failed to open stream : No such file or directory
(10 answers)
Closed 6 years ago.
I wrote this piece of code:
if (file_exists("testfile.rtf")) echo "file exists.";
else echo "file doesn't exist.";
$fh = fopen("testfile.rtf", 'w') or die("impossible to open the file");
$text = <<< _END
Hi buddies,
I write for the first time
in a PHP file!
_END;
fwrite($fh, $text) or die("Impossible to write in the file");
fclose($fh);
echo ("writing in the file 'testfile.rtf' succeed.");
But when I run it it says:
fopen(testfile.rtf): failed to open stream: Permission denied in /Applications/XAMPP/xamppfiles/htdocs/test/test1.php on line 64
impossible to open the file
I use XAMPP on my MAC to work on local server.
I found several topics where some people had the same problem, and solved it using something called "chmod 777" but I don't know what that means, where to write this, etc.
The error you are seeing simply means that your php script does not have the permission to open testfile.rtf for writing.
do not "chmod 777" everything anytime you are getting permission issues, this might introduce security problems later! instead- give the correct users the correct permissions.
In this case:
Since you are running XAMPP, then you need to make sure that your web server gets the write permission to the specific path you are trying to create new files in and\or edit existing files.
In the case of OSX and apache, I believe the webserver's user is named "_www".
Here's a small example (you might need to change it to your needs):
sudo chown -R _www:_www /path/to/folder
The example above will give _www (webserver) ownership of the /path/to/folder and all of the files in it.
Also: before you do any command-line based administration, you might want to read a little bit about unix commands, such as chown,chmod,etc..
https://www.techonthenet.com/linux/commands/chown.php
https://www.techonthenet.com/linux/commands/chmod.php
Hope it helps a bit!

Randomly arising "Permission denied" in php mkdir (windows)

I am wrestling with a problem. I stripped the example to this script that can be run as stand-alone application:
<?php
if(file_exists("x")){
print "<div>Deleting dir</dir>";
rmdir("x");
} else {
print "<div>Not exists</dir>";
}
clearstatcache();
mkdir("x");
If I call it repeatedly (F5 in browser) then sometimes this error occurs:
Deleting dir
Warning: mkdir(): Permission denied in F:\EclipseWorkspaces\Ramses\www\deploy\stripped_example.php on line 9
10-20 times it works OK and next time this error occurs. I googled more users has this problem but without solution.
https://github.com/getgrav/grav/issues/467
My example creates the directory in cwd, where anybody has full control. In addition the mkdir $mode parameter is ignored in windows. After the error the "x" directory truly not exists and in next attempt (F5) it is always created without error. I hopped later added "clearstatcache()" will help but nope.
In my full application I am using full file path. The deleted directory is not empty and I must clean it first. After successfull deleting the error occurs almost always.
My system is Windows 7, PHP 7.0.5, Apache 2.4
Windows doesn't let you delete things if another process is accessing them.
Check if your antivirus or some other process is opening the folder.
You can check this in resource monitor, from task manager.
Try the code with additional check on existing:
<?php
if(is_dir("x")){
print "<div>Deleting dir</dir>";
rmdir("x");
} else {
print "<div>Not exists</dir>";
}
clearstatcache();
if (!is_dir("x")) {
mkdir("x");
}
Had the same problem with Windows 10, Xampp and PHP 7. Problem was Kaspersky Internet Security, scanning and blocking the directory. Disabling KIS mkdir always works for me. Instead of directly recreating you can try rename, if disabling security software is not an option for you.
$time = time();
mkdir($path . $time);
rename($path . $time, $path);
juste delete espace name folder with Function Trim in php

PHP: Why is chmod() setting my file/folder to 555 or 444?

I created a web application with a file browser. I'm trying to add a functionality where the user can change the chmod/permissions via an ajax request which is handled via PHP on the back-end.
(Side Note: I'm running my local with WAMP)
So initially, I'm reading the permissions with this
substr(sprintf('%o', fileperms($relativePath)), -4)
to get this format (0777, 0644, etc), if not it returns something like 32726. This info is used to be displayed in the UI for the user to know whats current.
However, when I run the script, I set it to 0777 and it seems to run fine. But then when I read the file again, it returns 0555 or 0444. Anyone know what I'm missing?
Does your web server own the files it is trying to change the permissions on? You can check whether chmod ran correctly or failed by testing its return value. It will return FALSE if the webserver did not have permissions. For more information you can read: http://php.net/manual/en/function.chmod.php
<?php
$is_success = chmod("myfile.pdf", 777);
if($is_sucess) {
echo "success<br />\n";
}
I realized this was not an issue, but rather the chmod command does not work properly on a windows/apache setup.

PHP Write a variable to a txt file

I am trying to get a variable from the query string and write it to a text file.
I have tried like this:
<?php
$content=( $_GET['var'] );
echo $content;
$file = fopen("etlLOG.txt","w+");
echo fwrite($file,$content);
fclose($file);
?>
I get the following errors:
Warning: fopen(etlLOG.txt) [function.fopen]: failed to open stream: Permission denied in E:\Users\george\listener.php on line 8
Warning: fwrite(): supplied argument is not a valid stream resource in E:\Users\george\listener.php on line 9
Warning: fclose(): supplied argument is not a valid stream resource in E:\Users\george\listener.php on line 10
You may need to change the permissions as an administrator. Open up terminal on your Mac and then open the directory that etlLOG.txt is located in. Then type:
sudo chmod 777 etlLOG.txt
You may be prompted for a password. Also, it could be the directories that don't allow full access.
OR
PHP
chmod : Attempts to change the mode of the specified file to that given in mode.
chmod
Well it appears that the web server does not have access to that file. So used ftp fopen provided the correct credentials and paths and finally i did managed to access and edit the file
If you are running WAMP on windows
1) login as an administrator
2) Install wamp
3) Download subinacl.exe from microsoft:
4) grant permissions to the regular user account to manage the WAMP services: (subinacl.exe is in C:\Program Files (x86)\Windows Resource Kits\Tools)
subinacl /SERVICE \MachineName\wampapache /GRANT=domainname.com\username=F
subinacl /SERVICE \MachineName\wampmysql /GRANT=domainname.com\username=F
5) logout and log back in as the user. They should now be able to launch the WAMP taskbar application and control the WAMP service.
My guess is that PHP is trying to create the file at 'C:\WINDOWS', so the solution wouldn't be to set permissions there.
I would suggest you use a specific location, example: create a folder at the same location as your php script and use it to create the files:
$filePath = dirname(_FILE_) . "/temp_vars/etILOG.txt";
$file = fopen($filePath ,"w+");
Kind regards,
The code you are running is trying to create the etlLOG.txt in the same folder as your PHP script. You need to give Full Permission to your IUSER_ account on the E:\Users\george folder.
If you do not know how you can browse the following links
http://technet.microsoft.com/en-us/library/bb727008.aspx
http://www.wikihow.com/Change-File-Permissions-on-Windows-7
How to set 777 permission on a particular folder?

Categories