I am trying to create and write a file to ec2 instance. I am getting the error below despite the folder that i am writing possessing all the permissions required.
$handle = fopen("thumbnailFolder/testFile.txt", "r"); // line 4
if($handle != false){
echo 'File created!';
}else{
echo 'File create failed!';
}
The 'thumbnailFolder' has the following permissions:
drwxrwxrwx
Error message:
fopen(thumbnailFolder/testFile.txt): failed to open stream: No such file or directory in /var/www/html/book_aws/my_server/folder/web/thumbnailTest.php on line 4
File create failed!
As the error clearly say. System is failing to open the file which is not there.
$handle = fopen("thumbnailFolder/testFile.txt", "r");
Above code open files in read mode. if there is no files then throws an error.
If you want to open file to write then use try below code, this tries to open file and sets pointer at the begining if file is not there then creates the file in given name. for read and write use w+ instead of w
$handle = fopen("thumbnailFolder/testFile.txt", "w");
There are different modes with respect files. you can check below link for further details.
http://php.net/manual/en/function.fopen.php
Related
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())
Actually i want to send zip file to the dropbox .But when i try to open my file using fopen then this issue comes.
fopen(www.cloud01.wptemplate.net_09_10_2015_16_1444437876.zip): failed to open stream: No such file or directory in /home/cle1296/cloud01.wptemplate.net/wp-content/plugins/wp-cloud-safe/includes/UltimateBackup.php on line 830.
My server is dreamhost.I execute the same code on another server and don't face any issue.It seems that dreamhost disabled the fopen function.So kindly give me an alternative way
function sendToDropbox() {
try {
$this->log('Sending file to DropBox');
$dbxClient = new dbx\Client($this->dropboxGeneratedAccessToken, "PHP-Example/1.0");
$f = fopen($this->backupFilename, "r+");
$dbxClient->uploadFile($this->dropboxUploadPath . $this->backupFilename, dbx\WriteMode::add(), $f);
} catch (Exception $e) {
$this->log('ERROR while uploading file to DropBox');
}
}
The path to the file obviously is not correct, either because the file does not exist or simply what you passed to fopen() is not the actual location of the backup. Use the full path to the file to be absolutely sure, for example if your backup is at:
/home/cle1296/cloud01.wptemplate.net/my_backups/backup.zip
...then make sure to pass it to your fopen() and you shouldn't have any issues.
I'm trying to save some text that comes into a php script via a POST to a file. Here is my script:
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
$file = $path . '\test.txt';
$text = $_POST['text'];
// save it to a file
if (file_exists($file))
chmod($file, 0777);
$handle = fopen($file, 'w');
fwrite($handle, $text);
fclose($handle);
echo "success";
?>
I'm getting this error:
Warning:
fopen(D:\Hosting\11347607\html\test.txt) [function.fopen]: failed to open stream:
Permission denied in
D:\Hosting\11347607\html\test_file_saver.php on line
12
I've tried a number of different attempts and read many posts. The directory is set to RWX permission. How can I get permission to write to this file? Thanks!
If you don't have permissions to even open the file, what makes you think you have permission to change permissions?
That wasn't a question or a comment. You don't have permission to change the permission. Give your PHP process proper permissions.
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);
}
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);
}