Opening/Reading a local file from PHP Web Application - php

I feel like this should be a pretty straightforward process.
I have the following code:
<?php
$filename = "c:/TestFolder/config.txt";
echo "Attempting to read: ".$filename."<br/>";
$fh = fopen($filename, 'r') or die("file doesnt exist");
$readtext = fread($fh, filesize($filename));
fclose($fh);
echo "The Text is: ".$readtext;
?>
I have checked that I do indeed have "config.txt" in a folder called "TestFolder" on my C:/ drive... but I keep getting an error that the file doesn't exist.
I checked my PHPInfo to ensure that "allow_url_fopen" is turned on.
I have also tried different file path variations, such as:
C:\\TestFolder\\config.txt
C:\/TestFolder\/config.txt
This doesn't seem to make a difference.
Any idea what might be preventing me from opening this file?
Edits:
It should be noted that this file is uploaded to my web host, while I am attempting to access a file on my local machine. Not sure if this changes things at all.

This is not possible. "local files" are files on the server where PHP is running, not the client running the web browser. While they might be the same machine when you're testing locally, once you upload the script to a web host, PHP tries to read files on the web host, not your machine.
The only way for PHP to access a file on the client machine is for the application to upload it.

Related

PHP under IIS6 can't open/read file on network

I have a simple php script that runs on an IIS 6 2003 server. All the script does is try to open a file on a shared network network location and display its content to the screen. Try as I might I cannot get that to work. I keep getting a "failed to open stream error message". After a lot of reading (I'm on my second week of working at this) I narrow the problem down to being a server configuration problem. I can run the script through the command prompt and it works fine. If I run var_dump(shell_exec('whoami')) It returns "NULL". If I run that same command on the command prompt it returns the current user that is logged in (i.e. me). The task manager reports that the user for w3wp.exe is "NETWORK SERVICE". I'm including the code below although I'm 100% sure the code is not the problem but, some people like to look at code so there it is. How do you configure or make changes on the server so that it allows reading from a network location? Also, the network location I'm trying to access have been setup with all permissions for everybody so that we can solve this one issue.
<?php
$theFile="\\\\192.168.0.16\\geo\\junk.txt"; #network file does not works
#$theFile="junk.txt"; #local file works fine
$handle = fopen($theFile, "r");
if($handle){
while (!feof($handle)){
$buffer = fgets($handle);
echo $buffer."<br />";
}
}
?>

PHP can't access network drive but can if address is explicit

I've been battling this problem for days now. I'm 100% sure is a user configuration thing somewhere but, i don't know where to look or what to change. Here is the problem. I have a file i want to read. It just contains 5 lines like "this is line 1, this is line 2 etc. It's for debugging purposes. I have 2 copies of this files. one lives locally and one lives on a network drive. I can access the file locally no problem. I can also access the file on the network drive if I specify the address as in \\192.168.0.16\geo\junk.txt. What I cannot do is to access the file via a mapped drive. as in U:\junk.txt where the U: is mapped to the 192.168... above. Below is my code. Again, after A LOT!!! of reading I've come to the conclusion that its a user perminsion thing between the machine the code lives in and the apache server that runs the code. I don't think the two are talking to each other. Just in case this is on a windows 7 machine apache 2.2.
<?php
#$theFile="\\\\192.168.0.16\\geo\\junk.txt"; #works fine
#$theFile="junk.txt"; #local file works fine
$theFile="U:\\junk.txt"; #mapped drive DOESN'T WORK AAARRRGGG!!!!!
$handle = fopen($theFile, "r");
if($handle){
while (!feof($handle)){
$buffer = fgets($handle);
echo $buffer."<br />";
}
}
?>

PHP Read/Write files on remote server

I'm making a utility that provides a GUI to easy edit certain values in a csv file on a remote server. My boss wants the utility in php running on the private webserver. I'm new to php, but I was able to get the GUI file modifier working locally without issues. The final piece now is rather than the local test file I need to grab a copy of the requested file off of the remote server, edit it, and then replace the old file with the edited one. My issue is uploading and downloading the file.
When I searched for a solution I found the following:
(note in each of these I am just trying to move a test file)
$source = "http://<IP REMOTE SERVER>/index.html";
$dest = $_SERVER['DOCUMENT_ROOT']."index.html";
copy($source, $dest);
This solution ran into a permissions error.
$source ="http://<IP REMOTE SERVER>/index.html";
$destination = $_SERVER['DOCUMENT_ROOT']."newfile.html";
$data = file_get_contents($source);
$handle = fopen($destination, "w");
fwrite($handle, $data);
fclose($handle);
This also had a permissions error
$connection = ssh2_connect('<IP REMOTE SERVER>', 22);
ssh2_auth_password($connection, 'cahenk', '<PASSWORD>');
ssh2_scp_recv($connection, '/tmp/CHenk/CHenk.csv', 'Desktop/CHenk.csv');
This solution has the error Fatal error: Call to undefined function ssh2_connect() which I have learned is because the function is not a part of the default php installation.
In closing, is there any easy way to read/write files to the remote server through php either by changing permissions, having the php extension installed, or a different way entirely that will work. Basically I'm trying to find the solution that requires the least settings changes to the server because I am not the administrator and would have to go through a round about process of getting any changes done. If something does need to be changed instructions on doing so or a link to instructions would be greatly appreciated.
Did you set the enable-url-fopen-wrapper in your php.ini?(only if your php version is older)
Please look # php remote files storing in example 2

Trouble with writing to file with php and my home server

So, I have this simple little php script. It runs and compiles fine and works the way I want it to on the machine that I coded it. I'm running it on a personal home web-server running Debian 6.0.6, 32bit. It's apache with php. And I know for a fact that php is working on the server.
<?php
$hitsfile = "hits.txt"; #name of file
$filehandle = fopen($hitsfile, 'r') or die ("Couldn't read file."); #Opens file, 'hitsfile' to be read.
$hits = fread($filehandle, 5); #reads file to the introduced variable, 'hits'
fclose($filehandle); #closes file
$hits++; #increments the variable that it read.
$filehandle = fopen($hitsfile, 'w') or die ("Couldn't write to file."); #opens file to be read.
fwrite($filehandle, $hits); #writes the hits variable to file.
fclose($filehandle); #closes file.
echo $hits; #outputs the hits variable.
?>
When I access the file from the server, via a web browser, I get the "Couldn't write to file." error. So then, it's opening the file properly, and reading it. And when it opens it to write, it fails. I'm assuming this is some sort of problem with permissions or something. I'm sort of at a loss as to how to solve the issue. Any ideas? Assistance would be greatly appreciated! I've googled for a couple days now, and I can't solve the issue. I'm a php 'noob' and I'm very new to running a linux-based web-server, but hey, you gotta learn somehow. :*l
tried to check the permissions to the file? The Linux file system have a very strict permission system. Write on terminal:
ls -la /path/to/my/file.txt
This would give you your permissions on the left column. Please read this article to be sure, and check if Apache have the "write" permissions to the file. If not, use the chmod command to give Apache access to the file (or the chown command, to change the owner of this file to apache, if the owner of this file have writing permissions).

php fwrite() doesn't finish writing string data to file, why?

I'm trying to write a sizable chunk of data to a file that is opened via fopen() in php. The protocol wrapper I'm using is ftp, so the file is remote to the server running the php code. The file I'm writing to is on a Windows server.
I verified that the file does, in fact, get created by my php code, but the problem is that the data within the file is either non-existant (0KB) or writing to the file stops prematurely. Not sure why this is the case.
Here is the code I am using for handling the operation:
$file_handle = fopen($node['ftp'].$path_to_lut, "wb", 0, $node['ftp_context']);
include_once($file);
if ($file_handle)
{
fwrite($file_handle, $string); //$string is inside included $file
fclose($file_handle);
} else {
die('There was a problem opening the file.');
}
This code works fine when I host it on my local machine, but when I upload it to my webhost (Rackspace Cloud), it fails. This leads me to believe it's an issue related to the configuration of the my server at Rackspace, but want to know if there is anything I can do to my php code to make it more robust.
Any ideas to ensure fwrite actually finishes writing the string to the remote machine?
Thanks!
Okay, I changed the code that writes to the file like so:
if ($file_handle)
{
if ($bytesWritten = fwrite($file_handle, $string) ) {
echo "There were " . $bytesWritten . " bytes written to the text file.";
}
if (!fflush($file_handle)) {
die("There was a problem outputting all the data to the text file.");
}
if (!fclose($file_handle)) {
die("There was a problem closing the text file.");
}
} else {
die("No file to write data to. Sorry.");
}
What is strange is that the echo statement shows the following:
There were 10330 bytes written to the text file.
And yet, when I verify the text file size via FTP it shows it to be 0K and the data inside the file is, in fact, truncated. I can't imagine it has to do with the FTP server itself because it works if the PHP is hosted on a machine other than the one on Rackspace Cloud.
** UPDATE **
I spoke to a Rackspace Cloud rep who mentioned that they require passive ftp if you're going to ftp from their servers. I setup the remote server to handle passive ftp connections, and have verified that passive ftp now works on the remote server via the OSX Transmit ftp client. I added:
ftp_pasv($file_handle, true);
Right after the fopen() statement, but I get an error from PHP saying the I didn't provide a valid resource to ftp_pasv(). How can I ensure that the connection to the ftp site that PHP makes is PASV and not ACTIVE and still use fwrite()? Incidentally, I've noticed that the Windows machine reports that the file being written by my PHP code is 4096 bytes on disk. It never gets beyond that amount. This led me to change the output_buffering php value to 65536 just to troubleshoot, but that didn't fix the issue either. . .
** UPDATE PART DUEX **
Troubleshooting the problem on the my virtual server on the Rackspace Cloud Sites product was proving too difficult because they don't offer enough admin rights. I created a very small cloud server on Rackspace's Cloud Server product and configured everything to the point where I'm still seeing the same error with fwrite(). To make sure that I could write a file from that server to a remote server, I used basic ftp commands within my bash shell on the cloud server. It worked fine. So, I assume that there is a bug within the php implementation of fwrite(), and that it is probably due to some type of data throttling issue. When I write to the remote server from my local environment which has a slow upspeed compared to what is offered on the Rackspace Cloud server, it works fine. Is there any way to effectively throttle down the speed of the write? Just askin' :)
** UPDATE PART III *
So, I took the suggestion from #a sad dude and implemented a function that might help somebody trying to write to a new file and send it off in its entirety via ftp:
function writeFileAndFTP($filename=null, $data=null, $node=null, $local_path=null, $remote_path=null)
{
// !Determin the path and the file to upload from the webserver
$file = $local_path.'/'.$filename;
// !Open a new file to write to on the local machine
if (!($file_handle = fopen($file, "wb", 0))) {
die("There was a problem opening ".$file." for writing!");
}
// !Write the file to local disk
if ($bytesWritten = fwrite($file_handle, $data) ) {
//echo "There were " . $bytesWritten . " bytes written to " . $file;
}
// !Close the file from writing
if (!fclose($file_handle)) {
die("There was a problem closing " . $file);
}
// !Create connection to remote FTP server
$ftp_cxn = ftp_connect($node['addr'], $node['ftp_port']) or die("Couldn't connect to the ftp server.");
// !Login to the remote server
ftp_login($ftp_cxn, $node['user'], getPwd($node['ID'])) or die("Couldn't login to the ftp server.");
// !Set PASV or ACTIVE FTP
ftp_pasv($ftp_cxn, true);
// !Upload the file
if (!ftp_put($ftp_cxn, $remote_path.'/'.$filename, $file, FTP_ASCII)) {
die("There was an issue ftp'ing the file to ".$node['addr'].$remote_path);
}
// !Close the ftp connection
ftp_close($ftp_cxn);
}
The length of the string fwrite can write in one go is limited on some platforms (which is why it returns the number of bytes written). You can try running it in a loop, but a better idea is to simply use file_put_contents, which guarantees that the whole string will be written.
http://www.php.net/manual/en/function.file-put-contents.php

Categories