php cli reading files and how to fix it? - php

While using PHP cli in ubuntu i got apache as web server i cant read the file which i can while using it in the browser.
And about the error it just shows nothing and the next like i just used this code for my testing purposes :
<?
$handle = fopen("testFile.txt", "r");
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
echo $buffer;
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
if(!is_readable($handle)
{
die("Not readable");
}
fclose($handle);
}
?>
How do i fix that ?
EDIT :
After removing the '#' before fopen i got the following error
fopen(testFile.txt): failed to open
stream: No such file or directory in
/var/www/log/ka.php on line 2

When you run your script through CLI, it uses your shell's working directory, in opposition to the file's directory (which Apache hands as the current directory). This is important for you, since your fopen call depends on a relative path; and relative paths are resolved relatively to the working directory, not to the script.
To have your script behave like it does with Apache, you either need to cd /var/www/log prior to running the php command, or add this at the beginning of your PHP script:
chdir(dirname(__FILE__));

Related

Read or download 5kb of a file from FTP server in PHP or Python instead of downloading or reading whole file

I want to download or read part of a file from the FTP server instead of downloading the whole file, this is to just see the data that exists in the FTP server is correct.
We have so many clients and each file in the FTP server might be of any size, so instead of downloading or reading the complete file, I just want to download or read a part of the file, let's say I want only 5kb of file or if by line 100 lines from a file.
I have a function in PHP like below which does half of the work, but for larger files, it fails.
function readByBytes($path)
{
try
{
$handle = fopen($path, "rb");
if ($handle)
{
while (($buffer = fgets($handle, 4096)) !== false)
{
}
if (!feof($handle))
{
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
}
catch (Exception $e)
{
echo $e;
}
}
$filename = "ftp://username:password#127.0.0.1/prod/clientfeed.csv";
$iterator = readByBytes($filename);
foreach ($iterator as $key => $iteration)
{
/// if file read is 5kb or some 100 lines
break;
}
Can somebody help me or guide me on this in PHP or Python
Below warning errors getting
PHP Warning: fopen(ftp://...#127.0.0.1/prod/clientfeed.csv): failed
to open stream: FTP server reports 550 Could not get file size.
in /var/www/html/newLpplugins/ftp_read_line_line.php on line 80
PHP Warning: filesize(): stat failed for
ftp://...#127.0.0.1/prod/clientfeed.csv in
/var/www/html/newLpplugins/ftp_read_line_line.php on line 81
PHP Warning: fread() expects parameter 1 to be resource, bool given
in /var/www/html/newLpplugins/ftp_read_line_line.php on line 81
PHP Warning: fclose() expects parameter 1 to be resource, bool given
in /var/www/html/newLpplugins/ftp_read_line_line.php on line 82
PHP Warning:
file_get_contents(ftp://...#127.0.0.1/prod/clientfeed.csv): failed to
open stream: FTP server reports 550 Could not get file size.
in /var/www/html/newLpplugins/ftp_read_line_line.php on line 84
Thanks in advance.
If you want to read only part of the file, then just remove your while loop and call fgets only once.
$buffer = fgets($handle, 4096);
Though if the file is binary or if you want to read a fixes amount of bytes, you better use fread.
$buffer = fread($handle, 4096);
Though your server is not compatible with PHP URL wrappers, see:
Getting "FTP server reports 550 Could not get file size." when using FTP URL in fopen
And PHP does not offer any other robust alternative for your needs.
Though it is doable in Python with ftplib:
ftp = FTP()
ftp.connect(host, user, passwd)
size = 4096
cmd = "RETR {}".format(filename)
f = BytesIO()
aborted = False
def gotdata(data):
f.write(data)
while (not aborted) and (f.tell() >= size):
ftp.abort()
aborted = True
try:
ftp.retrbinary(cmd, gotdata)
except:
# An exception when transfer is aborted is expected
if not aborted:
raise
f.seek(0)
The code is based on my answer to:
Get files names inside a zip file on FTP server without downloading whole archive
There are ways to achieve this in python.
Solution 1:
Paramkio - The SSH V2 library implemented in python
Paramiko has the option to read N bytes from the file which is present in a remote location
sClient = ssh_client.open_sftp()
remoteFileLocation = sftp_client.open('<filepath>')
for line in remote_file:
#dosomethinghere
Soltuion 2:
This is an ad-hoc solution. Before that just clarifying if you just want to get to know that the file has content in it, you can use this.
Run a remote command to get a file size using the Python subprocess module.
from subprocess import Popen, PIPE
p = Popen(["du", "-sh", "filepath"], stdin=PIPE)
output = p.communicate(msg.as_string())

Calling PHP when running HTML locally not echoing strings

I like to test my Javascript by running on my local drive to avoid having to upload to my web page each time I make changes. In my HTML file I just use full paths to point to PHP files on my web page. Haven't had a problem until I ran into this. The PHP file below runs fine if I run the HTML file from my web page. But if I run the HTML file from my local drive, only the first part of the PHP file works. The foreach block does not - or it's just not echoing the strings.
I've tried using the full path to the folder rather than just ".txt" below even though it seems that shouldn't be necessary as the PHP is run at the server end.
I tried other methods of reading files in a directory in case the "glob" useage was the problem when running on my local drive.
I even did away with all the commands within the foreach block and just put an echo statement there, but nothing appeared.
I'm guessing an echo statement doesn't work when the PHP file is called from an HTML file on a local drive?
Tried innerHTML with a but that didn't work - or I'm not doing it correctly.
<?php
$MSG=$_GET["myFile"];
$fh = fopen($myFile, "w") or die("can't open file");
$MSG=$_GET["jsVar"];
fwrite($fh, $jsVar);
fclose($fh);
foreach (glob("*.txt") as $filename) {
echo $filename;
echo "<br />";
$file = fopen($filename, "r");
while(!feof($file)){
$line = fgets($file);
echo $line . "<br />";
}
fclose($file);
}
?>
Windows doesn't support PHP, you must install XAMPP to run it through localhost.

PHP file_put_contents works with file, no file gets "failed to open stream: No such file or directory"

The PHP file_put_contents function works perfectly fine when the file exists. If the file does not exist I receive the error "failed to open stream: No such file or directory".
$file = '../templates/stuff.xml';
if (!file_exists($file)) {$file = '../'.$file;}
$var['xhtml'] = $_POST['post_xhtml'];
$file_contents = serialize($var);
file_put_contents($file,$file_contents);
I tried the same thing with fopen and fwrite using the correct flags (w, w+ and tried the others) yet still had the same problem: if the file already existed it worked just fine, otherwise it would give me the same error message.
I know the file path is correct. I'm using Windows 7 for local development.
When the file doesn't exist, you are prepending ../ to the path, thus you are trying to write to:
../../templates/stuff.xml
Are you sure that the folder ../../templates exists (and that PHP can write to it)?
Before you write to a file, you need to check that the folder exists. Try using is_dir():
if(is_dir(dirname($file))){
file_put_contents($file, $file_contents);
}

PHP Permissions Denied fopen

I ran into a really bizarre problem. I am trying to perform writing to file using fopen().
This is what I tried in writetofile.php:
$fw = fopen('/test.txt', 'w');
fwrite($fw, 'hello world' . "\r\n");
fclose($fw);
This is the error I keep getting:
Warning: fopen(/test.txt):
failed to open stream: Permission denied in C:\inetpub\wwwroot\writetofile.php on line 41
Warning: fwrite() expects parameter 1 to be resource, boolean given...
I am 100% sure I have permissions to the server. I am the Administrator. Furthermore, I temporarily gave full permissions to everyone. I even tried running the php script locally, directly from the server using localhost. I am not using apache, I am using IIS. I tried restarting IIS after modifying permissions. I am not running php in safe mode.
Any idea on what might be causing this issue?
/test.txt would be a file in the ROOT directory of your filesystem, where user accounts generally do NOT have write privileges (unless you're running this code as root). This is especially true of PHP running under the webserver's user account.
You probably want just test.txt (no leading slash)` which will try to put the file into the script's "current working directory" - usually the same directory the script itself is in.
1- when you rollout website, delete all logs folder names
2- inside the code create folder name as below and create the logs insides
3- write at top of file. (during init the web)
$ClientUserName = gethostbyaddr($_SERVER['REMOTE_ADDR']);
function Data_Log($dataline)
{
global $ClientUserName;
$dir = 'UserInputLog' ;
$fileName = $ClientUserName. '_ServerWebLog.txt';
if(is_dir($dir) === false)
mkdir($dir);
$fileName = $dir. '\\'.$fileName;
$myfile = fopen($fileName, "a") or die("Unable to open file!");
fwrite($myfile, "$dataline\r\n");
fclose($myfile);
}

Linux Box using PHP writing file to Windows Server Web Share

We have a bunch of linuix and windows servers.
On my windows desktop I can see all the shares.
Using PHP I'm attempting to write a file to a directory on a windows share using the UNC path.
//ServerShare/directory/file.txt
Using fwrite says it successfully wrote the file but the file never exists on the server.
Using opendir function says the directory isn't accessible.
This is the source pretty simple.
$file_name = "\\SERVER2\Share\CPI\data.txt";
if (!$handle = fopen($file_name, 'w')) {
echo "Cannot open file ($file_name)";
exit;
}
// Write $somecontent to our opened file.
$somecontent = "this is a test";
if (fwrite($handle, $somecontent) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
echo "Success, wrote ($somecontent) to file ($file_name)";
fclose($handle);
Any thoughts on what types of permissions need to be set to let a linux box write files to a windows box?
You should be mounting the fileshare to a local directory:
mount -f smbfs //user#server2/Share/CPI/Data.txt /media/share
Then access /media/share/Share/CPI/Data.txt from your PHP script.
PHP needs to authenticate to the share, even if it is public, and using fopen or opendir does not do this.

Categories