Convert database to CSV and save the file to a folder on the server

I managed to export my database to csv as a download file. However, what I now need to do is not to create a direct .csv file that is uploaded, I just need to save it to a folder named "csv" on the server. Here is my code for the current export. I need help saving a part of the server. Chmod in folder (csv) - 777

$today = date('Ym-d'); $select = "SELECT * FROM goldpacks WHERE date = '$today'"; $export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) ); $fields = mysql_num_fields ( $export ); for ( $i = 0; $i < $fields; $i++ ) { $header .= mysql_field_name( $export , $i ) . "\t"; } while( $row = mysql_fetch_row( $export ) ) { $line = ''; foreach( $row as $value ) { if ( ( !isset( $value ) ) || ( $value == "" ) ) { $value = "\t"; } else { $value = str_replace( '"' , '""' , $value ); $value = '"' . $value . '"' . "\t"; } $line .= $value; } $data .= trim( $line ) . "\n"; } $data = str_replace( "\r" , "" , $data ); if ( $data == "" ) { $data = "\n(0) Records Found!\n"; } header("Content-type: application/octet-stream"); header("Content-Disposition: attachment; filename=import.csv"); print "$header\n$data"; 
+6
source share
1 answer

All you need to add is a call to file_put_contents() . You already have your CSV formatted correctly in $data , so the writing process is simple:

 // $filename is whatever you need the file to be called file_put_contents("/path/to/csv/" . $filename, "$header\n$data"); 

Instead of permissions 777 in the csv folder, it should belong to the user who the web server operates as with 700 , or belongs to the group that owns the web server as 770 .

+9
source

Source: https://habr.com/ru/post/894665/


All Articles