Link to home
Start Free TrialLog in
Avatar of Jake_D87
Jake_D87Flag for Australia

asked on

PHP/MySQL to create CSV in remote folder

So i am trying to create a page that will query my database and export the data to a csv file in a remote folder... I can make it work all good, except it wont save it to the folder, it will just bring up the SAVE/OPEN box...  Script is below...

$query = sprintf( "SELECT * FROM table" );
$result = mysql_query( $query, $conn ) or die( mysql_error( $conn ) );

header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment;filename=CUST.CSV' );

  $row = mysql_fetch_assoc( $result );
  if ( $row )
  {
    echocsv( array_keys( $row ) );
  }

  while ( $row )
  {
    echocsv( $row );
    $row = mysql_fetch_assoc( $result );
  }

  function echocsv( $fields )
  {
    $separator = '';
    foreach ( $fields as $field )
    {
      if ( preg_match( '/\\r|\\n|,|"/', $field ) )
      {
        $field = '"' . str_replace( '"', '""', $field ) . '"';
      }
      echo $separator . $field;
      $separator = ',';
    }
    echo "\r\n";
  }

Open in new window

Avatar of Dave Baldwin
Dave Baldwin
Flag of United States of America image

Security restrictions prevent you from saving a file on someone's computer without their permission.  SAVE/OPEN is all you get.
Avatar of Jake_D87

ASKER

No i want it to save the csv into the same folder that the php file is in...
ASKER CERTIFIED SOLUTION
Avatar of Dave Baldwin
Dave Baldwin
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
One problem, when i run this with a cronjob it doesnt create the csv file... I know its running because there is an SQL script which is executing successfully. Any ideas?
Does your user have full permissions in the directory where you are trying to write it?  Or is it just the web server that has permissions there?