Delete and update file if 1 day old - php

I'm writing a code in PHP which deletes a file if it's more than a day old.
but i t does not do so, and append line after it :(
$fileName = 'news/'.$_COOKIE['sign'];
if (isset($_COOKIE['sign']))
{
if ((file_exists($fileName)) && (date("d",filemtime($fileName))==date("d")))
{
$data = file_get_contents($fileName);
if ($data == '')
{
$data = 'Temporary network problem !';
unlink($fileName);
}
echo $data;
}
else
echo 'Fetch and put new news';

$fileName = 'news/'.$_COOKIE['sign'];
if (isset($_COOKIE['sign'])) {
if ((file_exists($fileName)) && (date("d", filemtime($fileName)) == date("d"))) {
$data = file_get_contents($fileName);
if ($data == '') {
$data = 'Temporary network problem !';
unlink($fileName);
}
echo $data;
}
elseif(file_exists($fileName)) { //if not above, then delete it!
unlink($fileName);
}
else {
echo 'Fetch and put new news';
}
}

Related

How to rename zipped filename?

So i have code to move from 1 dir to another dir file and make that file zipped.
That i need:
Rename zipped filename to second "-" symbol.
Example: i got zipped filename "SOMETEXT-de_dust2-20123323.dem.zip". I need that filename to be only "SOMETEXT.dem.zip"
So just remove all text until second -"-"
Any suggestion?
Thanks for helping me to understand code :)
My CODE:
<?php
//error_reporting(E_ALL);
//set_time_limit(0);
$path = "MIX1/cstrike";
$path2 = "/var/www/html/public/";
$to_dirs = array('/demos/');
$from_dirs = array('/demos/');
$filesizes = array();
//первый проход запоминаем размеры
foreach($from_dirs as $from_dir)
{
$demos_dir = opendir($path.$from_dir);
while (false!==($file=readdir($demos_dir)))
{
if ($file!='.'&&$file!='..'&&strpos($file,'.dem')!==false)
{
$fsize=filesize($path.$from_dir.$file);
if ($fsize<50000000)
{
$filesizes[$file]=$fsize;
}
else{
// echo "<br/>bad file:",$file, ", size = ", $fsize;
}
}
}
closedir($demos_dir);
}
//echo date("h:i:s");
sleep(3);
clearstatcache ();
//второй проход пермещаем
$i=0;
foreach($from_dirs as $from_dir)
{
$to_dir=$from_dirs[$i];
$demos_dir = opendir($path.$from_dir);
while (false!==($file=readdir($demos_dir)))
{
if ($file!='.'&&$file!='..'&&strpos($file,'.dem')!==false)
{
$fsize=0;
$fsize=filesize($path.$from_dir.$file);
if ($fsize<50000000)
{
if ($fsize==$filesizes[$file])
{
//echo "<br>ѕеремещаем файл ",$file," размер не изменилс¤; было ",$filesizes[$file]," стало, ".$fsize,";";
move_demo($file, $from_dir, $to_dir);
}
else
{
//echo "<br>","размер изменилс¤ у файла ", $file;
}
}
else
{
//echo "<br/>bad file:",$file, ", size = ", $fsize;
}
}
}
$i++;
closedir($demos_dir);
}
function move_demo($filename, $from_dir, $to_dir)
{
//echo $filename,"from ",$from_dir," to ",$to_dir,"<br>";
global $path, $path2;
if (file_exists($path2.$to_dir.$filename.".zip"))
unlink($path2.$to_dir.$filename.".zip");
echo "$path$from_dir$filename\n";
echo "$path2$to_dir$filename\n\n";
$data = file_get_contents($path.$from_dir.$filename);
$gzdata = gzencode($data, 9);
unset($data);
$fp = fopen($path2.$to_dir.$filename.".zip", "xb+");
//$fp = fopen($path.$to_dir.$filename.".zip")
fwrite($fp, $gzdata);
unset($gzdata);
fclose($fp);
unlink($path.$from_dir.$filename);
}
?>
Have a look at rename().
Here's a PoC:
function move_files($src, $dst)
{
$dh = opendir($src);
if (!$dh) {
return false;
}
// Combine the letters before the first dash/hyphen (-),
// and the letters after (and including) the first dot/period (.)
// after the first dash/hyphen (-).
$regex = '/^(.+?)-(?:.+?)(\..+?\.zip)$/';
$moved = 0;
$total = 0;
while (($filename = readdir($dh)) !== false) {
if (filetype("{$src}{$filename}") !== 'file') {
continue;
}
if (!preg_match($regex, $filename)) {
continue;
}
$total++;
$new_filename = preg_replace($regex, "$1$2", $filename);
$moved += (int)rename($src, "{$dst}{$new_filename}");
}
closedir($dh);
return [$moved, $total];
}
$srcDir = '/src/';
$dstDir = '/dst/';
$res = move_files($src, $dst);
if (!$res) {
// Error
}
list($moved, $total) = $res;
var_dump($moved, $total);

File name too long while deleting image in Laravel

I am working on a Laravel project, the code saves the image inside a folder created with the title coming from a post. The problem is that while adding post it does not gives a warning saying filename too long but while deleting the post it says filename too long in demo.php/uploads/filename.php.
Is it really because of long folder name or something else?
The following code is called for deleting the folder while deleting a post.
function rmdir_recursive($dir) {
if (is_array($dir) || is_object($dir))
{
foreach(scandir($dir) as $file) {
if ('.' === $file || '..' === $file) continue;
if (is_dir("$dir/$file")) rmdir_recursive("$dir/$file");
else unlink("$dir/$file");
}
}
if (is_string($dir)) {
rmdir($dir);
}
}
Following the function to add post:
function create()
{
if($_SERVER['REQUEST_METHOD']=="POST")
{
$pid = rand(1000,9000);
$title = $_POST['title'];
$descpt = $_POST['description'];
$push = isset($_POST['send_push']) ? $_POST['send_push'] : "";
$feature_image = array();
$fy = $_POST['fy'];
if(empty($title) || empty($descpt) || empty($fy))
{
array_push($this->errors, MEND_FIELD_ERROR);
return;
}
if(!empty($_FILES['feature_image']['name'][0]))
{
$image = $_FILES['feature_image'];
$allowed_ext = array('jpeg','jpg','png','pdf','docx');
$allowed_size = 20000000;
foreach($image['name'] as $pos=>$image_name)
{
$dir = "./cdn/uploads/notice/".$title;
$tmp = $image['tmp_name'][$pos];
$img_size = $image['size'][$pos];
$img_error = $image['error'][$pos];
$img_ext = explode('.', $image_name);
$img_name = $img_ext[0];
$img_ext = strtolower(end($img_ext));
if(in_array($img_ext, $allowed_ext))
{
if($img_size <= $allowed_size)
{
if(!file_exists($dir))
{
mkdir($dir);
}
$image_new_name = $img_name.'$$'.uniqid('', true).'.'.$img_ext;
$upload_destination = $dir.'/'.$image_new_name;
if(move_uploaded_file($tmp, $upload_destination))
{
array_push($feature_image, $image_new_name);
}
else
{
array_push($this->errors, $img_error);
return;
}
}
}
else
{
array_push($this->errors, $img_ext.' is not an allowed file extension.');
return;
}
}
}
$s_feature_image = json_encode($feature_image, JSON_UNESCAPED_UNICODE);
$statement = $this->db->prepare("INSERT INTO `notice` (`pid`,`title`,`descpt`,`date`,`photo`,`fy`)
VALUES (?,?,?,?,?,?)");
if($statement->execute([$pid,$title,$descpt,DAT, $s_feature_image, $fy]))
{
if($push == "checked")
{
$descpt = strip_tags($descpt);
$tek = array("message"=>$descpt,"title"=>$title);
$tokens = $this->getTokens();
$this->push_notification($tokens,$tek);
}
ExitThis::send_to(URL.'notice?id='.$pid);
}
else
{
array_push($this->errors, DATABASE_ERROR);
return;
}
}
}
Note: The title will be Nepali character.
I don't know this was right but deleting folder if that is not string help me. I did following changes in my code:
function rmdir_recursive($dir) {
if (is_array($dir) || is_object($dir))
{
foreach(scandir($dir) as $file) {
if ('.' === $file || '..' === $file) continue;
if (is_dir("$dir/$file")) rmdir_recursive("$dir/$file");
else unlink("$dir/$file");
}
}
if(!is_string($dir)){
rmdir($dir);
}
}

move_uploaded_file() function doesn't save uploaded file on server

I've been working on a php script which creates a folder and saves posted images in the created folder, the folders get created but the images I aren't saved.
Below is the script:
if (isset($_FILES['images'])) {
mkdir("files/test/".$new."/", 0755, true);
foreach ($_FILES['images']['tmp_name'] as $key => $value) {
if (!(empty($_FILES['images']['tmp_name'][$key]) || $_FILES['images']['tmp_name'][$key] == 'none')) {
$i_slika = 1;
$extenzion = strtolower(end(explode(".", $_FILES['images']['name'][$key])));
$file = "files/nekretnina/".$new."/".$i_slika.".".$extenzion;
while (file_exists($file)) {
$i_slika++;
$file = "files/nekretnina/".$new."/".$i_slika.".".$extenzion;
}
if (!#move_uploaded_file($_FILES['images']['tmp_name'][$key], $file)) {
$err_text = $err_text. 'Error: '.$_FILES['images']['name'][$key].'<br />';
} else {
include_once "thumbz.class.php";
$pic = new thumbz($file);
$pic->dimensionImage("resize",640);
$pic->addParam('l',0);
$pic->render($file);
}
}
}
}
You need to use $_FILES['images']['tmp_name'][$key] instead of $_FILES['slika']['tmp_name'][$key].
You have the wrong index name!
Try Using:
if (isset($_FILES['images'])) {
mkdir("files/test/".$new."/", 0755, true);
foreach ($_FILES['images']['tmp_name'] as $key => $value) {
if (!(empty($_FILES['images']['tmp_name'][$key]) || $_FILES['images']['tmp_name'][$key] == 'none')) {
$i_slika = 1;
$extenzion = strtolower(end(explode(".", $_FILES['images']['name'][$key])));
$file = "files/test/".$new."/".$i_slika.".".$extenzion;
while (file_exists($file)) {
$i_slika++;
$file = "files/test/".$new."/".$i_slika.".".$extenzion;
}
if (!#move_uploaded_file($_FILES['images']['tmp_name'][$key], $file)) {
$err_text = $err_text. 'Error: '.$_FILES['images']['name'][$key].'<br />';
} else {
include_once "thumbz.class.php";
$pic = new thumbz($file);
$pic->dimensionImage("resize",640);
$pic->addParam('l',0);
$pic->render($file);
}
}
}
}

Import csv into database only take one row

i have this code but it only take the first row of my csv file ..I already search the internet but none make me understand since i am very new in php ..i m sorry if this question is a duplicate.
if(isset($_POST["Import"])){
echo $filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0)
{
$file = fopen($filename, "r");
while (($getData = fgetcsv($file, 10000, ",")) !== FALSE)
{
$sql = "INSERT INTO book (book_id,total_book,price,title,author,surname,genre,location) values
('$getData[0]','$getData[1]','$getData[2]','$getData[3]','$getData[4]','$getData[5]','$getData[6]','$getData[7]')";
$result = mysqli_query($con, $sql);
var_dump($sql);die;
// var_dump(mysqli_error_list($con));
// exit();
if(!isset($result))
{
echo "<script type=\"text/javascript\">
alert(\"Invalid File:Please Upload CSV File.\");
window.location = \"bookList.php\"
</script>";
}
else {
echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Imported.\");
window.location = \"bookList.php\"
</script>";
}
}
fclose($file);
}
}
You can try in my way i did this to process user attendance save in database.
here my code below i am giving upload to data save in server/db.
//after form post with file
if (isset($_POST["frmUplaod"])) {
extract($_POST);
$filename = basename($_FILES['attendance_file']['name']);
$targetfolder = 'Attendance/'. $filename .'';
if ($filename != "") {
move_uploaded_file($_FILES['attendance_file']['tmp_name'], $targetfolder);
chmod($targetfolder, 0777);
$msg = "Attendance file succesfully updated";
}
}
after that i process this csv file using this code :
function MakeID($id) {
$refine_id = "";
if (strlen($id) == "1") {
$refine_id = "SUL00" . $id;
} elseif (strlen($id) == "2") {
$refine_id = "SUL0" . $id;
} elseif (strlen($id) == "3") {
$refine_id = "SUL" . $id;
} else {
$refine_id = "SUL".$id;
}
return $refine_id;
}
//336668677
//Read directory
$FileArray = scandir("Attendance");
$i = 0;
$existsdate = array();
foreach ($FileArray as $f) {
$filename = "Attendance/" . $f;
$extensiondebug='';
if(!empty($f))
{
$splitex=explode(".",$f);
$extensiondebug=$splitex[1];
}
if ($extensiondebug == "csv") {
$row = 1;
if (($handle = fopen("Attendance/".$f, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
$terminal_id=1;
$emp_code=MakeID($data['1']);
$pd=split('/',$data[0]);
#$raw_date=$pd[2]."-".$pd[1]."-".$pd[0];
$unixtime=strtotime($raw_date);
$date=date('Y-m-d',$unixtime);
//echo $date."<br>";
if($data['1']!="ID" && $date!="1970-01-01")
{
if($data['6']!="00:00" && $data['6']!="0:00")
{
//echo $data['6']."<br>";
//echo $date;
$time=date('g:i:s',strtotime($data['6']));
//exit();
$res = $con->existsByCondition("attendance_raw", " employee_id='$emp_code' AND date='$date' AND time='$time'");
if ($res <= 0) {
$array = array(
"machine_id" => $terminal_id,
"date" => $date,
"time" => $time,
"employee_id" => $emp_code,
"result" => "1"
);
$con->insert("attendance_raw", $array);
}
}
if($data['7']!="00:00" && $data['7']!="0:00")
{
$time2=date('g:i:s',strtotime($data['7']));
$res = $con->existsByCondition("attendance_raw", " employee_id='$emp_code' AND date='$date' AND time='$time2'");
if ($res <= 0) {
$array = array(
"machine_id" => $terminal_id,
"date" => $date,
"time" => $time2,
"employee_id" => $emp_code,
"result" => "1"
);
$con->insert("attendance_raw", $array);
}
}
}
//echo "<br />\n";
}
fclose($handle);
}
rename($filename, 'read/' . $filename);
echo "file moved to specified directory.";
}
}
I hope this will help you to complete your csv file process.
Thank you all for the help ..I already solve the problem ,the problem in my code is only the delimiter that i used ,i used a wrong delimiter

Saving data in the database in yii2 during file upload action

I have a upload controller where by am also performing saving other data to the database. The file uploading to the folder is okay but saving the other details in the table doesn't happen
controller code
$images = $_FILES['evidence'];
$success = null;
$paths= ['uploads'];
// get file names
$filenames = $images['name'];
// loop and process files
for($i=0; $i < count($filenames); $i++){
//$ext = explode('.', basename($filenames[$i]));
$target = "uploads/cases/evidence".DIRECTORY_SEPARATOR . md5(uniqid()); //. "." . array_pop($ext);
if(move_uploaded_file($images['name'], $target)) {
$success = true;
$paths[] = $target;
} else {
$success = false;
break;
}
echo $success;
}
// check and process based on successful status
if ($success === true) {
$evidence = new Evidence();
$evidence->case_ref=$id;
$evidence->saved_on=date("Y-m-d");
$evidence->save();
$output = [];
} elseif ($success === false) {
$output = ['error'=>'Error while uploading images. Contact the system administrator'];
foreach ($paths as $file) {
unlink($file);
}
} else {
$output = ['error'=>'No files were processed.'];
}
// return a json encoded response for plugin to process successfully
echo json_encode($output);
After doing var_dump($evidence->save()) I get an error of Boolean false
You could have validation errors. Check $errors property
// check and process based on successful status
if ($success === true) {
$evidence = new Evidence();
$evidence->case_ref=$id;
$evidence->saved_on=date("Y-m-d");
$retSave = $evidence->save();
if($retSave == false)
{
var_dump($evidence->errors);
}
$output = [];
}
....

Categories