Create CSV File in PHP and Save to SFTP using phpseclib - php

I need to generate a CSV file from a MySQL query and save the file to an SFTP server. I have tried the code below. The CSV file gets created, but it is empty. I also receive an error message in the browser that says Warning: is_file() expects parameter 1 to be a valid path, resource given in regard to this line $sftp->put($fileName, $fp, NET_SFTP_LOCAL_FILE);. If I move fclose($fp); to the last line, I don't get the error but data still doesn't appear in the file. Could someone please let me know how to get the data to save in the file that was created?
$fileName = 'dataFiles/reports/Report Summary/Report Summary.csv';
$sql = mysqli_query($db, "
SELECT *
FROM reports
WHERE reportID = 1
");
$fp = fopen('php://output', 'w');
$first = true;
while($row = mysqli_fetch_assoc($sql)){
if ($first) {
fputcsv($fp, array_keys($row));
$first = false;
}
fputcsv($fp, $row);
}
fclose($fp);
$sftp->put($fileName, $fp, NET_SFTP_LOCAL_FILE);

Try something like this:
<?php
$fp = fopen('php://temp', 'r+');
// do stuff
rewind($fp);
$sftp->put($filename, $fp);
phpseclib (assuming you're using a new enough version) will detect that the second parameter is a stream resource and will try to read from it accordingly.

The second argument is not a handle but the content directly.
I think you could do: stream_get_contents($fp); in the second argument.
$content = stream_get_contents($fp);
fclose($fp);
$sftp->put($fileName, $content, NET_SFTP_LOCAL_FILE);

Related

Read a txt file in Storage

I have this file that is already stored in Storage. It's a txt file that contains data lines recorded as show picture below. I get this file using the Storage facade like
$file = Storage::get('public/' . $model->path_to_file);
dd($file); // <- output the picture below
Now I need read each line on this file, but can't figure it out how this must be done. Someone can help me?
I try this code but give me an exception:
$fp = fopen(Storage::path('public/' . $file_path->path_to_file), "r+");
while (($line = stream_get_line($fp, 1024 * 1024, "\n")) !== false) {
echo $line;
}
fclose($fp);
... 580583507 05-08-2021 15:20:09 05-08-2021 15:20:47 Luca RemoteControl {260f5a65-35a4-4b57-bd21-b378f0ab7b82}): failed to open stream: Invalid argument
How this must be solve?
You can use the comand feof (find end of file), so you can do anything you want to inside the loop.
$fp = fopen(Storage::path('public/' . $file_path->path_to_file), "r");
while(!feof($fp)){
$line = fgets($fp);
print_r($line."\n");
}
fclose($fp);

PHP Lock file while reading - flock() makes my file blank

As you can see in the code below, I'm trying to use flock to prevent other clients to acess the php (actually multiple users will acess this something like 10 times per second, each one), as I've found searching here... But this is not working. My data.txt is getting blank everytime doing this.
<?php
$fileName = $_GET["room"]."/data.txt";
function replaceLine($data){
if (stristr($data, $_GET["player"])){
return $_GET["player"]." ".$_GET["data"]."\n";
}
return $data;
}
$file = fopen($fileName,"r");
if (flock($file, LOCK_EX)){
//ftruncate($file, 0);
///--------------
$data = file($fileName);
$data = array_map("replaceLine", $data);
file_put_contents($fileName, implode('', $data));
echo fread($file, filesize($fileName)+1);
///--------------
fflush($file);
flock($file, LOCK_UN);
} else {
echo "wait";
}
fclose($file);
?>
This is the original code (that I was trying to modify to prevent making the file empty): (It works as I want, but have this file problem...)
<?php
$fileName = $_GET["room"]."/data.txt";
function replaceLine($data){
if (stristr($data, $_GET["player"])){
return $_GET["player"]." ".$_GET["data"]."\n";
}
return $data;
}
$data = file($fileName);
$data = array_map("replaceLine", $data);
file_put_contents($fileName, implode('', $data));
$file = fopen($fileName,"r");
echo fread($file, filesize($fileName)+1);
fclose($file);
?>
Sorry for asking this newbie question, but I have not idea how to fix this and I'm searching and trying different things for weeks! Thanks!
You are opening the file for read only and then you are attempting to write to that same file. Try setting the fopen parameter to read/write.
$file = fopen($fileName,"r+");
I would also use fwrite() instead of file_put_contents() since you already have the file pointer and opening it again will likely be denied by the lock.

Unable to append (read and write) text file with php. Using fopen() and fwrite() together

I recently installed Apache, PHP and started working on a small project.
I have the following code.
<?php
$tim=time();
$ip=$_SERVER['REMOTE_ADDR'];
$ipadd=$tim."IPaddress".$ip;
$fp="user_log.txt";// file address
$myfilea = fopen($fp,"a");//open file
fwrite($myfilea,$ipadd.PHP_EOL);//add data to file
echo fread($myfilea,filesize($fp));//read file
fclose($myfilea);//close file
?>
Here is what I can do... I can either use "a" mode to add text or I can use "r" mode to read text. I cant do both. I tried using "a+","r+","ar" etc.
Did I miss something during my setup ???
I am running this on windows 8.1.
Thanks for your help.
You need to rewind the file pointer.
$tim = time();
$ip = $_SERVER['REMOTE_ADDR'];
$ipadd = $tim.'IPaddress'.$ip;
// file address
$fp = 'user_log.txt';
//open file
$myfilea = fopen($fp, 'a+');
//add data to file
fwrite($myfilea, $ipadd.PHP_EOL);
// your file pointer is at the end of the file now
// so rewind before you read
rewind($myfilea);
//read file
echo fread($myfilea, filesize($fp));
//close file
fclose($myfilea);
Try this code, use file_put_contents
file_put_contents = Write a string to a file
$fp="user_log.txt";
$tim=time();
$ip=$_SERVER['REMOTE_ADDR'];
$ipadd=$tim."IPaddress".$ip;
$myfile = file_put_contents($fp, $ipadd.PHP_EOL , FILE_APPEND | LOCK_EX);
And for your code try this, it will check able to open file or not
fopen("logs.txt", "a") or die("Unable to open file!");

PHP - Export CSV to FTP rather than download in browser

I have been trying for a few hours now to no avail. I have successfully output my CSV as a download in the browser using:
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=".$csv_filename."");
However I want that output to now go to an FTP server instead, I have got the connection and temp file part sorted but cannot seem to edit the file to output my results.
// create empty variable to be filled with export data
$csv_export = '';
for($i = 0; $i < $field; $i++) {
$csv_export.= mysql_field_name($query,$i).',';
}
// newline (seems to work both on Linux & Windows servers)
$csv_export.= '
';
// loop through database query and fill export variable
while($row = mysql_fetch_array($query)) {
// create line with field values
for($i = 0; $i < $field; $i++) {
$csv_export.= '"'.$row[mysql_field_name($query,$i)].'",';
}
$csv_export.= '
';
}
Above is the part that gets the query data and puts it into the CSV, I have tried incorporating both fputs and fputcsv in the loops to write the rows to the file.
//Upload the temporary file to server
ftp_fput($ftpstream, '/httpdocs/.../abandoned.csv', $temp, FTP_ASCII);
$fp = fopen('var/www/vhosts/.../abandoned.csv', 'w');
fputs($fp, '$csv_export');
fclose($fp);
echo($csv_export);
So, echoing the output works absolutely fine - all I want is that echo'd data written into a CSV file and uploaded to the FTP.
The error I've been given is:
Array ( [type] => 2 [message] => fclose() expects parameter 1 to be resource,
boolean given
So the fp is causing the problem... is it at the open stage or at the writing of csv_export?
Thanks in advance.
Try this
//Write the contents to the temp file
fputs($temp, $csv_export);
//upload the temp file
ftp_fput($ftpstream, '/httpdocs/.../abandoned.csv', $temp, FTP_ASCII);
//close the temp file
fclose($temp);
Your current code is creating an empty file, uploading it, and then creating a separate file. Even if you get it working on a local server, it is an unnecessary step.
Try this, not tested:
$filename = 'abandoned.csv';
$content = $csv_export;
$host = 'yourhost';
$user = 'youruser';
$password = 'yourpass';
//open connection to your ftp server
$stream = stream_context_create(array('ftp' => array('overwrite' => true)));
//authenticate to your ftp server, normal uri syntax
$uri = sprintf('ftp://%s:%s#%s/%s', $user, $password, $host, $filename);
file_put_contents($uri, $content, 0, $stream);
In phpinfo(); you can look for Registered PHP Streams and just use this in most of any cases:
file_put_contents('ftp://user:password#server/your/directory/file.csv', $csvData);
ftp_fput is a right way here.
But you have to prepare FTP connection and authenticate first. Assuming you have $csv_export string in memory:
// connect
$ftp_conn = ftp_connect('ftp.yourserver.net');
// authenticate
$login_result = ftp_login($conn_id, 'ftp_username', 'password');
// prepare output stream
$stream = fopen('data://text/plain,' . $csv_export, 'r');
// try to upload
if (ftp_fput($ftp_conn, '/httpdocs/.../abandoned.csv', $stream, FTP_ASCII)) {
echo "Successfully uploaded\n";
} else {
echo "There was a problem while uploading\n";
}
// close the connection and the file handler
ftp_close($ftp_conn);
fclose($stream);
You're receiving that error because fopen is returning false, which indicates that it was unable to open the file.
If I'm understanding your code, you're uploading abandoned.csv (which presumably exists) to the ftp after opening it in $temp. Is $temp pointing at your local copy of abandon.csv? Because if so, you should close the file stream pointing to it before opening a second one with fopen.
If that's not the issue, then abandoned.csv may not actually exist, in which case you may just be trying to fopen a missing file.

How to write into a file in PHP?

I have this script on one free PHP-supporting server:
<html>
<body>
<?php
$file = fopen("lidn.txt","a");
fclose($file);
?>
</body>
</html>
It creates the file lidn.txt, but it's empty.
How can I create a file and write something into it,
for example the line "Cats chase mice"?
You can use a higher-level function like:
file_put_contents($filename, $content);
which is identical to calling fopen(), fwrite(), and fclose() successively to write data to a file.
Docs: file_put_contents
Consider fwrite():
<?php
$fp = fopen('lidn.txt', 'w');
fwrite($fp, 'Cats chase mice');
fclose($fp);
?>
$fp = fopen('lidn.txt', 'w');
fwrite($fp, 'Cats chase');
fwrite($fp, 'mice');
fclose($fp);
http://php.net/manual/en/function.fwrite.php
$text = "Cats chase mice";
$filename = "somefile.txt";
$fh = fopen($filename, "a");
fwrite($fh, $text);
fclose($fh);
You use fwrite()
It is easy to write file :
$fp = fopen('lidn.txt', 'w');
fwrite($fp, 'Cats chase mice');
fclose($fp);
Here are the steps:
Open the file
Write to the file
Close the file
$select = "data what we trying to store in a file";
$file = fopen("/var/www/htdocs/folder/test.txt", "w");
fwrite($file, $select->__toString());
fclose($file);
I use the following code to write files on my web directory.
write_file.html
<form action="file.php"method="post">
<textarea name="code">Code goes here</textarea>
<input type="submit"value="submit">
</form>
write_file.php
<?php
// strip slashes before putting the form data into target file
$cd = stripslashes($_POST['code']);
// Show the msg, if the code string is empty
if (empty($cd))
echo "Nothing to write";
// if the code string is not empty then open the target file and put form data in it
else
{
$file = fopen("demo.php", "w");
echo fwrite($file, $cd);
// show a success msg
echo "data successfully entered";
fclose($file);
}
?>
This is a working script. be sure to change the url in the form action and the target file in fopen() function if you want to use it on your site.
In order to write to a file in PHP you need to go through the following steps:
Open the file
Write to the file
Close the file
$select = "data what we trying to store in a file";
$file = fopen("/var/www/htdocs/folder/test.txt", "a");
fwrite($file , $select->__toString());
fclose($file );
fwrite() is a smidgen faster and file_put_contents() is just a wrapper around those three methods anyway, so you would lose the overhead.
Article
file_put_contents(file,data,mode,context):
The file_put_contents writes a string to a file.
This function follows these rules when accessing a file.If FILE_USE_INCLUDE_PATH is set, check the include path for a copy of filename
Create the file if it does not exist then Open the file and Lock the file if LOCK_EX is set and If FILE_APPEND is set, move to the end of the file. Otherwise, clear the file content
Write the data into the file and Close the file and release any locks.
This function returns the number of the character written into the file on success, or FALSE on failure.
fwrite(file,string,length):
The fwrite writes to an open file.The function will stop at the end of the file or when it reaches the specified length,
whichever comes first.This function returns the number of bytes written or FALSE on failure.

Categories