I am trying to read multiple .sql files and then execute them into the database. This works, although now I am in need of deleting the file after its been successfully been imported to the database.
How would I be able to accomplish this?
<?php
function scan_for_sql_files($path){
$itdir = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($path, \RecursiveDirectoryIterator::SKIP_DOTS),
\RecursiveIteratorIterator::SELF_FIRST,
\RecursiveIteratorIterator::CATCH_GET_CHILD);
$files = array();
foreach ($itdir as $path=>$dir){
if ($dir->isFile()){
$ext = substr(strtolower($path), -3);
if($ext == 'sql'){
$files[] = array('path' => $path);
}
}
}
return $files;
}
//get files
$files = scan_for_sql_files('mysqls');
//Do sql
foreach($files as $file){
$sql = file_get_contents($file['path']);
$qr = $dbh->exec($sql);
}
?>
You can use unlink() function to delete the file.
unlink('test.html');
foreach($files as $file){
$sql = file_get_contents($file['path']);
$qr = $dbh->exec($sql);
if(is_file($file['path'])){
unlink($file['path']);
}
}
Ref: http://us2.php.net/unlink
You can add the "unlink" function to get rid of the file
Simple modification :
foreach($files as $file){
$sql = file_get_contents($file['path']);
$qr = $dbh->exec($sql);
unlink($file['path']);
}
http://www.w3schools.com/php/func_filesystem_unlink.asp
"Unlink" reference
you can delete your sql file by this
unlink('database.sql');
or
you can delete sql file content by this
file_put_contents("database.sql", "");
if you are working on window os don't worry but if you are working in linux you have to set permission of all sql file other wise your file will not access by your php script
Related
I have simple script like add-to-cart where I can put multiple files for later downloading. When user click on add to cart I store the ID of the file in session and when he click download all based on ID's stored it lookup into database table and download the files.
All the files are stored in same folder and I keep the names in table. The problem that I faced is that in the table I have 3 columns which hold different files(items). This is what I have so far and is working for one column. Question is how to add other two columns?
$files = $_SESSION['itemid'];
$valid_files = array();
if(is_array($files)) {
foreach($files as $file) {
$sql = "SELECT * FROM document_upload WHERE upload_id = :id";
$result = $pdo->prepare($sql);
$result->bindParam(":id", $file);
$result->execute();
$resArray = $result->fetch();
if (file_exists($filePath . $resArray['upload_lesson_plan'])){
$valid_files[] = $resArray;
}
}
}
if(count($valid_files > 0)){
$zip = new ZipArchive();
$zip_name = "zipfile.zip";
if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE){
$error .= "* Sorry ZIP creation failed at this time";
}
foreach($valid_files as $res){
$zip->addFile($filePath.$res['upload_lesson_plan']);
// columns that I want to add and take files from...
//$zip->addFile($filePath.$res['upload_worksheet']);
//$zip->addFile($filePath.$res['upload_materials']);
}
Those are both columns which I want to take files from
//$zip->addFile($filePath.$res['upload_worksheet']);
//$zip->addFile($filePath.$res['upload_materials']);
I have tried something like this but doesn't work.. just showing me blank page and doesn't download anything and no errors.
if (file_exists($filePath . $resArray['upload_lesson_plan'] || $filePath . $resArray['upload_worksheet'] || $filePath . $resArray['upload_materials']))
They are stored in columns and they are multiple files in same column comma separated.
Acording to what you said
They are stored in columns and they are multiple files in same column comma separated.
You can try this way. With explode them:
foreach($resArray as $col){
$items = explode(',', $col);
foreach ($items as $item) {
if (file_exists($filePath . trim($item))){
$valid_files[] = $filePath . trim($item);
}
}
And then call them like this
foreach($valid_files as $res){
$zip->addFile($res);
}
just
foreach(['upload_lesson_plan', 'upload_worksheet', 'upload_materials'] as $col){
if (file_exists($filePath . $resArray[$col])){
$valid_files[] = $resArray[$col];
}
}
I'm struggling around with a simple PHP functionality: Creating a ZIP Archive with some files in.
The problem is, it does not create only one file called filename.zip but two files called filename.zip.a07600 and filename.zip.b07600. Pls. see the following screenshot:
The two files are perfect in size and I even can rename each of them to filename.zip and extract it without any problems.
Can anybody tell me what is going wrong???
function zipFilesAndDownload_Defect($archive_file_name, $archiveDir, $file_path = array(), $files_array = array()) {
// Archive File Name
$archive_file = $archiveDir."/".$archive_file_name;
// Time-to-live
$archiveTTL = 86400; // 1 day
// Delete old zip file
#unlink($archive_file);
// Create the object
$zip = new ZipArchive();
// Create the file and throw the error if unsuccessful
if ($zip->open($archive_file, ZIPARCHIVE::CREATE) !== TRUE) {
$response->res = "Cannot open '$archive_file'";
return $response;
}
// Add each file of $file_name array to archive
$i = 0;
foreach($files_array as $value){
$expl = explode("/", $value);
$file = $expl[(count($expl)-1)];
$path_file = $file_path[$i] . "/" . $file;
$size = round((filesize ($path_file) / 1024), 0);
if(file_exists($path_file)){
$zip->addFile($path_file, $file);
}
$i++;
}
$zip->close();
// Then send the headers to redirect to the ZIP file
header("HTTP/1.1 303 See Other"); // 303 is technically correct for this type of redirect
header("Location: $archive_file");
exit;
}
The code which calls the function is a file with a switch-case... it is called itself by an ajax-call:
case "zdl":
$files_array = array();
$file_path = array();
foreach ($dbh->query("select GUID, DIRECTORY, BASENAME, ELEMENTID from SMDMS where ELEMENTID = ".$osguid." and PROJECTID = ".$osproject.";") as $subrow) {
$archive_file_name = $subrow['ELEMENTID'].".zip";
$archiveDir = "../".$subrow['DIRECTORY'];
$files_array[] = $archiveDir.DIR_SEPARATOR.$subrow['BASENAME'];
$file_path[] = $archiveDir;
}
zipFilesAndDownload_Defect($archive_file_name, $archiveDir, $file_path, $files_array);
break;
One more code... I tried to rename the latest 123456.zip.a01234 file to 123456.zip and then unlink the old 123456.zip.a01234 (and all prior added .a01234 files) with this function:
function zip_file_exists($pathfile){
$arr = array();
$dir = dirname($pathfile);
$renamed = 0;
foreach(glob($pathfile.'.*') as $file) {
$path_parts = pathinfo($file);
$dirname = $path_parts['dirname'];
$basename = $path_parts['basename'];
$extension = $path_parts['extension'];
$filename = $path_parts['filename'];
if($renamed == 0){
$old_name = $file;
$new_name = str_replace(".".$extension, "", $file);
#copy($old_name, $new_name);
#unlink($old_name);
$renamed = 1;
//file_put_contents($dir."/test.txt", "old_name: ".$old_name." - new_name: ".$new_name." - dirname: ".$dirname." - basename: ".$basename." - extension: ".$extension." - filename: ".$filename." - test: ".$test);
}else{
#unlink($file);
}
}
}
In short: copy works, rename didn't work and "unlink"-doesn't work at all... I'm out of ideas now... :(
ONE MORE TRY: I placed the output of $zip->getStatusString() in a variable and wrote it to a log file... the log entry it produced is: Renaming temporary file failed: No such file or directory.
But as you can see in the graphic above the file 43051221.zip.a07200 is located in the directory where the zip-lib opens it temporarily.
Thank you in advance for your help!
So, after struggling around for days... It was so simple:
Actually I work ONLY on *nix Servers so in my scripts I created the folders dynamically with 0777 Perms. I didn't know that IIS doesn't accept this permissions format at all!
So I remoted to the server, right clicked on the folder Documents (the hierarchically most upper folder of all dynamically added files and folders) and gave full control to all users I found.
Now it works perfect!!! The only thing that would be interesting now is: is this dangerous of any reason???
Thanks for your good will answers...
My suspicion is that your script is hitting the PHP script timeout. PHP zip creates a temporary file to zip in to where the filename is yourfilename.zip.some_random_number. This file is renamed to yourfilename.zip when the zip file is closed. If the script times out it will probably just get left there.
Try reducing the number of files to zip, or increasing the script timeout with set_time_limit()
http://php.net/manual/en/function.set-time-limit.php
I have pdf files which are report cards of students.The report card names format is <student full name(which can have spaces)><space><studentID>.I need to download files.For this I have used the following code.
if(file_exists($folder_path.'/') && is_dir(folder_path)) {
$report_files = glob(folder_path.'/*'.'_*\.pdf' );
if(count($report_files)>0)
{
$result_data = '';
$result_data = rename_filenamespaces($report_files);
var_dump($result_data);//this shows the edited filename
foreach ($result_data as $file) {
if (strpos($file,$_GET['StudentID']) !== false) {
//code for showing the pdf docs to download
}
}
}
}
//function for renaming if filename has spaces
function rename_filenamespaces($location)
{
$new_location = $location;
foreach ($location as $file) {
//check file has spaces and filename has studentID
if((strpos($file," ")!==false)&& (strpos($file,$_GET['StudentID']) !== false))
{
$new_filename = str_replace(" ","-",$file);
rename($file,$new_filename);
$new_location = $new_filename;
}
}
return $new_location;
}
The variable $result_data gives me the filename without spaces,but the for each loop is showing Warning:Invalid argument supplied for foreach(). But the filename is changed in the server directory immediately after running the function. This warning shows only for first time. I am unable to solve this.
$new_location = $new_filename;
$new_location is a array
$new_filename is a string
You have to use $new_location[$index]
or try
foreach ($new_location as &$file) {
...
...
$file = $new_filename;
I would like to delete all files matching a particular extension in a specified directory and all subtree. I suppose I should be using using unlink but some help would be highly appreciated... Thank you!
you need a combination of this
Recursive File Search (PHP)
And the unlink / delete
You should be able to edit the example instead of echoing the file, to delete it
To delete specific extension files from sub directories, you can use the following function. Example:
<?php
function delete_recursively_($path,$match){
static $deleted = 0,
$dsize = 0;
$dirs = glob($path."*");
$files = glob($path.$match);
foreach($files as $file){
if(is_file($file)){
$deleted_size += filesize($file);
unlink($file);
$deleted++;
}
}
foreach($dirs as $dir){
if(is_dir($dir)){
$dir = basename($dir) . "/";
delete_recursively_($path.$dir,$match);
}
}
return "$deleted files deleted with a total size of $deleted_size bytes";
}
?>
e.g. To remove all text files you can use it as follows:
<?php echo delete_recursively_('/home/username/directory/', '.txt'); ?>
The below code, checks in my folder 'mysqls' for .sql files. Then I want it to execute the .sqls into the database.
<?php
$dirf = 'mysqls';
$dir = scandir($dirf);
unset($dir['0']);
unset($dir['1']);
foreach($dir as $file) {
$sql = file_get_contents($file);
$qr = $dbh->exec($sql);
}
?>
I've used die(var_dump($sql)); although it comes up with bool(false)
The code finds all the files that have the .sql extension successfully, although it does not execute it.
You have to add the directory for file_get_contents():
$sql = file_get_contents($dirf . '/'. $file);