I've made a simple script that allows users to upload html files to a web directory on my server. However, I'd like it so each file is deleted after 24 hours of being on my server. 24 hours for each file, not 24 hours for the entire directory. Here is my code so far... Thank you for your help. :)
<?php
$target = "users/";
$target = $target . basename( $_FILES['uploaded']['name']) ;
$ok=1;
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)
&& ($_FILES["uploaded"]["type"] == "html"))
{
echo "File: " . $_FILES["uploaded"]["name"] . "<br />";
echo "Type: " . $_FILES["uploaded"]["type"] . "<br />";
echo "Size: " . ($_FILES["uploaded"]["size"] / 1024) . " Kb<br />";
echo "Location: /users/" . $_FILES["uploaded"]["name"];
}
else {
echo "Sorry, " . $_FILES["uploaded"]["name"] . " is not a valid HTML document. Please try again.";
unlink . $_FILES["uploaded"]["name"];
}
?>
Use Cron to execute this script every 10 minutes (better 30 or 60)
$Time=time();
foreach(glob('/users/*') as $file){
if(filemtime($file)+60*60*24<$Time){
unlink($file);
}
}
Not fullproof, but it gives an idea..
foreach(glob("/users/YOUR_USER/*") as $file) {
$file = "/users/YOUR_USER/".$file;
if ((time() - filectime($file)) >= 86400) {
// delete me
}
}
If you're using a Windows server then run a batch file using Windows Scheduler:
Batch file to delete files older than N days
Otherwise, just set up a CRON job.
Include following script at the end of your script. Don't forget to replace /var/www/uploads/ with correct path. Other wise all files will be removed in different place.
$files=shell_exec('find /var/www/uploads/ -mmin +1440');
$file = explode("\n",$files);
if(isset($file) && is_array($file))
{
foreach($file as $val)
{
#unlink($val);
}
}
The above code will work on Linux/UNIX based hosting.
"shell_exec" will execute linux command and return the out put
"find -mmin -1440" is looking for files older than 1 day or 1440
minutes
First line "/var/www/uploads/" path need to be replaced with full
path of the directory.
Unlink have "#" sign to avoid warning if the file not exists there.
As this is powerful linux based command verify the paths correctly.
Related
I am trying to execute a PHP script using crontab but it doesn't seem to work. I am running AWS EC2 Linux and here is the PHP script:
FOREACH (GLOB("*.jpg") AS $filename) {
ECHO "$filename size " . FILESIZE($filename) . "\n";
UNLINK($filename);
}
FOREACH (GLOB("*.jpeg") AS $filename) {
ECHO "$filename size " . FILESIZE($filename) . "\n";
UNLINK($filename);
}
FOREACH (GLOB("*.gif") AS $filename) {
ECHO "$filename size " . FILESIZE($filename) . "\n";
UNLINK($filename);
}
FOREACH (GLOB("*.png") AS $filename) {
ECHO "$filename size " . FILESIZE($filename) . "\n";
UNLINK($filename);
}
When I execute this script manually from a browser, it works normally. But it doesn't work using crontab
Here is my cron command:
00 * * * * php /var/www/html/*****/*****/delete.php
And here is the log:
Nov 28 02:12:01 ip-##-##-##-## CROND[#####]: (root) CMD (/usr/bin/php
/var/www/html/*****/*****/delete.php)
What am I possibly doing wrong?
I just had a similar issue...
Cron is setup correct (I think) but is not running
It is now working for me:
edit /etc/crontab directly and be sure to check your paths.
(You can even cd into the correct directory like this, perhaps that will solve your issue too..)
00 * * * * cd /var/www/html/*****/*****/ && php ./delete.php
Also check if just php will do the trick.
call:
which php
to see the full path of PHP and use that instead.
If it is working fine in browser then you can set the cron job as below,
00 * * * * wget -q -O /dev/null http://example.com/delete.php
this will work same like you calling in browser just change the "http://example.com/delete.php" with the url which you call in browser.
I want to synchronize files between two servers.
The idea is to check if a file exists on the "local" server and if true, check if it the same as a remote server. If not, the update it.
If it doesn't exist, add it.
The code seems to work but always one file is changed, even when it hasn't and its a different one each time.
Is there an error or what is the reason?
if (file_exists($img)) {
$image_hashfile_remote = sha1_file($image_url[$urlIndex]);
$image_hashfile_local = sha1_file($img);
if ($image_hashfile_local == $image_hashfile_remote) {
$num_same++;
} else {
file_put_contents($img, file_get_contents($image_url[$urlIndex]));
echo "Image file as changed since last synchronization. " .$img . " updated. <br />";
echo $image_hashfile_local . " " .$image_hashfile_remote . "<br />";
$num_saved++;
}
} else {
file_put_contents($img, file_get_contents($image_url[$urlIndex]));
echo "New image file found. " . $img . " added. <br />";
$num_saved++;
}
I've gone through some of the questions, but haven't found an answer to my question so here it goes.
I've written a stereotypical script for uploading small files. The script works, and the file is uploaded to the server. However, I can't get it to upload it to move to the right subfolder.
<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " MB<br>";
}
if (file_exists("/enhstudios/clients/media/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"/enhstudios/clients/media/" . $_FILES["file"]["name"]);
}
?>
The error I get is:
Warning: move_uploaded_file(/enhstudios/clients/july.jpg) [function.move-uploaded-file]: failed to open stream: No such file or directory in /hermes/waloraweb013/b1311/moo.enhstudios/enhstudios/clients/fileuploadcode.php on line 20
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phpkfxGLm' to '/enhstudios/clients/july.jpg' in /hermes/waloraweb013/b1311/moo.enhstudios/enhstudios/clients/fileuploadcode.php on line 20
Permissions for this directory are set at 777.
Where have I gone wrong? I've tried all different combos of subdirectories and still can't get it to upload to the right one.
Are you sure you don't mix the /hermes/waloraweb013/b1311/moo.enhstudios/enhstudios/clients and the /enhstudios/clients/ directories?
I think you would like to move to the longer one, but the second arguments first / makes it an absoulte path.
You can add there the full path, or you can try to remove the first /. (This relativisation works only if the document root is /hermes/waloraweb013/b1311/moo.enhstudios/)
I've built a website with a HTML form/ PHP upload for image files, it works well when its running on XAMPP on my local computer but when i've uploaded it to 000webhost most of the time it says invalid file and only sometimes will the images successfully upload. I've tried turning up the max execution time in the php configuration but that doesn't seem to have fixed it. The files i've tried to upload are smaller than the max file size in the php config and have worked on my test machine perfectly.
I find it odd that it works sometimes and doesn't other times and don't really know what to try.
EDIT:
Here is the form
Filename:
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/png")))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
move_uploaded_file($_FILES["file"]["tmp_name"],
"churchimages/pauls.jpeg");
echo "Stored in: " . "churchimages/pauls.jpeg";
}
}
else
{
echo "Invalid file";//This is the section I am seeing
}
Your file type detection is relying on $_FILES["file"]["type"], which is sent by the browser and highly unreliable.
A much better way to detect whether an uploaded file is an image is getimagesize().
$info = getimagesize($_FILES["file"]["tmp_name"]);
$allowed_types = array(IMG_GIF, IMG_JPEG, IMG_PNG);
if (in_array($info[2], $allowed_types))
{ .... do stuff ... }
You should check if the upload actually succeeded FIRST, before doing any of the other operations:
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
... handle upload...
if (!move_uploaded_file(...)) { // <--important. ALWAYS check if the move worked.
die("File move failed. Data is lost");
}
} else {
die("Upload failed with code " . $_FILES['file']['error']);
}
IN the case where an upload did not occur, then the ['type'] field would not be set, and just saying "invalid file" would be useless - there is no file at all.
As Pekka's pointed out, you should use other methods of determining file type. The ['type'] data in $_FILES is user-provided, and is trivial to forge.
Make sure that you're defining an absolute path for the uploaded files rather than a relative one.
I have had this issue today.. very sad. took about an hour to repair.
Idea: checking for $_FILES["file"]["type"] == "image/gif" at the top of the script is what failed for me. It seems the browser was populating a "BLANK DATA" instead of "image/gif" so my initial check failed each time with "invalid file type"
Question: It seems the browsers are not properly sending across the file type from the tmp directory?
My FIX: remove the file type check.... as stated above it is very unreliable...
Check the PHP file permissions. in ooowebhost you can find it in chmod. change to '777'. otherwise, the file doesn't have permissions to execute/write
I'm uploading files from an iPhone app to PHP using the following code:
<?php
if ($_FILES["media"]["error"] > 0) {
echo "Error: " . $_FILES["media"]["error"] . "<br />";
} else {
echo "Upload: " . $_FILES["media"]["name"];
echo "Type: " . $_FILES["media"]["type"];
echo "Size: " . ($_FILES["media"]["size"] / 1024);
echo "Stored in: " . $_FILES["media"]["tmp_name"];
if (file_exists("uploads/" . $_FILES["media"]["name"])) {
echo $_FILES["media"]["name"] . " already exists. ";
} else {
move_uploaded_file($_FILES["media"]["tmp_name"],
"uploads/" . $_FILES["media"]["name"]);
echo "Stored in: " . "uploads/" . $_FILES["media"]["name"];
}
}
?>
Afterwards, I get the success message saying "uploads/2542543.jpg" - but I can't seem to find where the image is actually stored. Is the filepath relative to the php file (which is in php - and has an uploads folder) or is it absolute from the root??
EDIT: Looks like the file should have ended up in php/uploads/filename.jpg - but it doesn't appear to be making it. I don't quite understand why - anyone have any idea?
This is an absolute path from the root
/uploads/2543.jpg
This is a relative path from your PHP document
uploads/2543.jpg
So you're working with a relative path (note the missing / at the start)
This is defined in php.ini using the upload_tmp_dir directive. If that's not set, it uses the system default, which you can figure out using sys_get_temp_dir. I believe it defaults to /tmp on Linux, and C:\Windows\Temp\ on Windows.