简体   繁体   中英

How to save file in subfolder using php

I have a script with a mysql query which saves a file called invoice.xml every day automatically by running a cron job. In case no data is found a no_orders.txt is saved.

I would like this file not be saved to the same folder as the script.php file is in but to a subfolder called invoices .

The renaming of the old invoice.xml is done with the following code

 // rename old file
$nowshort = date("Y-m-d");
if(file_exists('invoice.xml')) {
  rename('invoice.xml','invoice_'.$nowshort.'.xml');
}  

The saving is done with the following code:

if($xml1 !='') {    
    $File = "invoice.xml"; 
     $Handle = fopen($File, 'w');
     fwrite($Handle, $xml1);  
     print "Data Written - ".$nowMysql; 
     fclose($Handle); 
    #print $xml;
    die();
} else {
     print "No new orders - ".$nowMysql; 
     $File = "no_orders_".$nowshort.".txt"; 
     $Handle = fopen($File, 'w');  
     fclose($Handle);
     die();
}

Could I please get assistance how to save this file to a subfolder. Also the renaming of the existing file would need to be within the subfolder then. I have already tried with possibilities like ../invoice/invoice.xml but unfortunately without any success.

Thank you

Just give the path of file 'invoice.xml' to $File. Otherwise create some $Dir object which will point to Folder named 'invoice', then use accordingly

Use __DIR__ magic constant to retrieve your script.php directory, then you can append /invoice/invoice.xml .

Example if path to your script php something like this: /var/www/path/to/script.php

$currentDir = __DIR__; //this wil return /var/www/path/to
$invoicePath = $currentDir.'/invoice/invoice.xml';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM