Why is this code resulting in bool(false)? - php

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);

Related

Using move_uploaded_file To Rename File BEFORE Being Placed In uploads/ Folder

I've seen questions similar to this but no one seems to have the problem I do.
I've set up a process to check to see if the filename already exists in a MySQL table, and if it does, it puts a timestamp between the filename and the extension (E.G. Test.PDF becomes Test-19:25:36 if it's a duplicate), thus negating any database conflicts.
My issue is that the while the database is updated correctly, the duplicate file isn't uploaded with the timestamp in the name. Instead, it uses the duplicate name and just overwrites the original and creates a ghost "filename" listing in the database.
I've seen you can use move_uploaded_file to rename files in the servers memory before they're uploaded, but I've tried multiple ways and can't get it to rename the file in memory BEFORE attempting to write it to the "/uploads" folder. Here's the upload code:
<?php
include_once 'dbconnect.php';
//check if form is submitted
if (isset($_POST['submit'])) {
// START OF PRE-EXISTING FILE CHECK
$filename = $_FILES['file1']['name'];
$dupeCheck = "SELECT * FROM tbl_files WHERE filename = '$filename'";
if ($output = mysqli_query($con, $dupeCheck)) {
if (mysqli_num_rows($output) > 0) {
$fileArray = pathinfo($filename);
$timeStamp = "-" . date("H:i:s");
$filename = $fileArray['filename'] . $timeStamp . "." . $fileArray['extension'];
}
}
// END OF PRE-EXISTING FILE CHECK
if($filename != '')
{
$trueCheck = true;
if ($trueCheck == true) {
$sql = 'select max(id) as id from tbl_files';
$result = mysqli_query($con, $sql);
//set target directory
$path = 'uploads/';
$created = #date('Y-m-d H-i-s');
$moveTargetVar = "uploads/" . $filename;
move_uploaded_file($_FILES['file1']['tmp_name'], $moveTargetVar);
// insert file details into database
$sql = "INSERT INTO tbl_files(filename, created) VALUES('$filename', '$created')";
mysqli_query($con, $sql);
header("Location: index.php?st=success");
}
else
{
header("Location: index.php?st=error");
}
}
else
header("Location: index.php");
}
?>
Any advice on how to rename a file before it's written to the uploads folder?
I'd suggest not using : to separate your time stamp, because that will cause issue with file name restrictions. Try doing something like:
$timeStamp = "-" . date("H-i-s");
Solved by replacing move_uploaded_file($_FILES['file1']['tmp_name'], $moveTargetVar); with move_uploaded_file($_FILES['file1']['tmp_name'],$path . $filename);
Deprecated $moveTargetVar = "uploads/" . $filename;

Use copy() in a foreach loop to copy multiple files php

I'm trying to copy multiple files from one domain on a web server to another using copy() and looping through a list of files, but it's only copying the last file on the list.
Here is the contents of files-list.txt:
/templates/template.php
/admin/admin.css
/admin/codeSnippets.php
/admin/editPage.php
/admin/index.php
/admin/functions.php
/admin/style.php
/admin/editPost.php
/admin/createPage.php
/admin/createPost.php
/admin/configuration.php
This script runs on the website that I'm trying to copy the files to. Here's the script:
$filesList = file_get_contents("http://copyfromhere.com/copythesefiles/files-list.txt");
$filesArray = explode("\n", $filesList);
foreach($filesArray as $file) {
$filename = trim('http://copyfromhere.com/copythesefiles' . $file);
$dest = "destFolder" . $file;
if(!#copy($filename, $dest))
{
$errors= error_get_last();
echo "COPY ERROR: ".$errors['type'];
echo "<br />\n".$errors['message'];
} else {
echo "$filename copied to $dest from remote!<br/>";
}
}
I get the affirmative message for each and every file individually just as I should, but when I check the directory, only the last file from files-list.txt is there. I've tried changing the order, so I know the problem lies with the script, not any individual file.
The output from the echo statements looks something like this:
http://copyfromhere.com/copythesefiles/admin/admin.css copied to updates/admin/editPage.php from remote!
http://copyfromhere.com/copythesefiles/admin/admin.css copied to updates/admin/editPost.php from remote!
http://copyfromhere.com/copythesefiles/admin/admin.css copied to updates/admin/index.php from remote!
Etc
I've modified your code slightly, and tested it on my local dev server. The following seems to work:
$fileURL = 'http://copyfromhere.com/copythesefiles';
$filesArray = file("$fileURL/files-list.txt", FILE_IGNORE_NEW_LINES);
foreach ($filesArray as $file) {
$fileName = "$fileURL/$file";
$dest = str_replace($fileURL, 'destFolder', $fileName);
if (!copy($fileName, $dest)) {
$errors= error_get_last();
echo "COPY ERROR: ".$errors['type'];
echo "<br />\n".$errors['message'];
}
else {
echo "$fileName copied to $dest from remote!<br/>";
}
}
This uses the same fix that Mark B pointed out, but also consolidated the code a little.
Unless the data you're fetching from that remote site has leading/ in the path/filename, you're not generating proper paths:
$file = 'foo.txt'; // example only
$dest = "destFolder" . $file;
produces destFolderfoo.txt, and you end up littering your script's working directory with a bunch of wonky filenames. Perhaps you wanted
$dest = 'destFolder/' . $file;
^----note this
instead.

On creating zip file by php I get two files instead of one

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

Removing a file after sql execution in PHP

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

How to auto delete a zip file after using stream_get_contents(); to view a file in php?

I have this code to read a file for preview, but the downside is I have to download the file first from cloud and read from it, but it's a waste of space so I want to delete it after viewing a certain file. Is there an automatic way of doing this? Or do I have to integrate it to a close button?
// Get the container we want to use
$container = $conn->get_container('mailtemplate');
//$filename = 'template1.zip';
// upload file to Rackspace
$object = $container->get_object($filename);
//var_dump($object);
//echo '<pre>' . print_r($object,true) . '</pre>';
$localfile = $dir.$filename;
//echo $localfile;
$object->save_to_filename($localfile);
if($_GET['preview'] == "true")
{
$dir = "../mailtemplates/";
$file1 = $_GET['tfilename'];
$file = $dir.$file1;
$file2 = "index.html";
$info = pathinfo($file);
$file_name = basename($file,'.'.$info['extension']);
$path = $file_name.'/'.$file2;
$zip = new ZipArchive();
$zip->open($file);
$fp = $zip->getStream($path);
if(!$fp)
{
exit("faileds\n");
$zip->close();
unlink($dir.$filename);
}
else
{
$stuff = stream_get_contents($fp);
echo $stuff;
$zip->close();
if($stuff != null)
{
unlink($dir.$filename);
}
}
}
else
{
unlink($dir.$filename);
}
You didn't google this did ya?
Try Unlink
Edit:
Taking a look at this code, $zip->open($file); <-- is where you open the file. The file variable is set by:
"../mailtemplates/" . basename($_GET['tfilename'], '.' . $info['extension']) . '/' . "index.html"
So you're grabbing a relative directory and grabbing a filename as a folder, and going to that folder /index.html. Here's an example:
if you're in c:\ testing and you go to ../mailtemplates/ you'll be in c:\mailtemplates and then you're looking at file test.php but you're removing the file extension, so you'll be opening the location c:\mailtemplates\test\index.html so you open up that html file and read it. Then, you're trying to delete c:\mailtemplates\test.php
can you explain how any of that makes sense to you? 'cause that seems very odd to me.

Categories