Check if file exists in 2 directories using ASP or PHP - file-io

I am looking for a way to compare 2 directories to see if a file exists in both. What I want to do is delete a file in 1 of the directories if it exists in both.
I can either use ASP or PHP.
Example:
/devices/1001
/devices/1002
/devices/1003
/devices/1004
/devices/1005
/disabled/1001
/disabled/1002
/disabled/1003
So since 1001, 1002, 1003 exist in /disabled/, I want to remove them from /devices/ and only be left with 1004, 1005 in /devices/.

Using scandir() to get an array of the file names in each directory, and then using array_intersect() to find elements of the first array that are present in any additional arguments given.
http://au.php.net/manual/en/function.scandir.php
http://au.php.net/manual/en/function.array-intersect.php
<?php
$devices = scandir('/i/auth/devices/');
$disabled = scandir('/i/auth/disabled/');
foreach(array_intersect($devices, $disabled) as $file) {
if ($file == '.' || $file == '..')
continue;
unlink('/i/auth/devices/'.$file);
}
Applied as a function including checking the directories are valid:
<?php
function removeDuplicateFiles($removeFrom, $compareTo) {
$removeFromDir = realpath($removeFrom);
if ($removeFromDir === false)
die("Invalid remove from directory: $removeFrom");
$compareToDir = realpath($compareTo);
if ($compareToDir === false)
die("Invalid compare to directory: $compareTo");
$devices = scandir($removeFromDir);
$disabled = scandir($compareToDir);
foreach(array_intersect($devices, $disabled) as $file) {
if ($file == '.' || $file == '..')
continue;
unlink($removeFromDir.DIRECTORY_SEPARATOR.$file);
}
}
removeDuplicateFiles('/i/auth/devices/', '/i/auth/disabled/');

It's very easy with PHP - in this example we set the two base directories and the filename... this could easily be an array in a foreach() loop. Then we check in both directories to see if it does indeed reside in each. If so, we delete from the first. This can be easily modified to delete from the second.
See below:
<?php
$filename = 'foo.html';
$dir1 = '/var/www/';
$dir2 = '/var/etc/';
if(file_exists($dir1 . $filename) && file_exists($dir2 . $filename)){
unlink($dir1 . $filename);
}

if ($handle = opendir('/disabled/')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
unlink('/devices/' . $file);
}
}
closedir($handle);
}

In php, use this for checking if the file exists.... it will return true or false...
file_exists(relative file_path)

For each file in devices check to see if it exists in disabled using the disabled path and the file name from devices.
<%
Set fso = server.createobject("Scripting.FileSystemObject")
Set devices = fso.getfolder(server.mappath("/i/auth/devices/"))
Set disabledpath = server.mappath("/i/auth/disabled/")
For each devicesfile in devices.files
if directory.fileExists(disablepath & devicesfile.name ) Then
Response.Write " YES "
Response.write directoryfile.name & "<br>"
Else
Response.Write " NO "
Response.write directoryfile.name & "<br>"
End if
Next
%>

Related

Is there a syntax error in this iCalendar event code?

I have a 'Subscribed Calendar' on my iPhone which fetches calendar events in the iCalendar format from a URL. The calendar works fine except it does not show the following event, is there a reason why? All other events show fine. I'm thinking there's maybe a problem with the way the event is formatted/syntax but I can't seem to find anything that may be causing it.
BEGIN:VEVENT SUMMARY:Meet with tenant DESCRIPTION:Notes: Meter readings\, SoC images\, post box key\, finalise Let Procedure.\nLocation: Apartment X X Woodland Road\, Bebington\, Wirral\, CHXX XXX\nEmployee: Michael Le Brocq\nStatus: Confirmed\nOriginally Arranged: 07/09/16 12:18:43 by Lucy Christian\nLast Updated: 12/09/16 15:57:05 by Michael Le Brocq\n UID:2432 STATUS:CONFIRMED DTSTART:20160914T160000 DTEND:20160914T151500 LAST-MODIFIED:20160912T155705 LOCATION:Apartment 5 20 Woodland Road\, Bebington\, Wirral\, CH42 4NT END:VEVENT
Code used to generate calendar events;
<?php
require_once('../inc/app_top_cron.php');
if (!empty($_GET)) {
// define and escape each GET as a variable
foreach ($_GET as $key => $value) {
if (!empty($value)) {
${$key} = mysqli_real_escape_string($con, PrepareInput($value));
}
}
}
// company details
$company_details_query = mysqli_query($con, "SELECT company_id, company_trading_name FROM company WHERE company_token = '" . $company . "' LIMIT 1") or die(mysql_error());
$company_details = mysqli_fetch_array( $company_details_query );
// the iCal date format. Note the Z on the end indicates a UTC timestamp.
define('DATE_ICAL', 'Ymd\THis');
// max line length is 75 chars. New line is \\r\n
$output = "BEGIN:VCALENDAR
METHOD:PUBLISH
VERSION:2.0
PRODID:-//Property Software//Calendar//EN
CALSCALE:GREGORIAN
X-WR-CALNAME:" . $company_details['company_trading_name'] . " Calendar" . "
\r\n";
$sql = "SELECT ce.*, ces.calendar_event_status_name
FROM calendar_event ce
INNER JOIN calendar_event_status ces
on ce.calendar_event_status = ces.calendar_event_status_id
WHERE ce.calendar_event_company_id = '" . $company_details['company_id'] . "'";
$calendar_event_query = mysqli_query($con, $sql) or die(mysql_error());
while($row = mysqli_fetch_array( $calendar_event_query )) {
$calendar_event_subject = str_replace(",","\,", $row['calendar_event_subject']);
$calendar_event_description = str_replace(",","\,", $row['calendar_event_description']);
$calendar_event_description = str_replace("\r\n","\\n", $calendar_event_description);
$calendar_event_location = str_replace(",","\,", $row['calendar_event_location']);
// loop through events
$output .=
"BEGIN:VEVENT
SUMMARY:" . $calendar_event_subject . "
DESCRIPTION:" . $calendar_event_description . "
UID:" . $row["calendar_event_id"] . "
STATUS:" . $row["calendar_event_status_name"] . "
DTSTART:" . date(DATE_ICAL, strtotime($row["calendar_event_start"])) . "
DTEND:" . date(DATE_ICAL, strtotime($row["calendar_event_end"])) . "
LAST-MODIFIED:" . date(DATE_ICAL, strtotime($row["calendar_event_date_updated"])) . "
LOCATION:" . $calendar_event_location . "
END:VEVENT
";
}
// close calendar
$output .= "END:VCALENDAR";
echo $output;
mysqli_close($con);
?>
This:
$calendar_event_description = str_replace("\r\n","\\n", $calendar_event_description);
You're taking \r\n (carriage return + newline) and turning them into a literal \ character, followed by an n. That's not a new line (one byte/character), it's TWO bytes/characters, and has no special meaning to anything.
And as per my comments above, don't do multiline string building/concatenating. it makes for hard-to-read and hard-to-follow debugging. Use a heredoc instead:
$output = <<<EOL
BEGIN:VEVENT
SUMMARY: {$calendar_event_subject}
DESCRIPTION: {$calendar_event_description}
UID: {$row["calendar_event_id"]}
etc...
EOL;
Note the lack of any " or . - making for a much more compact and easy-to-follow code block. If you need to change the line breaks afterwards, because your system uses something different than what your code editor is embedding, you can do that with a simple str_replace() after finishing building the string.
The icalendar standard requires \r\n line breaks between lines. You can validate the icalendar output using the validator at http://icalendar.org/validator.html

I need a Tracking Pixel in vb.net

In php i fire off my pixel in a if statement like this :
if ($result == C){
echo "<img src='http://www.123123.com/tracking/RecordPixel.aspx?cmp=933&optional'/>";
}else{
echo "<meta http-equiv=\"refresh\" content=\"0;URL='http://123123.co.uk/index.php/'\"> ";
}
I am trying to do this in vb.net and i am looking for resources and cannot find any.
In VB.NET you can add a server control to your page, as a literal control. And in codebehind (for ex. in pageload), you can translate it in something similar to:
if (result = C) then
yourLiteralID.text = "<img src..."
else
yourLiteralID.text = "<meta..."
end if

file name automatically change when i upload the file

I'm new to CodeIgniter and having the following issue. When I upload a file, its successfully uploaded on my local folder and the file name saved to the db. The problem is, file name has been changed after uploading.
eg:
file name "screenshot image 123.png" -> "screenshot_image_123.png"
It just convert the space into underscore;this issue occurred only when the file name having space.Other than this issue all the other files uploading successfully. Given below is my code which I used on my controller page:
public function upload_pic()
{
$image_path = realpath(APPPATH . '../uploads');
$config['upload_path'] = $image_path;
$config['allowed_types'] = "gif|jpg|jpeg|png";
$config['file_name'] = $_FILES['file']['name'];
$config['encrypt_name'] = TRUE;
$config['overwrite'] = TRUE;
$this->load->library('upload',$config);
$this->upload->initialize($config);
if(!$this->upload->do_upload('file'))
{
echo $this->upload->display_errors();
}
else
{
$finfo=$this->upload->data();
$data['uploadInfo'] = $finfo;
}
}
Can anyone help me????
Try before saving file name generate some unique
$filename = $_FILES['file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$filename = sha1_file($filename). md5(date('Y-m-d H:i:s:u')) . '.'. $ext; //not only this you can generate any format
$config['file_name'] = $filename; //Use this file name is db too

Elegantly appending a set of strings (.txt file) to another set of strings (.txt also)?

This request might seem slightly ridiculous, unfortunately however, it is direly needed by my small company and because of this I will be awarding the maximum bounty for a good solution.
We have a set of legacy order information stored in a .txt file. In order to import this order information into our new custom database system, we need to, for each row, append on a value from another set.
So, in my .txt file I have :
Trans Date,NorthTotal,NorthSoFar,SouthTotal,SouthSoFar,IsNorthWorkingDay,IsSouthWorkingDay
2012-01-01,21,0,21,0,0,0
2012-01-02,21,0,21,0,0,0
2012-01-03,21,1,21,1,1,1
...
Now, I have a set of locations in a .txt file also, for which I need to add two columns - city and country. Let's say :
City, Country
London,England
Paris,France
For each row in my first text file, I need to append on a row of my second text file! So, for my end result, using my sample data above, I wish to have :
Trans Date,NorthTotal,NorthSoFar,SouthTotal,SouthSoFar,IsNorthWorkingDay,IsSouthWorkingDay,City,Country
2012-01-01,21,0,21,0,0,0,London,England
2012-01-02,21,0,21,0,0,0,London,England
2012-01-03,21,1,21,1,1,1,London,England
2012-01-01,21,0,21,0,0,0,Paris,France
2012-01-02,21,0,21,0,0,0,Paris,France
2012-01-03,21,1,21,1,1,1,Paris,France
...
At the moment my only idea for this is to import both files into an SQL database and write a complicated function to append the two together (hence my tag) - surely someone can save me and think of something that will not take all day though! Please?! Thank you very much.
Edit : I am open to solutions written in all programming languages; but would prefer something which uses DOS or some kind of console/program that can be easily reran!
If you are open to using a database and importing these files (which should not be very difficult), then you do not need a "complicated function to append the two together". All you need is a simple cross join like this ... select t1.*, t2.* from t1, t2
See for yourself at... http://sqlfiddle.com/#!2/0c584/1
Here is a solution in C#. You run it like:
joinfiles a.txt b.txt c.txt
where a.txt is the first file, b.txt the second one, and c.txt the output file that will be created. It generates the output at 100 MB/s on my machine so that is probably fast enough.
using System;
using System.IO;
using System.Text;
namespace JoinFiles
{
class Program
{
static void Main(string[] args)
{
if (args.Length != 3)
return;
string[] file1, file2;
try
{
using (var sr1 = new StreamReader(args[0]))
using (var sr2 = new StreamReader(args[1]))
{
file1 = sr1.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
file2 = sr2.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
}
using (var outstream = new StreamWriter(args[2], false, Encoding.Default, 1048576))
{
outstream.WriteLine(file1[0] + "," + file2[0]);
for (int i = 1; i < file2.Length; i++)
for (int j = 1; j < file1.Length; j++)
outstream.WriteLine(file1[j] + "," + file2[i]);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
bash script example
echo -e 'c1\na\nb' > t1
echo -e 'c2\n1\n2' > t2
while read l1;do
read -u 3 l2
echo "$l1,$l2"
done <t1 3<t2
see man bash / internal function / read
You could also write a WSH script to do this and execute from the command line. Here is a quick hack (works but will certainly need some refining). You'll need to save this as a vbs file and execute on the cli like this... wscript script.vbs infile1.txt infile2.txt outfile.txt where script.vbs is your script and infile 1 and 2 are input filenames and outfile.txt is the output file.
Set FSO_In1 = CreateObject("Scripting.FileSystemObject")
Set FSO_In2 = CreateObject("Scripting.FileSystemObject")
Set FSO_Out = CreateObject("Scripting.FileSystemObject")
Set File_Out = FSO_In1.CreateTextFile(Wscript.Arguments.Item(2),2)
Set F1_file = FSO_In1.OpenTextFile(Wscript.Arguments.Item(0),1)
HeaderWritten = False
Header = F1_File.Readline 'Read the first header line from first file
Do While F1_File.AtEndOfStream = False
F1_Line = F1_file.Readline
Set F2_File = FSO_In2.OpenTextFile(Wscript.Arguments.Item(1),1)
if HeaderWritten = False then
Header = Header & "," & F2_File.Readline
File_Out.Writeline(Header)
HeaderWritten = True
else
F2_File.Readline 'Read the first header line from second file and ignore it
end if
Do While F2_File.AtEndOfStream = False
F2_Line = F2_File.Readline
out = F1_Line & "," & F2_Line
File_Out.Writeline(out)
Loop
F2_File.Close
Loop
F1_File.Close
File_Out.Close

Perl script to export sql query to csv

The code below works, but all of the data displays in one row(but different columns) when opened in Excel. The query SHOULD display the data headings, row 1, and row 2. Also, when I open the file, I get a warning that says "The file you are trying to open,'xxxx.csv', is in a different format than specified by the file extension. Verify that the file is not corrupted...etc. Do you want to open the file now?" Anyway to fix that? That may be the cause too.
tldr; export to csv with multiple rows - not just one. fix Excel error. Thanks!
#!/usr/bin/perl
use warnings;
use DBI;
use Text::CSV;
# local time variables
($sec,$min,$hr,$mday,$mon,$year) = localtime(time);
$mon++;
$year += 1900;
# set name of database to connect to
$database=MDLSDB1;
# connection to the database
my $dbh = DBI->connect("dbi:Oracle:$database", "", "")
or die "Can't make database connect: $DBI::errstr\n";
# some settings that you usually want for oracle 10
$dbh->{LongReadLen} = 65535;
$dbh->{PrintError} = 0;
# sql statement to run
$sql="select * from eg.well where rownum < 3";
my $sth = $dbh->prepare($sql);
$sth->execute();
my $csv = Text::CSV->new ( { binary => 1 } )
or die "Cannot use CSV: ".Text::CSV->error_diag ();
open my $fh, ">:raw", "results-$year-$mon-$mday-$hr.$min.$sec.csv";
$csv->print($fh, $sth->{NAME});
while(my $row = $sth->fetchrow_arrayref){
$csv->print($fh, $row);
}
close $fh or die "Failed to write CSV: $!";
while(my $row = $sth->fetchrow_arrayref){
$csv->print($fh, $row);
$csv->print($fh, "\n");
}
CSV rows are delimited by newlines. Just simply add a newline after each row.
I think another solution is to use the instantiation of the Text::CSV object and pass along the desired line termination there...
my $csv = Text::CSV->new ( { binary => 1 } )
or die "Cannot use CSV: " . Text::CSV->error_diag();
becomes:
my $csv = Text::CSV->new({ binary => 1, eol => "\r\n" })
or die "Cannot use CSV: " . Text::CSV->error_diag();