I'm new in php.
Every 17 seconds my php code generates id1.php and id2.php in this folder:"sitename.com/"
So, every 17 seconds i've got this:
sitename.com/master.php
sitename.com/id1.php
sitename.com/id2.php
sitename.com/filebag/id1.php
sitename.com/filebag/id2.php
sitename.com/filebag/id3.php
after script generates id1.php and id2.php i need to copy this files to sitename/filebag/ and if filename exist add +1. so in the end, i must get this situation:
sitename.com/
sitename.com/master.php
sitename.com/filebag/id1.php
sitename.com/filebag/id2.php
sitename.com/filebag/id3.php
sitename.com/filebag/id4.php
sitename.com/filebag/id5.php and so on...
i use master.php to do a replace
<?php
$idname = "id1";
copy ("./id1.php","./filebag/$idname.php");
?>
question is how can i rename file if filename exist in this folder "sitename.com/filebag/"
This code delivers what you want:
<?php
$stringName = "id";
$numName = "1";
$file_orig = './' . $stringName . $numName . '.php';
$file_dest = './filebag/' . $stringName . $numName . '.php';
if(file_exists($file_dest))
{
$count = (int)$numName;
while(file_exists($file_dest))
{
$count = $count + 1;
$file_dest = './filebag/' . $stringName . $count . '.php';
}
}
copy ($file_orig, $file_dest);
?>
Related
I am trying to read the PDF files in each child job and pull out the number of pages in each. My code works perfectly for the first file, but not for the second. My thinking is that the file is not being overwritten by the second PDF that's pulled in.
I am downloading the file to read it, so there's no need to keep it afterwards.
I tried putting in a check to unlink the file after use, but I get a permission denied error.
$CI = &get_instance();
$CI->load->library('Awss3', null, 'S3');
$PdfTranscriptInfo = $CI->MJob->getDOCCSPdfTranscript($copy['jobid']);
$filename = $PdfTranscriptInfo['origfilename'];
$PdfFilename = 'uploads/' . $copy['jobid'] . '/' . $filename;
$localfilename = FCPATH . 'tmp/local.pdf';
$fileData = $CI->S3->readfile($PdfFilename, false, 'bucket');
require_once 'application/libraries/fpdi/fpdf.php';
require_once 'application/libraries/fpdi/fpdi.php';
$pdf = new FPDI();
$pageCount = $pdf->setSourceFile($localfilename);
if ($pageCount == $copy['pagecount']) {
echo '<td>' . $copy['pagecount'] . '</td>';
} else {
echo '<td style="background-color:red;">' . $copy['pagecount'] . '/' . $pageCount . '</td>';
}
if (file_exists($localfilename)) {
unlink(FCPATH . 'tmp/local.pdf');
}
I am not getting any error messages, but the page count for the second file ($pageCount) is the same as the first file, so it's obviously not picking up the second PDF.
Thanks in advance for any help.
EDIT: FCPATH is C:\wamp64\www\companyname\
In a filemanagement, for moving files to another folder, i am trying to count the number of files which already exists in a folder.
foreach($checkboxfiles as $checkboxfile) {
$src_file = $checkboxfile;
$fileName = basename($src_file);
$new_dest = $_POST['cbdestination'];
/* New path for this file */
$dest_file = $MainFolderName.'/'. $new_dest . '/' . $fileName;
echo count(file_exists($dest_file)); //this should give me the number of files which already exists
As 2 files are already exists, the echo produces
11
11
as output.
How can i achieve the number 2 as output?
You're using count wrong. file_exists returns true or false. count is used for counting arrays.
Ir order to achieve what you want you can do:
$count = 0;
foreach($checkboxfiles as $checkboxfile) {
$src_file = $checkboxfile;
$fileName = basename($src_file);
$new_dest = $_POST['cbdestination'];
/* New path for this file */
$dest_file = $MainFolderName.'/'. $new_dest . '/' . $fileName;
if(file_exists($dest_file)){
$count++;
}
}
echo $count;
You can count number of files in a folder by FilesystemIterator(requires PHP 5 >= 5.3.0, PHP 7)
$fi = new FilesystemIterator('directory/location', FilesystemIterator::SKIP_DOTS);
printf("Number of files: %d ", iterator_count($fi));
Here is my code, what I am trying to do is take the file post.php or $file from the root of the directory that it is originally from, then put it inside this uniqueID directory, or it should finally arrive in the $newFolder5 variable to complete. The $root in the !copy function is a path pointing to the file inside the current directory, then it should go it the $newFolder5 directory when the copy function is executed on the page load. Can $root or the source of the copy be a string with a directory to the file?
<?php
$unique = uniqid();
$root = '/gallry/' . $dir_auth1 . '/'. 'post.php';
$folder = mkdir($unique, 0755);
$uniqueFolder = '/' . $unique . '/' . 'post.php';
$destination2 = $dir_auth1 . '/' . $unique . '/' . 'post.php';
$newFolder = '/' . $dir_auth1 . $uniqueFolder;
if (!copy($root, $newFolder)) {
echo " status not created.";
} else {
echo "Success!";
}
?>
I changed $dir_auth1 to 'aidan', since that is the root directory that the post.php is in.
In short, what Im trying to do is create a folder/directory with a uniqid() and put post.php inside of it. Or copy it.
You're not creating the same directory that you're trying to copy into.
$unique = uniqid();
$root = "/gallry/$dir_auth1/post.php";
$uniqueFolder = "/$dir_auth1/$unique";
$destFile = "$uniqueFolder/post.php";
if (mkdir($uniqueFolder)) {
if (copy($root, $destFile)) {
echo "Success!";
} else {
echo " status not created";
}
} else {
echo "Unable to create folder $uniqueFolder";
}
I'm using the mailReader script found here: https://github.com/stuporglue/mailreader
I am trying to copy the file(s) after upload to another folder.
The file(s) upload correctly to the folder where the script resides.
When I try to run a copy command, the filename variable is empty.
Here is the portion of the code I am working with: The last three lines are what I added.
private function saveFile($filename,$contents,$mimeType = 'unknown'){
$filename = preg_replace('/[^a-zA-Z0-9_-]/','_',$filename);
$unlocked_and_unique = FALSE;
while(!$unlocked_and_unique){
// Find unique
$name = time() . "_" . $filename;
$name = substr_replace($name,".pdf",-4); // added 1-19-2016
while(file_exists($this->save_directory . $name)) {
$name = time() . "_" . $filename;
$name = substr_replace($name,".pdf",-4);
}
// Attempt to lock
$outfile = fopen($this->save_directory.$name,'w');
if(flock($outfile,LOCK_EX)){
$unlocked_and_unique = TRUE;
}else{
flock($outfile,LOCK_UN);
fclose($outfile);
}
}
fwrite($outfile,$contents);
fclose($outfile);
if (copy($this->save_directory.$name, "/attachments/" . TRANS_ID . "/". $name)) {
unlink( $this->save_directory.$name );
}
I receive confirmation by email that the file(s) are uploaded, then another email with the error message.
Warning: copy(/attachments/W7652222-546/1453406138_residential-print_from_td.pdf): failed to open stream: No such file or directory in /home/myhost/public_html/mailreader/mailReader.php on line 224
224 being the line number of my added code.
The source filename is missing from in front of /attachments...
Anyone have any thoughts?
$name is defined in the while loop and may not be accessible on the upper scopes my suggestion is to change your code to this:
private function saveFile($filename,$contents,$mimeType = 'unknown'){
$filename = preg_replace('/[^a-zA-Z0-9_-]/','_',$filename);
$unlocked_and_unique = FALSE;
$name = '';
while(!$unlocked_and_unique){
// Find unique
$name = time() . "_" . $filename;
$name = substr_replace($name,".pdf",-4); // added 1-19-2016
while(file_exists($this->save_directory . $name)) {
$name = time() . "_" . $filename;
$name = substr_replace($name,".pdf",-4);
}
// Attempt to lock
$outfile = fopen($this->save_directory.$name,'w');
if(flock($outfile,LOCK_EX)){
$unlocked_and_unique = TRUE;
}else{
flock($outfile,LOCK_UN);
fclose($outfile);
}
}
fwrite($outfile,$contents);
fclose($outfile);
if (copy($this->save_directory.$name, "/attachments/" . TRANS_ID . "/". $name)) {
unlink( $this->save_directory.$name );
}
I hope this solves your problem
I ended up defining a constant of email_id in the private function saveToDb, then running a script after everything else is finished to query the table using the email_id and looping through the records moving the files.
Long time reader, first time poster. I know just enough about php to be dangerous and this is my first BIG project using it.
Some background:
I have over 1 million (yes, million) .html files that were generated from an old news gathering program. These .html files contain important archive information that needs to be searched on daily basis. I have yet to get to other servers which might very well have more so 2-3 million+ is not out of the question.
I am taking these .html files and transferring them into a mysql database. At least, so far, the code has worked wonderfully with several hundred test files. I'll attach the code at the end.
The problem starts when the .html files are archived, and it's a function of the box generating the archive which cannot be changed, is the files go into folders. They are broken down like this
archives>year>month>file.html
so an example is
archives>2002>05may>lots and lots of files.html
archives>2002>06june>lots and lots of files.html
archives>2002>07july>lots and lots of files.html
With help and research, I wrote code to strip the files of markup that includes html2text and simple_html_dom and put the information from each tag in the proper fields in my database, which works great. But ALL of the files need to be moved to the same directory for it to work. Again, over a million and possibly more for other severs takes a REALLY long time to move. I am using a batch file to robocopy the files now.
My question is this:
Can I use some sort of wildcard to define all of the subdirectories so I don't have to move all of the files and they can stat in their respective directories?
Top of my code:
// Enter absolute path of folder with HTML files in it here (include trailing slash):
$directory = "C:\\wamp1\\www\\name\\search\\files\\";
The subdirectories are under the files directory.
In my searches for an answer, I have seen "why would you want to do that?" or other questions asking about .exe files or .bat files in the directories and how it could be dangerous so don't do it. My question is just for these html files so there is nothing being called or running and no danger.
Here is my code for stripping the html into the database. Again, works great, but I would like to skip the step of having to move all of the files into one directory.
<?php
// Enter absolute path of folder with HTML files in it here (include trailing slash):
$directory = "C:\\wamp1\\www\\wdaf\\search\\files\\";
// Enter MySQL database variables here:
$db_hostname = "localhost";
$db_username = "root";
$db_password = "password";
$db_name = "dbname";
$db_tablename = "dbtablename";
/////////////////////////////////////////////////////////////////////////////////////
// Include these files to strip all characters that we don't want
include_once("simple_html_dom.php");
include_once("html2text.php");
//Connect to the database
mysql_connect($db_hostname, $db_username, $db_password) or trigger_error("Unable to connect to the database host: " . mysql_error());
mysql_select_db($db_name) or trigger_error("Unable to switch to the database: " . mysql_error());
//scan the directory and look for all the htmls files
$files = scandir($directory);
for ($filen = 0; $filen < count($files); $filen++) {
$html = file_get_html($directory . $files[$filen]);
// first check if $html->find exists
if (method_exists($html,"find")) {
// then check if the html element exists to avoid trying to parse non-html
if ($html->find('html')) {
//Get the filename of the file from which it will extract
$filename = $files[$filen];
//define the path of the files
$path = "./files/";
//Combine the patha and filename
$fullpath = $path . $filename;
// Get our variables from the HTML: Starts with 0 as the title field so use alternate ids starting with 1 for the information
$slug = mysql_real_escape_string(convert_html_to_text($html->find('td', 8)));
$tape = mysql_real_escape_string(convert_html_to_text($html->find('td', 9)));
$format0 = mysql_real_escape_string(convert_html_to_text($html->find('td', 10)));
$time0 = mysql_real_escape_string(convert_html_to_text($html->find('td', 11)));
$writer = mysql_real_escape_string(convert_html_to_text($html->find('td', 12)));
$newscast = mysql_real_escape_string(convert_html_to_text($html->find('td', 13)));
$modified = mysql_real_escape_string(convert_html_to_text($html->find('td', 14)));
$by0 = mysql_real_escape_string(convert_html_to_text($html->find('td', 15)));
$productionCues = mysql_real_escape_string(convert_html_to_text($html->find('td', 16)));
$script = mysql_real_escape_string(convert_html_to_text($html->find('td', 18)));
// Insert variables into a row in the MySQL table:
$sql = "INSERT INTO " . $db_tablename . " (`path`, `fullpath`, `filename`, `slug`, `tape`, `format0`, `time0`, `writer`, `newscast`, `modified`, `by0`, `productionCues`, `script`) VALUES ('" . $path . "', '" . $fullpath . "', '" . $filename . "', '" . $slug . "', '" . $tape . "', '" . $format0 . "', '" . $time0 . "', '" . $writer . "', '" . $newscast . "', '" . $modified . "', '" . $by0 . "', '" . $productionCues . "', '" . $script . "');";
$sql_return = mysql_query($sql) or trigger_error("Query Failed: " . mysql_error());
}
}
}
?>
Thanks in advance,
Mike
Just wanted to update this post with a answer to my question that works quite well. With some help, we found that scandir used recursively to create an array would work.
I thought I'd post this so if anyone else was looking to do something similar, they would be able wouldn't have to look far! I know I like to see answers!
The code is from the second user-contributed note here with a few modifications: http://php.net/manual/en/function.scandir.php
so in my code above, I replaced
//scan the directory and look for all the htmls files
$files = scandir($directory);
for ($filen = 0; $filen < count($files); $filen++) {
$html = file_get_html($directory . $files[$filen]);
with
function import_dir($directory, $db_tablename) {
$cdir = scandir($directory);
foreach ($cdir as $key => $value)
{
if (!in_array($value,array(".","..")))
{
if (is_dir($directory . DIRECTORY_SEPARATOR . $value))
{
// Item in this directory is sub-directory...
import_dir($directory . DIRECTORY_SEPARATOR . $value,$db_tablename);
}
else
// Item in this directory is a file...
{
$html = file_get_html($directory . DIRECTORY_SEPARATOR . $value);
and then for the filenames, replaced
//Get the filename of the file from which it will extract
$filename = $files[$filen];
//define the path of the files
$path = "./files/";
//Combine the patha and filename
$fullpath = $path . $filename;
with
//Get the filename of the file from which it will extract
$filename = mysql_real_escape_string($value);
//define the path of the files
$path = mysql_real_escape_string($directory . DIRECTORY_SEPARATOR);
//Combine the patha and filename
$fullpath = $path . $value;
Thanks to those who answered!
Mike
I'm not sure how long it would take before your PHP query times out, but there is an inbuilt function RecursiveDirectoryIterator which sounds like it might do the trick for you.