I am trying to read the contents of a file in a subdirectory
here is my attempt :
$entityBody = "123456"
$vval= file_get_contents(__DIR__."/../data/names/$entityBody");
echo("$vval");
here is the directory outlook:
Issue: issue is when i run the script echo("$vval"); it doesnt echo anything on the screen.
what am I doing wrong ?
If you set
ini_set('display_errors', '1');
error_reporting(E_ALL);
In your PHP script you will see something like
PHP Warning: file_get_contents(/var/www/html/myData/../data/names/123456):
Failed to open stream: No such file or directory
Now since both your PHP script and data dir are sharing the same __DIR__ you don't need ..
So
$vval = file_get_contents(__DIR__ . "/data/names/$entityBody");
Will solve the problem for you.
I get the following error from PHP when running from the server
PHP Warning: rename(var/www/vhosts/example.com/httpdocs/dir1/papers/1632813138.pdf,var/www/vhosts/example.com/httpdocs/dir1/papers/00000006.pdf): No such file or directory in /var/www/vhosts/example.com/httpdocs/dir1/processes/generate_abstract_pages.php on line 98
If I then run
less var/www/vhosts/example.com/httpdocs/dir1/papers/1632813138.pdf on the command line it finds the file. I'm copy/pasting the address so it's not accidentally getting changed.
I also tried giving rename a relative path of ../papers/1632813138.pdf but that gave the same error.
The relative path works when run in browser, https://example.com/dir1/processes/generate_abstract_pages.php
<?php
$abstract["pdf_url"] = "1632813138.pdf";
$abstractId = 7;
$pdfFilename = str_pad($abstractId, 8, "0", STR_PAD_LEFT).".pdf";
$fileRenameSuccess = rename("../papers/$abstract[pdf_url]","../papers/$pdfFilename");
echo ($fileRenameSuccess ? "y":"n");
Running PHP 7.1.23
Running CentOS Linux 7.6.1810 (Core)
You can use getcwd() to get the current working directory of your script to make sure that it's running from where you expect for your relative path to work.
You need a starting "/" for the absolute path to work.
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
All I want to do is fopen() a text file in my PHP script. It's the most important part of the module that I'm building. Unfortunately, while testing the script, I found that the script cannot see the text file that I'd like to open. I have the script in the same directory as the text file, but I keep getting met with the same error. I'm posting the script code snippet and the command line prompt/response below.
Code
$membersfile = fopen('./members.txt', 'r');
print_r($membersfile);
fclose($membersfile);
Command Line
507 elersong:~$ php /Users/elersong/Desktop/SS2014/register_member.php
Warning: fopen(./members.txt): failed to open stream: No such file
or directory in
/Users/elersong/Desktop/SS2014/register_member.php on line 11
Warning: fclose() expects parameter 1 to be resource, boolean given in
/Users/elersong/Desktop/SS2014/register_member.php on line 13
I have no clue why PHP can't see the file since it most certainly exists, and it's in the same directory as the script. Please help me make sense of this.
Some PHP setups have problems with relative parts, so try this instead:
fopen(__DIR__ . '/members.txt', 'r');
__DIR__ contains the path to the folder where the currently executing PHP file is.
Your are currently doing:
$membersfile = fopen(__DIR__ .'/members.txt', 'r');
print_r($membersfile);
fclose($membersfile);
But $membersfile contains just the handle, a number so that PHP nows which opened file you are meaning. If you print that you will just see the handle number. You need to tell pHP to read the file using:
$file = __DIR__ .'/members.txt';
$membersfile = fopen($file, 'r');
echo fread($membersfile, filesize($file))
fclose($membersfile);
or use the php shorthand function:
echo file_get_contents( __DIR__ .'/members.txt');
After trying a number of the suggestions posted here, I was finally able to figure out that the PHP script isn't using a relative path to the text file based on the directory that holds the PHP script.
User #andrew suggested that I add the following line to my script in order to learn which directory the script uses as its starting point.
echo '<pre>';var_dump(glob('*'));
From the output of this line, I was able to see that the script uses the user's root folder as the starting point in fopen() on my OSX machine. I simply needed to preface the filename with the remainder of the file path, and PHP could read it. The amended script is as follows:
$membersfile = fopen('Desktop/SS2014/members.txt', 'r');
Thanks so much, #andrew and everyone else who submitted suggestions!
I am writing a simple SFTP client in PHP because we have the need to programatically retrieve files via n remote servers. I am using the PECL SSH2 extension.
I have run up against a road block, though. The documentation on php.net suggests that you can do this:
$stream = fopen("ssh2.sftp://$sftp/path/to/file", 'r');
However, I have an ls method that attempts to something similar
public function ls($dir)
{
$rd = "ssh2.sftp://{$this->sftp}/$dir";
$handle = opendir($rd);
if (!is_resource($handle)) {
throw new SFTPException("Could not open directory.");
}
while (false !== ($file = readdir($handle))) {
if (substr($file, 0, 1) != '.'){
print $file . "\n";
}
}
closedir($handle);
}
I get the following error:
PHP Warning: opendir(): Unable to open ssh2.sftp://Resource id #5/outgoing on remote host
This makes perfect sense because that's what happens when you cast a resource to string. Is the documentation wrong? I tried replacing the resource with host, username, and host and that didn't work either. I know the path is correct because I can run SFTP from the command line and it works fine.
Has anyone else tried to use the SSH2 extenstion with SFTP? Am I missing something obvious here?
UPDATE:
I setup sftp on another machine in-house and it works just fine. So, there must be something about the server I am trying to connect to that isn't working.
When connecting to a SFTP server and you need to connect to the root folder (for instance for reading the content of the folder) you would still get the error when using just "/" as the path.
The solution that I found was to use the path "/./", that's a valid path that references to the root folder. This is useful when the user you are logging with has access only to its own root folder and no full path is available.
So the request to the server when trying to read the contents of the root folder should be something like this:
$rd = "ssh2.sftp://{$this->sftp}/./";
For php versions > 5.6.27 use intval()
$sftpConnection = ssh2_connect($host);
$sftp = ssh2_sftp($sftpConnection);
$fp = fopen("ssh2.sftp://" . intval($sftp) . $remoteFile, "r");
https://bugs.php.net/bug.php?id=73597
I'm having a similar issue. I assume you are doing something similar to this:
$dir = "ssh2.sftp://{$sftp}{$remote_dir}";
$handle = opendir($dir);
When $remote_dir is the full path from root then open_dir works. If $remote_dir is just '/' or '', then I get the 'unable to open' error as you did.
In my case, it seems ssh connects at the root folder instead of the 'home' directory as ftp does. You mentioned that it worked on a different server, so I wonder if it is just a config issue.
the most easiest way to get SFTP working within PHP (even on windows) without installing any extension etc is PHPSECLIB: http://phpseclib.sourceforge.net/ . The SSH stuff is completely implemented in a PHP class.
You use is like this:
<?php
include('Net/SFTP.php');
$sftp = new Net_SFTP('www.domain.tld');
if (!$sftp->login('username', 'password')) {
exit('Login Failed');
}
echo $sftp->pwd();
?>
The documentation on that page contains an error. Take a look at the example here instead: http://php.net/ssh2_sftp - what you actually need to do is to open a special SFTP resource using ssh2_sftp() prior to using it with fopen(). And yes, it looks just like that, e.g. "Resource #24" when converted to string... a bit weird but apparently it works.
Another caveat is that SFTP starts in the root directory rather than the home directory of the remote user, so your remote path in the URI should always be an absolute one.
I just had the same issue, but I could figure out the problem.
On my case, when connecting to the server, I was going to the root of the account, and due to server configs I wasn't able to write there.
I have connected to the account using a fireFTP, and so I could see where the root of the account was...it was the root of the server.
I had to include the whole path until the folder where I am allowed to write, and so I could solve the issue.
So, my advice is to get the path using a graphic interface (I have used fireFTP), and add the whole path to your code.
$pathFromAccountRootFolderToMyDestinationFolder = '/Account/Root/Folder/To/My/Folder';
$stream = fopen("ssh2.sftp://".$sftp."/".$pathFromAccountRootFolderToMyDestinationFolder."/myFile.ext", 'r');
Hope this will help you and other people with the same issue!
Cheers!
I recently tried to get SFTP on PHP working and found that phpseclib was a lot easier to use:
http://phpseclib.sourceforge.net/
If you have the luxury of not being on a shared host and can install whatever extensions you want to maybe the PECL extension would be better but not all of us are so lucky. Plus, phpseclib's API looks a bit more intuitive, being OOP and all.
My issue was, that I was connecting in function and returning string URL with resource inside. Unfortunatelly resource is than created in function context and garbage collector is disconnecting resource on function end. Solution: return resource by reference and unset it manually in more complex context.
Solved my issue by enabling sftp support on the (Powershell) server
This is a bug in the ssh2 package that I found years ago and posted a patch to php.net. It fixes this issue but requires a rebuild of the ssh2 pecl package. You can read more here: https://bugs.php.net/bug.php?id=69981. I included a patch there to the ssh2_fopen_wrappers.c file in the package to fix the issue. Here is a comment I included:
Here is a line of code from ssh2_fopen_wrappers.c that causes this bug: (comment included)
/*
Find resource->path in the path string, then copy the entire string from the original path.
This includes ?query#fragment in the path string
*/
resource->path = estrdup(strstr(path, resource->path));
This line of code -- and therefore this bug -- was introduced as a fix for bug #59794. That line of code is attempting to get a string containing the part, query and fragment from the path variable.
Consider this value for the path variable:
ssh2.sftp://Resource id #5/topdir?a=something#heading1
When resource->path is "/topdir", the result is that "/topdir?a=something#heading1" gets assigned to resource->path just like the comment says.
Now consider the case when resource->path is "/". After the line of code is executed, resource->path becomes "//Resource id#5/topdir#heading1". This is clearly not what you want. Here's a line of code that does:
resource->path = estrdup( strstr( strstr( path, "//" ) + 2, "/" ) );
You may also need to apply the patch for bug # 73597 which removes "Resource id #" from the path string before calling php_url_parse().