$f="../mts/sites/default/files/test.doc";//in this way i am able to find line count,but i am not getting how i can give folder path for line counting..if i give path as $safe_filename and $target_path.$safe_filename it's coming file content not opening. Please check the code and help me out thanks in advance
<?php
$nid = 1;
$teaser = false;
// Load node
$node = node_load(array('nid' => $nid));
// Prepare its output
if (node_hook($node, 'view')) {
node_invoke($node, 'view', $teaser, false);
}
else {
$node = node_prepare($node, $teaser);
}
// Allow modules to change content before viewing.
node_invoke_nodeapi($node, 'view', $teaser, false);
// Print
print $teaser ? $node->teaser : $node->body;
$target_path = "../mts/sites/default/files/ourfiles/";
//$myfile = basename( $_FILES['uploadedfile']['name']);
$safe_filename = preg_replace(
array("/\s+/", "/[^-\.\w]+/"),
array("_", ""),
trim($_FILES['uploadedfile']['name']));
$target_path = $target_path.$safe_filename;
if(file_exists($target_path))
{
echo "<script language=\"javascript\">";
echo "window.alert ('File already exist');";
echo "//--></script>";
}
elseif(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "<script language=\"javascript\">";
echo "window.alert ('File uploaded succesfully');";
echo "//--></script>";
/*
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
*/
}
$con = mysql_connect("localhost","mts","mts");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Create table
mysql_select_db("mts", $con);
$f="../mts/sites/default/files/test.doc";//in this way i am able to find line count,but i am not getting how i can give folder path for line counting
// count words
$numWords = str_word_count($str)/11;
echo "This file have ". $numWords . " words";
echo "This file have ". $numWords . " lines";
mysql_query("INSERT INTO mt_upload (FileName,linecount, FilePath,DateTime)
VALUES ('".$safe_filename."','".$numWords."', '".$target_path.$safe_filename."',NOW())");
// Execute query
mysql_query($sql,$con);
mysql_close($con);
?>
emphasized text
This is not a very safe way of doing things. If two users submitted files with the same filename, they would overwrite each other. This limits the user to a unique filename, which after a while of running a system becomes a problem. Not to mention that the user would be quite puzzled if he ever got such a message.
A much better solution is to generate your own filename for every file. You could make a long random string, or maybe take the mysql_insert_id() for the inserted record in mt_upload table. Then you would also not need to mess around with regexps, and the whole thing would be much simpler. In the mt_upload table you can keep the old filename if you want to show it to the user or something.
If that's the exact code, then the problem is that you call str_word_count() on $str but don't appear to set $str anywhere.
Function to count lines in all the files residing in a certain directory
function linecount_dir($dir) {
$ig = array('.','..');
$d = dir($dir);
while (false !== ($entry = $d->read())) {
if (!in_array($entry,$ig)) {
$total += linecount($d->path . "/$entry");
}
}
$d->close();
return $total;
}
Function to count lines
define(BLOCK_SIZE,131072);
function linecount($filename) {
$f = fopen($filename,'r');
while (!feof($f)) {
$d = fread($f,BLOCK_SIZE);
$rcount += substr_count($d, "\n");
$ncount += substr_count($d, "\r");
}
fclose($f);
return (($rcount >= $ncount) ? $rcount : $ncount);
}
Applied to your code
$f="../mts/sites/default/files/test.doc";//in this way i am able to find line count,but i am not getting how i can give folder path for line counting
// count words
$numWords = str_word_count($str)/11;
// count lines
$numLines = linecount($f);
echo "This file have ". $numWords . " words";
echo "This file have ". $numLines . " lines";
$f="../mts/sites/default/files/".$safe_filename;
Related
I'm trying to upload the file's path into my database. But nothing is being inserted. My file gets uploaded to target directory successfully. I want to insert the path too, but can't do it. I believe I'm doing some mistake in the Insert Into statement. Please let me know what's wrong?
My upload.php code is below:
<?php
// variables
$conn = mysqli_connect('localhost','root','abcdef','trademark');
if(!$conn) {
echo "Not Connected To Server";
}
else {
define('UPLOAD_DIR', 'uploads/');
$fileName = $_FILES['file'];
// check for which action should be taken if file already exist
//Rename file name
if(file_exists(UPLOAD_DIR . $fileName['name']))
{
$updatedFileName = update_file_name(UPLOAD_DIR.$fileName['name']);
move_uploaded_file($fileName['tmp_name'], $updatedFileName);
echo"FILE SUCCESSFULLY UPLOADED!! " . "<br/><br/><br/>"; //after renaming
}
// If no such file already exists, then upload it as it is
else
{
move_uploaded_file($fileName['tmp_name'], UPLOAD_DIR.$fileName['name']);
echo " FILE SUCCESSFULLY UPLOADED!! ". "<br/><br/>";
}
// function to rename file
function update_file_name($file)
{
$pos = strrpos($file,'.');
$ext = substr($file,$pos);
$dir = strrpos($file,'/');
$dr = substr($file,0,($dir+1));
$arr = explode('/',$file);
$fName = trim($arr[(count($arr) - 1)],$ext);
$exist = FALSE;
$i = 2;
while(!$exist)
{
$file = $dr.$fName.'_'.$i.$ext;
if(!file_exists($file))
$exist = TRUE;
$i++;
}
return $file;
} // function to rename ends
$sql = "INSERT INTO file (Path) VALUES (' " . mysqli_real_escape_string( UPLOAD_DIR.$fileName['name']) . " ')";
$r = mysqli_query($conn,$sql);
echo 'file info inserted';
}
?>
Check syntax for function mysqli_real_escape_string
getting warning message as,
Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1
given in
I'm having trouble with a foreach loop from a text file. I have a directory tree, and a list of these directories is in a text file, I want to check the tree against the list, and echo if any directories are missing.
The problem that I'm having is that I can't see an account for a new line, so if the file has 1 line, then it returns that it exists, but if the file has two line it returns the first as missing and the second as existing, even if it's the same entry twice in the file - see code below for clarification
<?php
$logFile = 'LogFile.txt';
$rootDirectory = 'C:\testdir\\';
$verificationFile = 'verificationfiles/directoryverification.txt';
$verificationContents = file($verificationFile);
$fh = fopen($logFile,'a') or die("can't open file");
$new_line = "\r\n";
foreach($verificationContents as $directoryName) {
$subDirectory = $rootDirectory.$directoryName;
echo "$subDirectory <br />";
if (file_exists($subDirectory)) {
echo "$subDirectory Exists <br />";
} else {
echo "$subDirectory Does Not Exist <br />";
$libverificationfailed = 'failed';
fwrite($fh, "$subDirectory Not Found");
fwrite($fh, $new_line);
}
}
?>
So, as an example, the root directory has 2 sub directories, subdir1 and subdir2.
directoryverification.txt
subdir1
subdir2
and the page echos
C:\testdir\subdir1
C:\testdir\subdir1 Does Not Exist
C:\testdir\subdir2
C:\testdir\subdir2 Exists
So if there is a new line after the data in the text file, the code isn't reading it correctly. I'm hoping that this makes sense and that somebody can help.
regards,
Thanks rickdenhaan,
$subDirectory = rtrim($subDirectory);
Just before the if statement sorted it.
Try this
$rootDirectory = 'C:\testdir\\';
$verificationFile = 'verificationfiles/directoryverification.txt';
$file = new \SplFileObject($verificationFile, 'r');
$file->setFlags(\SplFileObject::SKIP_EMPTY);
while ( $dirname = $file->fgets() )
{
$dirname = $rootDirectory . trim($dirname);
if ( !file_exists($dirname) )
{
echo sprintf("direcrory %s does not exist\n", $dirname);
continue;
}
echo sprintf("direcrory %s exists\n", $dirname);
}
I wondered if there were a way to check if the filename exists and then to add a number after it, I know this - in a basic for is possible so if someone does it once it'll add 1 after it.
But how would you get it to check if someone has done it more than once? So the first time it would add a 1 then a 2 then a 3 and so on?
$title = $_POST['title'];
$content = $_POST['content'];
$compile = $title. "\r\n" .$content;
$content = $compile;
$path = "../data/" .md5($title). ".txt";
$fp = fopen($path,"wb");
fwrite($fp,$content);
fclose($fp);
$con=new mysqli("###","###_public","###","###");
if (!($stmt = $con->prepare("INSERT INTO `blog_posts` (`post_title`,`post_content`,`post_date`) VALUES (?,?,?)")) || !is_object($stmt)) {
die( "Error preparing: (" .$con->errno . ") " . $con->error);
}
$stmt->bind_param('sss', $_POST['title'], $path, $_POST['date']);
if($stmt->execute()) {
echo "Successfully Posted";
} else {
echo "Unsuccessfully Posted";
}
$stmt->close();
Thanks for any help in advance
The general idea would be like this:
$basefilename = "somefile";
$filename = $basefilename;
$i = 0;
while(file_exists("../data/".$filename.".txt") $filename = $basefilename.(++$i);
Adapt as needed.
You can use something like this:
<?php
if(file_exists($filename)) { // check if the file exists in the first place
$i = 1;
while(file_exists($filename.$i)) { // check if the filename with the index exists. If so, increase the $i by 1 and try again
$i++;
}
rename($filename, $filename.$i); // rename the actual file
} else {
// file did not exist in the first place
}
Do not add strings at the end of file name - you would eventually
hit the OS file name length limit pretty soon. You would also fail
to recognize the last added number, when the string gets too big -
you'd have to parse all the numbers from the beginning.
Use glob() to search for a file name.
Parse the file names found for the number at the end and increment
that number.
Use rename() on the file name and check the return status to
avoid racing conditions.
Generally avoid that - use a database or any other system that
supports atomic operations.
I wrote a very simple web form that allows my user to view text files from within their Internet browser.
Occasionally, the search criteria entered returns more than one file. So I want to implement a feature whereby the text files returned by the search are compressed into a ZIP.
I got a prototype working but it only compresses the first file. The second or third files are ignored.
Here's my code
<HTML><body><form name="myform" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<fieldset><label for="DBRIDs">RIDs</label><input type="text" id="DBRIDs" name="DBRIDs" >
</fieldset></form></body></HTML>
<?php
function check_search() {
if (isset($_POST['submit'])) {if (!empty($_POST['DBRIDs'])) { $results = getFiles(); }
} else $errors = "Please enter something before you hit SUBMIT.";
return Array($results, $errors);
}
function getFiles() {
$result = null;
$ZIPresult = null;
if (empty($_POST['DBRIDs'])) { return null; }
$mydir = MYDIR;
$dir = opendir($mydir);
$DBRIDs = $_POST['DBRIDs'];
$getfilename = mysql_query("select filename from search_table where rid in (" . $DBRIDs . ")") or die(mysql_error());
while ($row = mysql_fetch_array($getfilename)) {
$filename = $row['filename'];
$result .= '<tr><td>' . $filename . '</td></tr>';
$ZIPresult .= basename($mydir) . '/' . $filename;
}
if ($result) {
$result = "<table><tbody><tr><td>Search Results.</td></tr> $result</table>";
shell_exec("zip -9 SearchResult.zip ". $ZIPresult ." > /dev/null ");
} return $result;
}
The hyperlinks pointing to the file(s) are generated just fine. The ZIP file however only contains the first file listed in the results.
How can I get the ZIP file to capture ALL the files returned??
Thanks for your input.
PS: The new ZipArchive() library/class is not available on our production environment so I chose to use the Unix utility ZIP instead.
There are a number of issues here (security, for one, as it appears that you're not sanitizing your DB inputs), but I'm guess the issue is around the $ZIPresult variable. It doesn't appear (unless I'm missing something) that you have any spaces between your file names, so the shell_exec call is trying to zip "file1.extfile2.extfile3.ext". See what happens if you modify this line:
$ZIPresult .= basename($mydir) . '/' . $filename.' ';
I am new to PHP and Javascript.
I am uploading files that after 15 days need to be deleted automatically from the database. Please can anyone help me out.
I am using following code for uploading:
<?php
$nid = 1;
$teaser = false;
// Load node
$node = node_load(array('nid' => $nid));
// Prepare its output
if (node_hook($node, 'view')) {
node_invoke($node, 'view', $teaser, false);
}
else {
$node = node_prepare($node, $teaser);
}
// Allow modules to change content before viewing.
node_invoke_nodeapi($node, 'view', $teaser, false);
// Print
print $teaser ? $node->teaser : $node->body;
$target_path = "../mts/sites/default/files/ourfiles/";
//$myfile = basename( $_FILES['uploadedfile']['name']);
$safe_filename = preg_replace(
array("/\s+/", "/[^-\.\w]+/"),
array("_", ""),
trim($_FILES['uploadedfile']['name']));
$target_path = $target_path.$safe_filename;
if(file_exists($target_path))
{
echo "<script language=\"javascript\">";
echo "window.alert ('File already exist')";
echo "//--></script>";
}
elseif(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "<script language=\"javascript\">";
echo "window.alert ('File uploaded succesfully');";
echo "//--></script>";
/*
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
*/
}
$con = mysql_connect("localhost","mts","mts");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Create table
mysql_select_db("mts", $con);
$ut=date("y-m-d # h:i:s");
mysql_query("INSERT INTO mt_upload (FileName, FilePath,DateTime)
VALUES ('".$safe_filename."', '".$target_path.$safe_filename."',NOW())");
// Execute query
mysql_query($sql,$con);
mysql_close($con);
?>
Since you're using mysql, you'd want to create a PHP script that would connect to your database and delete everything older than 15 days.
*nix: Use a tool like cron to run that script every X hours, where X is a reasonable number for your operation.
Windows: Use a scheduled task to run that script every X hours, where X is a reasonable number for your operation.
Option called Cron job.
Check it in your server.
Set a time duration in the server. Which server checks for time and process the function that you have set.
Automatically the it wont delete the records. You have to initiate an event.