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.
Related
I want to upload 1000 images in just one click via URL. I have 1000 Image URLs stored in MYSQL database.
So please any one give me PHP code to upload that 1000 images via URL through mysql database.
Currently I am using the bellow code:-
It upload one image per click by posting URL of image...
But i want to upload 1000 image in one click by getting URLs from databse
$result = mysql_query("SELECT * FROM thumb") or die(mysql_error());
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
echo "<div>";
$oid = $row['tid'];
$th= $row['q'];
echo "</div>";
$thi = $th;
$get_url = $post["url"];
$url = trim('$get_url');
if($url){
$file = fopen($url,"rb");
$directory = "thumbnail/";
$valid_exts = array("php","jpeg","gif","png","doc","docx","jpg","html","asp","xml","JPEG","bmp");
$ext = end(explode(".",strtolower(basename($url))));
if(in_array($ext,$valid_exts)){
$filename = "$oid.$ext";
$newfile = fopen($directory . $filename, "wb");
if($newfile){
while(!feof($file)){
fwrite($newfile,fread($file,1024 * 8),1024 * 8);
}
echo 'File uploaded successfully';
echo '**$$**'.$filename;
}
else{
echo 'File does not exists';
}
}
else{
echo 'Invalid URL';
}
}
else{
echo 'Please enter the URL';
}
}
Thanks a lot.... …
The code you have is outdated and a lot more complex than needed. This is not a site where you get code because you ask, this is a learning environment.
I'll give you an example on which you can continue:
// Select the images (those we haven't done yet):
$sItems = mysql_query("SELECT id,url FROM thumb WHERE imported=0") or die(mysql_error());
// Loop through them:
while( $fItems = mysql_fetch_assoc($sItems) ){
$imgSource = file_get_contents($fItems['url']); // get the image
// Check if it didn't go wrong:
if( $imgSource!==false ){
// Which directory to put the file in:
$newLocation = $_SERVER['DOCUMENT_ROOT']."/Location/to/dir/";
// The name of the file:
$newFilename = basename($fItems['url'], $imgSource);
// Save on your server:
file_put_content($newLocation.$newFilename);
}
// Update the row in the DB. If something goes wrong, you don't have to do all of them again:
mysql_query("UPDATE thumb SET imported=1 WHERE id=".$fItems['id']." LIMIT 1") or die(mysql_error());
}
Relevant functions:
file_get_contents() - Get the content of the image
file_put_contents() - Place the content given in this function in a file specified
basename() - given an url, it gives you the filename only
Important:
You are using mysql_query. This is deprecated (should no longer be used), use PDO or mysqli instead
I suggest you make this work from the commandline and add an echo after the update so you can monitor progress
Prior to this link:What is the best way to store media files on a database?
The answer stated:
(
Every system I know of that stores large numbers of big files stores them externally to the database. You store all of the queryable data for the file (title, artist, length, etc) in the database, along with a partial path to the file. When it's time to retrieve the file, you extract the file's path, prepend some file root (or URL) to it, and return that.
)
My questions are:
a)How do you store the partial path of the file?
b)How do you extract the file's path?
c)How do you prepend some file root and return it?
(Sorry I am very new and this bit I don't quite get. Any input or examples would be lovely.)
Btw, these are my codes for uploading the file, I just don't know the retrieve bit.
<?php
if(isset($_FILES['uploaded_file'])) {
if($_FILES['uploaded_file']['error'] == 0) {
// Connect to the database
$dbLink = new mysqli('localhost', 'root', '', 'spellingbee');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Gather all required data
$name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']);
$location = $dbLink->real_escape_string($_FILES['uploaded_file']['location']);
$data = $dbLink->real_escape_string(file_get_contents($_FILES ['uploaded_file']['tmp_name']));
$size = intval($_FILES['uploaded_file']['size']);
// Create the SQL query
$query = "
INSERT INTO `file` (
`name`, `location`, `size`, `data`, `created`
)
VALUES (
'{$name}', '{$location}', {$size}, '{$data}', NOW()
)";
// Execute the query
$result = $dbLink->query($query);
// Check if it was successfull
if($result) {
echo 'Success! Your file was successfully added!';
}
else {
echo 'Error! Failed to insert the file'
. "<pre>{$dbLink->error}</pre>";
}
}
else {
echo 'An error accured while the file was being uploaded. '
. 'Error code: '. intval($_FILES['uploaded_file']['error']);
}
// Close the mysql connection
$dbLink->close();
}
else {
echo 'Error! A file was not sent!';
}
// Echo a link back to the main page
echo '<p>Click here to go back</p>';
?>
As far as I understand your problem you want to upload a audio file and save its name to database and then You want to retrieve it.
To do so just after your all validations (I am writing this code as if want to create a directory)
if(is_dir("audio")
{}
else
{mkdir("audio");}
$path = "http://www.domain.com/audio/".$_FILES['file']['name']; //prepend any path
// insert in database
move_uploaded_file($_FILES['file']['tmp_name'],$path);
And to retrive it:
just fetch the value of path from database.
Fetch From DB:
$q = mysql_query("select * from tablename");
while($r = mysql_fetch_array($q))
{
$path = $r['columnNameofPathinDatabase'];
echo $path;
}
I have to migrate a legacy database up to MySQL using PHP. One of the components of the old system is a large (>1000) list of attached files (mostly .pdf, some are .doc/.docx).
I have so far done the following:
created mysql table, with a blob to contain the file (this method has
been chosen for valid reasons)
imported all the data except the attachments
extracted all the attachments into a folder, naming each file with a unique name
added and populated in mysql a column containing the unique name of the attachment
created a file containing the full names of all the attachments in the folder.
To add a single file is the only solution that I found in stack
But my requirement is to RECURSIVELY go through the list of filenames and find the matching row in mysql, then insert the file from the folder into the blob
example ...
I have a text file with entries like this (filename, date created, size)..
024048DE44C-RUE_MA.pdf,05/24/2013,80233
024048DE44C-RUE.pdf,06/21/2013,85151
... (1000 more)
I have a file with name 024048DE44C-RUE_MA.pdf in the folder
I have a row column filename containing 024048DE44C-RUE_MA.pdf in mysql database
I think the solution is something like this, but need help in the middle bit.
$myfile = fopen("filelist.txt", "r") or die("Unable to open file!");
while(!feof($myfile)) {
$attfile =fgets($myfile);
...upload the file
// Check if a file has been uploaded
if(isset($_FILES['uploaded_file'])) {
// Make sure the file was sent without errors
if($_FILES['uploaded_file']['error'] == 0) {
// Connect to the database
$dbLink = new mysqli('localhost', 'root', '', 'dbase');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Gather all required data
$name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']);
$mime = $dbLink->real_escape_string($_FILES['uploaded_file']['type']);
$data = $dbLink->real_escape_string(file_get_contents($_FILES ['uploaded_file']['tmp_name']));
$size = intval($_FILES['uploaded_file']['size']);
// Create the SQL query
$query = "
INSERT INTO `deal_attachment` (
`deal_att_name`, `deal_att_mime`, `deal_att_size`, `deal_att_content`, `deal_att_created`
)
VALUES (
'{$name}', '{$mime}', {$size}, '{$data}', NOW()
)";
// Execute the query
$result = $dbLink->query($query);
// Check if it was successfull
if($result) {
echo 'Success! Your file was successfully added!';
}
else {
echo 'Error! Failed to insert the file'
. "<pre>{$dbLink->error}</pre>";
}
}
else {
echo 'An error accured while the file was being uploaded. '
. 'Error code: '. intval($_FILES['uploaded_file']['error']);
}
// Close the mysql connection
$dbLink->close();
}
else {
echo 'Error! A file was not sent!';
}
}
fclose($myfile);
Why don't you just use mysql LOAD_FILE function if you already have a table with the filename?
UPDATE mytable SET blobdata=LOAD_FILE(concat("/path/to/", filename));
Your files need to be on your mysql server in order for it to work.
If your only problem is how to read the CSV file you can do:
list($filename,$date, $size)=explode(",", $attfile);
Adam's suggestion worked perfectly for me with the important proviso in Windows that file path must contain double backslashes (so you would construct it like this
$path = 'c:\\dir\\subdir\\' . trim($filename) ;.
Following snippet of code shows the call ..
$query = "UPDATE `attachments` SET `att_content`=LOAD_FILE('" .$path . "') WHERE `att_name` = '" . $filename ."'" ;
$result = mysqli_query($dbcon,$query) ;
// Check if it was successful (maybe add some more insurance by going back to the database to see if the file is there - it can be that no error was reported but LOAD_FILE didn't work (like if the path is invalid)
if (false === $result) {
echo mysqli_error($dbcon);
die ;
} else { echo 'Success! Your file was successfully added!'; }
I have some problems during the upload of file on windows store application. I got Status 200, but when I check the server there's no file uploaded..I'm using apache server
I've checked the Sample of Microsoft Background Transfer sample but it work with a ASP .Net server.
any solution ?
I need to upload one single file at a time, It works for me, let me know:
upload.php:
<?php
$target = "data/";
$target = $target . basename( $_FILES['Filename']['name']) ;
if(move_uploaded_file($_FILES['Filename']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['Filename']['name']). " has been uploaded";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
?>
C# code:
private async void StartMultipartUpload_Click(object sender, RoutedEventArgs e)
{
Uri uri;
if (!Uri.TryCreate(serverAddressField.Text.Trim(), UriKind.Absolute, out uri))
{
rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage);
return;
}
// Verify that we are currently not snapped, or that we can unsnap to open the picker.
if (ApplicationView.Value == ApplicationViewState.Snapped && !ApplicationView.TryUnsnap())
{
rootPage.NotifyUser("File picker cannot be opened in snapped mode. Please unsnap first.", NotifyType.ErrorMessage);
return;
}
FileOpenPicker picker = new FileOpenPicker();
picker.FileTypeFilter.Add("*");
IReadOnlyList<StorageFile> files = await picker.PickMultipleFilesAsync();
if (files.Count == 0)
{
rootPage.NotifyUser("No file selected.", NotifyType.ErrorMessage);
return;
}
List<BackgroundTransferContentPart> parts = new List<BackgroundTransferContentPart>();
for (int i = 0; i < files.Count; i++)
{
BackgroundTransferContentPart part = new BackgroundTransferContentPart("Filename", files[i].Name);
part.SetFile(files[i]);
parts.Add(part);
}
BackgroundUploader uploader = new BackgroundUploader();
UploadOperation upload = await uploader.CreateUploadAsync(uri, parts);
String fileNames = files[0].Name;
for (int i = 1; i < files.Count; i++)
{
fileNames += ", " + files[i].Name;
}
Log(String.Format("Uploading {0} to {1}, {2}", fileNames, uri.AbsoluteUri, upload.Guid));
// Attach progress and completion handlers.
await HandleUploadAsync(upload, true);
}
I used the same code of The SDK sample. data/ folder is in the same folder of upload.php and my Uri is http://mySite/myApp/upload.php
Ok so I found a full solution. Basically you need to upload as multipart on your SDK Samples ( doesn't matter if it is C# or C++ ) and the key is to the php file. Here is my PHP file that processes all of the selected files. Works as a charm! Also if you get error 1 it means that in your php.ini the maximum file upload size is too small! So look out for that too. Hope it helps, it surely took me some effort to get this done.
<?php
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
foreach ($_FILES as $name) {
if ($_FILES[$name]["error"] > 0){
fwrite($fh, "Error: " . $_FILES[$name]['error'] . " on file: " . $_FILES[$name]['name']); // log the error
}
$target = "data/";
$target = $target . basename( $_FILES[$name]['name']) ;
if(move_uploaded_file($_FILES[$name]['tmp_name'], $target))
{
echo "The file ". basename( $_FILES[$name]['name']). " has been uploaded"; // succes, do whatever you want
}
else {
fwrite($fh, "File movement error on file: " . $_FILES[$name]['name']); // log the error
}
}
fclose($fh);
?>
$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;