简体   繁体   中英

PHP - locking an exported file

I'm looking for an easiest way to lock a file. The following code export a .csv file from mysql via php code :

<?php
require_once('connect_db.php');
$fdate = $_POST['fdate'];
$tdate = $_POST['tdate'];
//Selecting Items based on Date 
$result = mysql_query("SELECT item_no, qty, discount_price, date FROM sold_items WHERE date BETWEEN '".$fdate."' AND '".$tdate."' ORDER BY date Desc");


//Check if File Name Exists
$filename = $name = "C:/Sales-{$tdate}".".csv";
$index = 1;
while(file_exists($filename)) {
  $filename = $name.'--'.$index.".csv";
  $index++;
}

//Fputs the Table Headers
fputcsv($f, array('Item No', 'Qty', 'Sell Price', 'Date'));

//Fputcsv adds records to csv file
while($row = mysql_fetch_array($result, MYSQL_NUM))
{
    fputcsv($f, $row);
}

//Close file
fclose($f);

?>

All i need know is a code that will do any of the following:

  • Password protect .csv file when trying to open it

  • locking fields which makes this file uneditable

  • or convert this .csv file to zip file, and create password before extracting it.

I'm not looking for high secured way to lock this file. However while googling around I found this code :

<?php echo system('zip -P pass file.zip file.txt'); ?>

I've tried it! but its not working.

Thank You


Edit: Using flock

$file = fopen("{$filename}", "w+"); 

// exclusive lock 
if (flock($file,LOCK_EX)){ 
//Fputs the Table Headers
fputcsv($f, array('Item No', 'Qty', 'Sell Price', 'Date'));

//Fputcsv adds records to csv file
while($row = mysql_fetch_array($result, MYSQL_NUM))
{
    fputcsv($f, $row);
}

  flock($file,LOCK_UN); 
} 
else{ 
  echo "Could not lock file!"; 
} 

fclose($file); 

?>

It will export the csv file empty but when trying to write something inside any fields and save it; An error will pop up " filename " is read-only and forces me to save as file to another name. But after saving as the file, you can still edit fields and save it. How to disable save as?

What about the PHP function flock ? Small example:

<?php

$file = fopen("test.txt","w+");

// exclusive lock
if (flock($file,LOCK_EX)){

  //write to file here

  // release lock
  flock($file,LOCK_UN);
}
else{
  echo "Could not lock file!";
}

fclose($file);

?> 

Either you can change its permission using chmod() function.

You can pass parameter like

0777 which means full permission for read-write same way you can assign by which no one can read or write in file.

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