ZF2, PGSQL - how to determine current save path of file? - php

I would like to save some data from pgsql database to a csv file. The thing you also should know that I'm working at ZF2 Framework. So the code looks like this:
$adapter = $this->serviceMenager->get('db');
$adapter->query("Copy (Select * From data.my_data) To '/test.csv' With CSV;")->execute();
But while I'm trying to execute the code, I'm getting exception:
SQLSTATE[42501]: Insufficient privilege: 7 ERROR: could not open file "/test.csv" for writing: Permission denied
That was the thing that I was expecting, because the only writing path is the public folder with privilages 777. But if I execute:
$adapter->query("Copy (Select * From data.my_data) To '/public/test.csv' With CSV;")->execute();
I'm getting exception:
SQLSTATE[58P01]: Undefined file: 7 ERROR: could not open file "/public/test.csv" for writing: No such file or directory
How to determine where am I (I mean current path)? And how to properly set the path in the query to export my data?
Thanks in advice.

It seems to be executed on PGSQL and not MYSQL as ins0 said.
The problem is almost what he stated though. You are trying to write to /test.csv, which means for PGSQL the root of the Unix server. You need to give the path you really want, and you can actually get the root of your app with getcwd.
Then your code will look like this:
$adapter = $this->serviceMenager->get('db');
$file = getcwd()."/public/test.csv";
$adapter->query("Copy (Select * From data.my_data) To '". $file ."' With CSV;")->execute();

Related

PHP Change default User on fopen

I'm having problems when trying to write a file with a different user rather than www-data.
I need to leave the file on a mapped unit that it's NOT mine so i cannot change permissions on that one. Insetead i have a username and a group, let's call them 'myself':'myself'
I'm using Symfony 5 Filesystem to move files around but i still use PHP's fopen to create those files. This is what i have so far.
private function moveAndDeleteFile($url_origin, $url_destiny)
{
$filesystem = new Filesystem();
$a = fopen($url_origin, 'wa+');
fwrite($a, 'Test');
fclose($a);
$filesystem->copy($url_origin, $url_destino, true);
if (!$filesystem->exists($url_destiny)) {
return false;
}
$filesystem->remove($url_origin);
return true;
}
This is just a test, so i'm creating a file (name included in $url_origin) and try to copy the file to $url_destiny and then remove the original (again, just a test).
The ting is that the file is always created by www-data and for my target directory i need to set the file owner to 'myself'.
Is there any way i can change the file owner with sudo?
$filesystem->chown($url_origin, 'myself', false);
This returns an error -> Failed to chown file "my/route/file.xml"
Same thing happens when trying
$filesystem->chgrp($url_origin, 'myself', false);
Then i tried to use the default PHP chown() function like this:
chown($url_origin, 'myself');
And get this other Error: Operation not permitted.
I guess that i need to specify somewhere the user's properties but i'm clueless right now. Any ideas on how to pass this through? i'm sure i'm missing something obvious.
Thanks-.
You cannot use "chown" because only "root" can use "chown".
The way is to set "chmod" or change configuration in your server with php-fpm running with myself user.
Regards

Laravel - Read an SQLite file dynamically

I am trying to work on a project that accepts an SQLite file via upload, saves it, and parses the data in the SQLite database. I am finding that when I use a smaller DB file the "-wal" and "-shm" files are not being created but when using a larger DB (at least 2mb) they are.
Here is the code that I am using:
$destination = storage_path().'/tempDir/databases/'.$userId.'/';
//store the file in the directory
$request->file('database')->move($destination .'database/database.db');
$destination = $destination.'database/database.db';
Config::set('database.connections.sqlite.database', $dbLocation);
$sqliteDbConnection = \DB::connection('sqlite');
$getUsers = $sqliteDbConnection->table("users")->get();
Whenever I try and do this, I am getting the following error:
"SQLSTATE[HY000]: General error: 10 disk I/O error (SQL: select * from \"users\")"
Does anyone have an idea why that might be? I can confirm that the file being saved to the server is in good standing, I am able to open it with other SQLite viewers.
UPDATE: Is it possible that the link between Homestead and my MAC is prohibiting the file from being accessed by Laravel?
UPDATE2: The problem is 100% located in the sharing mechanism between VirtualBox and the computer. I tried this via XAMPP and it works alright. WTF?
This is how I managed to get a Builder instance with my custom PDO connection:
$pathname = '/absolute/path/to.sqlite';
$connection = new \Illuminate\Database\SQLiteConnection(new \PDO('sqlite:' . $pathname));
$builder = new \Illuminate\Database\Query\Builder($connection);
$builder->newQuery()->from('my_table')->get()->all();

PHP Rename error : The system cannot find the path specified. (code: 3)

I want to move an excel file from one folder to another, I have used the following line of code
$approve_employee_id = $this->input->post('approve_employee_id');
$approve_month_id = $this->input->post('approve_month_name');
$approve_year_name = $this->input->post('approve_year_name');
$approve_employee_username = $this->input->post('approve_employee_username');
$folder_name = $approve_month_id.$approve_year_name;
rename(".files/".$folder_name."/un_approved/".$approve_employee_username, ".files/".$folder_name."/approved/".$approve_employee_username);
I keep on getting the following error from the system :
A PHP Error was encountered
Severity: Warning
Message: rename(.files/January2013/un_approved/HS0103,.files/January2013/approved/HS0103): The system cannot find the path specified. (code: 3)
Filename: controllers/time_sheet.php
Line Number: 279
My folder tree is as follows :
C:\xampp\htdocs\timesheet\files\January2013\approved for approved and C:\xampp\htdocs\timesheet\files\January2013\un_approved for un approved
Please advise on the best way to implement this ?
Perhaps you should use "./files", instead of ".files" ...?
However, I'd suggest to decouple the location of your data files from the location of your php script... So, I should do:
...
$basedir = $_SERVER['DOCUMENT_ROOT'] . "/timesheet/files/$folder_name";
rename("$basedir/un_approved/$approve_employee_username", "$basedir/approved/$approve_employee_username);
This approach makes your life easier when you should deploy your code do different web servers, for example...
use __DIR__.'./../yourfolder/'
I tried and it works
I just stick to full path as it makes it much more easy to understand ...
for example
dirname(__FILE__).'/files/etc/etc/path.yourfile';
you can go up the tree by
dirname(dirname(__FILE__)).'/files/etc/etc/path.yourfile'; and so on
You can try this ...
$files_folder = dirname(__FILE__); //or go up as required.
Then
rename($files_folder."/".$folder_name."/un_approved/".$approve_employee_username, $files_folder."/".$folder_name."/approved/".$approve_employee_username);

php&mysql fopen cannot open the file

I am using PHP & MySQL to generate a dynamic web page. Now I want to make the search result into a file.
Firstly, I use
$query = "select * from database into outfile 'query.txt'";#mysql($query);
BUt it cannot work;
Then, I try to use the "fopen" function.
$fp=fopen("query.txt","w+") or exit("Unable to open file!");
if($result_specific){
while( $row = mysql_fetch_array( $result_specific,MYSQL_ASSOC )){
echo fwrite($fp,$row["p1"]."\t".$row["p2"]."\t".$row["p3"]."\n");
}
}
fclose($fp);
Unfortunately, it tells me "Unable to open file!".
Maybe it is a wrong Url?
But I don't know how to specify the correct URL.
select * from database into outfile 'query.txt'
You haven't specified a path - only a filename. The file will be written to the current working directory of the MySQL instance. It will be written with the uid of the the user running the instance. It's impossible to say from the information you've provided what permissions the resultant file will have - on a Linux/BSD/Posix system the permissions will be based on he the umask inherited by the DBMS instance.
$fp=fopen("query.txt","w+")
Is you PHP looking in the right directory? What are the permissions on the file?
or exit("Unable to open file!");
That 'or' will not do what you think it does - should be '||'
if($result_specific){
...
What has this got to do with the problem?
Go back and use full paths and check the permissions.

PHP MySQL OUTFILE command

If I use the following in a mysql_query command:
SELECT *
FROM mytable
INTO OUTFILE '/tmp/mytable.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n';
Where is the tmp file relative to, to the MySQL database somehow or to the PHP file?
If it does not exist will it be created?
If I would like it to appear 1 folder up from the PHP file which does it, how would I do that?
According to The Documentation On Select, it's stored on the server and not on the client:
The SELECT ... INTO OUTFILE 'file_name' form of SELECT writes the selected rows to a file. The file is created on the server host, so you must have the FILE privilege to use this syntax. file_name cannot be an existing file, which among other things prevents files such as /etc/passwd and database tables from being destroyed. As of MySQL 5.0.19, the character_set_filesystem system variable controls the interpretation of the file name.
And, more to the point:
The SELECT ... INTO OUTFILE statement is intended primarily to let you very quickly dump a table to a text file on the server machine. If you want to create the resulting file on some other host than the server host, you normally cannot use SELECT ... INTO OUTFILE since there is no way to write a path to the file relative to the server host's file system.
So, don't use it in production to generate CSV files. Instead, build the CSV in PHP using fputcsv:
$result = $mysqli->query($sql);
if (!$result) {
//SQL Error
}
$f = fopen('mycsv.csv', 'w');
if (!$f) {
// Could not open file!
}
while ($row = $result->fetch_assoc()) {
fputcsv($f, $row);
}
fclose($f);
Where is the tmp file relative to?
A: The file will have the result of the select * from mytable
If it does not exist will it be created?
A: yes
If I would like it to appear 1 folder up from the php file which does it, how would I do that?
A: if you want one folder up from the fileYouAreRunning.php then make path like that: "../mytable.csv"
Your current query has an absolute path. So the outfile will not be relative to anything, but saved to /tmp/mytable.csv.
I'd say, the safest bet would be to keep useing absolute paths, so check in your php what your absolute path to the parent is, and then add this to your query using a variable.

Categories