I have a directory called 'files' that contains folders that represent upload space for a user, e.g. files/14 where '14' is the UserID of a user.
I am trying to create a simple script that when files are uploaded, the script:
Checks if the User's folder already exists
If user folder doesn't exist create one with the UserID, else ignore and continue
Upload files to the newly created directory (e.g. 14) or upload in previously created user directory.
This is the code:
<?php
include("dbConfig.php");
$Username = $_SESSION["username"];
global $userid;
$Password = $_SESSION["password"];
$Password = md5($Password);
$sql = "SELECT UserID FROM users WHERE Username = '".$Username."'";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
$userid = $row['UserID'];
}
$dirname = (string)$userid;
$filename = ("$dirname" . "/");
if (!file_exists("../files/" .$filename)) {
mkdir("files/$dirname", 0775);
} else {
if (isset($_FILES['files'])) {
echo "<div id='files_table'><table class='center'.><tr><td>";
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name) {
$dest = ($filename . "{$_FILES['files']['name'][$key]}");
move_uploaded_file($tmp_name, $dest );
echo $_FILES['files']['name'][$key], " uploaded.", "<br>";
}
}
}
?>
The files are being uploaded into the root directory (../files), although the User Directory is being created.
Also, the warning is not being ignored, giving me this error:
**Warning: mkdir(): File exists in C:\xampp\htdocs\Task2PHP\final\upload.php on line 80**
Can anyone help me and tell me how to fix this?
How about using the same structure for both calls?
For example:
if (!file_exists("../files/" .$filename)) {
mkdir("../files/" .$filename, 0775);
You seem to be checking that one file/folder exists on one hand and create another one somewhere else since ../files != files/
Also navnav is right you should stop using relative paths. Garanteed problems down the road. Especially if you use some framework and url rewrinting.
Related
this is my code
<?php
include 'koneksi.php';
$judul_artikel = $_POST['judul_artikel'];
$isi_artikel = $_POST['isi_artikel'];
$tanggal_artikel = date('Y-m-d');
$tag_artikel = $_POST['tag_artikel'];
$filetmp = $_FILES["gambar_artikel"]["tmp_name"];
$filename = $_FILES["gambar_artikel"]["name"];
$filetype = $_FILES["gambar_artikel"]["type"];
$filepath = "img/".$filename;
move_uploaded_file($filetmp, $filepath);
$query = mysql_query('INSERT INTO artikel(judul_artikel,isi_artikel,tanggal_artikel,tag_artikel,gambar_artikel) VALUES ("'.$judul_artikel.'","'.$isi_artikel.'","'.$tanggal_artikel.'","'.$tag_artikel.'","'.$filepath.'")')or die(mysql_error());
if ($query) {
header('location:artikel.php?notif=berhasil');
} else {
header('location:artikel.php?notif=gagal');
}
?>
the problem I face is, I want to copy the image file to another directory after I upload it, and input it into the mysql database too, but when I execute, the file that I upload is not copied in the directory that I want, and is not inputted into the mysql database, how to handle it ?
try to wrap it inside if condition like this
if(move_uploaded_file($filetmp, $filepath)){
echo "success";
}else{
echo "failed";
}
and make sure you set the folder permission
I've seen questions similar to this but no one seems to have the problem I do.
I've set up a process to check to see if the filename already exists in a MySQL table, and if it does, it puts a timestamp between the filename and the extension (E.G. Test.PDF becomes Test-19:25:36 if it's a duplicate), thus negating any database conflicts.
My issue is that the while the database is updated correctly, the duplicate file isn't uploaded with the timestamp in the name. Instead, it uses the duplicate name and just overwrites the original and creates a ghost "filename" listing in the database.
I've seen you can use move_uploaded_file to rename files in the servers memory before they're uploaded, but I've tried multiple ways and can't get it to rename the file in memory BEFORE attempting to write it to the "/uploads" folder. Here's the upload code:
<?php
include_once 'dbconnect.php';
//check if form is submitted
if (isset($_POST['submit'])) {
// START OF PRE-EXISTING FILE CHECK
$filename = $_FILES['file1']['name'];
$dupeCheck = "SELECT * FROM tbl_files WHERE filename = '$filename'";
if ($output = mysqli_query($con, $dupeCheck)) {
if (mysqli_num_rows($output) > 0) {
$fileArray = pathinfo($filename);
$timeStamp = "-" . date("H:i:s");
$filename = $fileArray['filename'] . $timeStamp . "." . $fileArray['extension'];
}
}
// END OF PRE-EXISTING FILE CHECK
if($filename != '')
{
$trueCheck = true;
if ($trueCheck == true) {
$sql = 'select max(id) as id from tbl_files';
$result = mysqli_query($con, $sql);
//set target directory
$path = 'uploads/';
$created = #date('Y-m-d H-i-s');
$moveTargetVar = "uploads/" . $filename;
move_uploaded_file($_FILES['file1']['tmp_name'], $moveTargetVar);
// insert file details into database
$sql = "INSERT INTO tbl_files(filename, created) VALUES('$filename', '$created')";
mysqli_query($con, $sql);
header("Location: index.php?st=success");
}
else
{
header("Location: index.php?st=error");
}
}
else
header("Location: index.php");
}
?>
Any advice on how to rename a file before it's written to the uploads folder?
I'd suggest not using : to separate your time stamp, because that will cause issue with file name restrictions. Try doing something like:
$timeStamp = "-" . date("H-i-s");
Solved by replacing move_uploaded_file($_FILES['file1']['tmp_name'], $moveTargetVar); with move_uploaded_file($_FILES['file1']['tmp_name'],$path . $filename);
Deprecated $moveTargetVar = "uploads/" . $filename;
I save the path to my images in my database. To delete these images, I get the path from the database.
This worked fine, until I added two folders to the path.
So far the path in my database looked like this (working!):
/var/www/myproject/public/images/550d744bd91d16.7869
Now, it looks like this (not working!): /var/www/myproject/public/images/5/profile/550d744bd91d16.7869
My Code
$folder_name = /var/www/myproject/public/images/ . $_GET['user_id'] . '/';
$profile_folder = $folder_name . 'profile/';
chmod($folder_name, 0777);
chmod($profile_folder, 0777);
// Get the images file path
$database = DatabaseFactory::getFactory()->getConnection();
$query = $database->prepare("SELECT image_path FROM images WHERE image_id = :image_id AND user_id = :user_id LIMIT 1");
$query->execute(array(':image_id' => $image_id, ':user_id' => Session::get('user_id')));
$img_path = $query->fetch();
// Convert array to string
$path = $img_path->image_path;
$file = $path . '.jpg';
if (file_exists($file)) {
// Delete the image file on the server
unlink($file);
} else {
echo 'An error occured';
return false;
}
What I tried so far
The path is definitely correct. I triple checked in the database and outputted the variable multiple times.
Therefore, I thought it must be the directory permissions, however, I added the permissions to the code and nothing changed.
I am not getting any error message and I would be beyond thankful for any kind of help with this!
Summary
file_exists(unlink($file)) returns FALSE.
unlink($file) returns TRUE.
The file permissions:
images drwxrwxrwx
5 drwxrwxrwx
profile drwxrwxrwx
image.jpg -rwxrwxrwx
I have to delete a file from the database and also to delete the file from the folder which is stored in server as files(folder)/newsletter(subfolder)/file1 using php.Iam using following code,the file is deleting from the database,but its not deleting from the folder,..plz help,thanks in advance.
my code is..
<?php
$id = intval($_REQUEST['id']);
include 'db/connection.php';
$sql1 = mysql_query("select * from newsletters where id=$id");
$results = mysql_fetch_array($sql);
if ($results["file"] != "") {
$image = $results["file"];
unlink('../files/newsletter/' . $image);
}
$sql = "delete from newsletters where id=$id";
$result = #mysql_query($sql);
if ($result) {
echo json_encode(array('success' => true));
} else {
echo json_encode(array('msg' => 'Some errors occured.'));
}
?>
Take care of this path "../files/newsletter/" should mention correct path and if your server is ubuntu based then change permissions to files ,newsletter folders.
Ive made the following script to display files from a directory if user is signed in:
<?php
session_start();
require_once("path/file.php");
if (!empty($_SESSION[username]))
{echo "You <b>$_SESSION[username]</b> are registered.";
$dirPath = dir('includes/path/');
$docArray = array();
while (($file = $dirPath->read()) !== false)
{
if ((substr($file, -3)=="pdf") || (substr($file, -3)=="doc"))
{
$docArray[ ] = trim($file);
}
}
$dirPath->close();
sort($docArray);
$c = count($docArray);
foreach($docArray as $filename)
{
echo "<div>Download '$filename'</div>";
echo "<br/>";
}
include('logout.php');
}
else
{echo "somethingsomething";
include('login.php');
}
?>
In the members table there are two columns MSV and LTP with possible values 0, 1. Also I have to directories /path/LTP and /path/MSV.
I would need an addition to the script that if a user has privileges to LTP or/and MSV, the files would be displayed accordingly.
You will need stored into $_SESSION the value of the fields LTP and MSV and try somethig like this in the php file that your are using to read those folder
read LTP folder
if(!empty($_SESSION[LTP])){
//code to read LTP folder
}else{
//Cannot read LTP folder
}
read MSV folder
if(!empty($_SESSION[MSV])){
//code to read MSV folder
}else{
//Cannot read MSV folder
}
Assuming 0 is deny acces and 1 is grant permission to read
Query your database for the user, and build in logic after you fetch your row.
$username = mysqli_real_escape_string($con, $_SESSION['username']);
$query = "SELECT `LTP`, `MSV` FROM `members` WHERE `username`='".$username."'";
$data = mysqli_query($con, $query) or die(mysqli_error($con));
$row = mysqli_fetch_array($data);
if ($row['MSV'] == '1') {
//provide access to MSV files here.
}
if ($row['LTP'] == '1') {
//provide access to LTP files here.
}
Note that the die statement is for debugging and is not graceful enough for production use.