I have a system that allows user to upload PDF files and save the name of the file on the database.
How can I make this script works so user can delete all files from server whose name is not in my database?
This is what I actually have, but the script deletes all files. I don't know how to proceed.
<?php
include 'fimg.class.php';
require('../../../php/cone.php');
//header('Location: ../produccion.php');
$directory = "upload/";
//get all image files with a .jpg extension.
$images = glob($directory . "*");
foreach($images as $image)
{
$name = explode('_',$image);
$name = 'photos/' . $name[0];
$sql = mysql_query("SELECT imagen FROM r_alumnos");
if(mysql_num_rows($sql) == 0)
unlink($image);
}
?>
You could create something like a maintenance-script which handels this.
First, load everything in an array (I personally don't like the multiple queries execute):
$database_files = array();
$result_db_files = mysqli_query("SELECT imagen FROM r_alumnos");
while ($row = $result_db_files->fetch_assoc())
{
$database_files[] = $row['imagen'];
}
Then check each file:
$images = glob($directory . "*");
foreach($images as $image)
{
$name = explode('_',$image);
$name = 'photos/' . $name[0];
if (!in_array($name, $database_files))
{
unlink($image);
}
}
Related
I'm trying to create a file upload only my current script doesn't seem to work as I believe it should.
I've managed to get the data saved in the MySQL table okay but I can't seem to get the file into the 'uploads' directory?
if(isset($_POST['new']) && $_POST['new']==1){
$folder = "uploads/";
$upload_image = $folder . basename($_FILES["image1"]["name"]);
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $upload_image);
$trn_date = date("Y-m-d H:i:s");
$brand =$_REQUEST['brand'];
$user =$_SESSION["username"];
$model = $_REQUEST['model'];
$serial =$_REQUEST['serial'];
$purchasedate = $_REQUEST['purchasedate'];
$img1 =$_REQUEST['image1'];
$ins_query="insert into table
(`user`,`trn_date`,`brand`,`model`,`serial`,`purchasedate`,`image1`)values
('$user','$trn_date','$brand','$model','$serial','$purchasedate','$img1')";
mysqli_query($con,$ins_query)
or die(mysql_error());
$status = "added successfully.
</br></br><a href='home.php'>home</a>";
}
$upload_image = $folder . basename($_FILES["image1"]["name"]);
move_uploaded_file($_FILES["image1"]["tmp_name"], $upload_image);
What if trying directly what the doc said ;)
$uploads_dir = '/uploads';//try over 'uploads' too or create a 'uploads' folder in you app_root
foreach ($_FILES["image1"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["image1"]["tmp_name"][$key];
$name = $_FILES["image1"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
Possible Link
I have found an issue in your code.
$folder = "uploads/";
$upload_image = $folder . basename($_FILES["image1"]["name"]);
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $upload_image);
In this case the file does not have the extension
$folder = "uploads/";
$ext = explode('.', basename( $_FILES['image1']['name']));
$upload_image = $folder . basename($_FILES["image1"]["name"].$ext);
move_uploaded_file($_FILES["image1"]["tmp_name"], $upload_image);
The uploads folder is in the same directory that is the php script?
You also can verify if the file was correctly moved doing the following test
if (file_exists($upload_image)){
echo "true";
}
Provide a file upload validation before uploading into server it will prevent server from malicious files
How to give file validation in php : Link
I am using this bellow php to check the the kind of file saved in database, but it show everything as folder please i don't know what the problem is.
<?php
$path = dirname(__FILE__);
$sub_folder = scandir($path);
$num = count($sub_folder);
//$jailchillink This is the name of file saved in database replaced width index.php
if(is_file($path.'\\'.index.php)){ $codetype = 'file';}
else if(is_img($path.'\\'.index.php)){ $codetype = 'image';}
else{ $codetype = 'folder';}?>
The above code will output folder
<?php
$path = dirname(__FILE__);
$sub_folder = scandir($path);
$num = count($sub_folder);
//$jailchillink This is the name of file saved in database replaced width index.php
if(is_file($path.'\\'.'index.php')){
echo $codetype = 'file';
}else if(is_img($path.'\\'.'index.php')){
echo $codetype = 'image';
}else{
echo $codetype = 'folder';
}
?>
Now the output is file. just add ' around index.php.
I am currently able to perform an upload of multiple images and then inserting the file paths into a row in the database. Ideally I need to find a way to upload these files paths as separate entries with their own ID. The reason why is because the image paths I am inserting are to be bound to a task which is inserted into a separate table.
function upload_file_new_task(){
global $db;
if(isset($_POST['create'])) {
$path = "../uploads/";
for ($i=0; $i<count($_FILES['files']['name']); $i++) {
$ext = explode('.', basename( $_FILES['files']['name'][$i]));
$path = $path . md5(uniqid()) . "." . $ext[count($ext)-1];
move_uploaded_file($_FILES['files']['tmp_name'][$i], $path);
}
$sql = "INSERT INTO upload_data (`image`) VALUES ('$path');";
$res = mysqli_query($db,$sql);
echo "<p>Post Created $date</p>";
}
}
So theimage is uploaded into the /uploads folder, the path is then loaded into the database as a single row with an id in the ID field and the path(s) are loaded into the image field.
Something like
function upload_file_new_task()
{
global $db;
if(isset($_POST['create']))
{
$path = "../uploads/";
for ($i=0; $i<count($_FILES['files']['name']); $i++)
{
$ext = pathinfo($_FILES['files']['name'][$i], PATHINFO_EXTENSION);
$path1 = $path . md5(uniqid()) . "." . $ext;
move_uploaded_file($_FILES['files']['tmp_name'][$i], $path1);
$sql = "INSERT INTO upload_data (`image`) VALUES ('$path1');";
$res = mysqli_query($db,$sql);
}
echo "<p>Post Created $date</p>";
}
}
Good Day. I have a php script that move multiple file in my directory..
$filepath = 'uploads/';
if (isset($_FILES['file'])) {
$file_id = $_POST['file_id'];
$count = 0;
foreach($_FILES['file']['tmp_name'] as $k => $tmp_name){
$name = $_FILES['file']['name'][$k];
$size = $_FILES['file']['size'][$k];
if (strlen($name)) {
$extension = substr($name, strrpos($name, '.')+1);
if (in_array(strtolower($extension), $file_formats)) { // check it if it's a valid format or not
if ($size < (2048 * 1024)) { // check it if it's bigger than 2 mb or no
$filename = uniqid()."-00000-". $name;=
$tmp = $_FILES['file']['tmp_name'][$k];
if (move_uploaded_file($tmp_name, $filepath . $filename)) {
$id = $file_id;
$file_path_array = array();
$files_path = $filepath . $filename;
$file_extension = $extension;
foreach($file_name as $k_file_path => $v_file_path){
$file_path_array[] = $v_file_path;
}
foreach($file_extension as $k_file_extension){
$file_extension_array[] = $v_file_extension;
}
$file_path = json_encode($files_path);
$file_name = str_replace("\/", "/",$file_path);
var_dump($file_name);
$update = $mysqli->query("UPDATE detail SET file_path='$file_name' WHERE id='$id'");
} else {
echo "Could not move the file.";
}
} else {
echo "Your file is more than 2MB.";
}
} else {
echo "Invalid file format PLEASE CHECK YOU FILE EXTENSION.";
}
} else {
echo "Please select FILE";
}
}
exit();
}
this is my php script that move file to 'uploads/' directory and i want to save the path to my database. i try to dump the $file_name and this is my example path how to save that to my database.. ? any suggestions ?
NOTE: i already move the file to uploads/ directory and i only want to save the path to my database
string(46) "uploads/5638067602b48-00000-samplePDF.pdf"
string(46) "uploads/5638067602dee-00000-samplePDF1.pdf"
string(46) "uploads/5638067602f8d-00000-samplePDF2.pdf"
if you must store them in one field..
inside the loop
$file_name_for_db[]=$file_name;
outside the loop:
$update = $mysqli->query("UPDATE detail SET file_path='".json_encode($file_name_for_db)."' WHERE id='$id'");
there is serialize() instead of json_encode() if you prefer
I am trying to get images from while loop and split them up at the period (.).. and then change the name of the image to ImageName + -resized. But I can not seem to figure out how to do this. Any help would be greatly appreciated!
So in short I have this: image.jpg and I want to create this image-resized.jpg: Here is my code:
<?php
$f = $_GET['f'];
$h = $_GET['h'];
$gp = $_GET['gp'];
//Create folder path
$path = "Fotos/".$f."/".$h."/".$gp."/";
//Get pictures from database
$getfolders = mysql_query("SELECT FolderName, Files FROM Files WHERE FolderDate = '$f' AND FolderHour = '$h' AND FolderName = '$gp'") or die(mysql_error());
//List pictures from database
while($row = mysql_fetch_array($getfolders)){
$img = $row['Files'];
//Seperate image at period(.)
$image = explode('.', $img);
//Get image name ----------------Here is where I need help!!
for($i = 0; $i < sizeof($image); $i++)
{
$imag = $image[$i];
}
?>
<div class="picture" id="pic"><img src="<?php echo $path; echo $imag ?>" alt="picture" /><?php echo $img?></div>
<?php
}
?>
Well, the simplest solution would be:
$image = explode('.', $img);
$extension = array_pop($image);
$resizedFileName = implode('.', $image) . "-resized.{$extension}";
But this solution does assume, that there are only simple extensions:
image.jpg => image-resized.jpg // ok
image.tar.gz => image.tar-resized.gz // not so ok
But if there are only simple extensions, this solution might be sufficient.
A better solution would be using SplFileInfo:
$fi = new SplFileInfo($image);
$resizedFileName = $fi->getBasename("." . $fi->getExtension()) . "-resized." . $fi->getExtension();
SplFileInfo::getExtensions() is available since PHP 5.3.6