I have this page where you can send message to multiple people and attach files into it...
Here is my code
<?php
session_start();
$inboxfrom = $_SESSION['loginusername'];
$inboxto = $_POST['inboxto'];
$inboxsubject = $_POST['inboxsubject'];
$inboxcontent = $_POST['inboxcontent'];
$inboxtime = date('g:i A', time()+(6*60*60));
$inboxdate = date('Y-m-d', time()+(6*60*60));
mysql_connect("127.0.0.1", "root", "")or die("Cannot Connect toDb");
mysql_select_db("Abbot_db");
$count = 0;
function generateRandomString($length = 8){
$string = "";
$possible = "0123456789bcdfghjkmnpqrstvwxyz"; //character that can be used
for($i=0;$i < $length;$i++){
$char = substr($possible, rand(0, strlen($possible)-1), 1);
if (!strstr($string, $char)){
$string .= $char;
}
}
return $string;
}
if (count($inboxto) != 0){
$count = 0;
while ($count < count($inboxto)){
$recepient = $_POST['inboxto'][$count];
mysql_query("INSERT INTO Inbox_tbl(InboxTo, InboxFrom, InboxSubject, InboxContent, InboxTime, InboxDate,InboxStatus,ToDelete,FromDelete)VALUES ('$recepient','$inboxfrom','$inboxsubject','$inboxcontent','$inboxtime','$inboxdate','Unread','No','No')");
$recepient_result = mysql_query("SELECT * FROM Accounts_tbl WHERE UserID='$recepient'");
if (mysql_result($recepient_result, 0, "UserTypeID") == 1){
$notiurl = "LMSadmin_inbox.php";
} else if (mysql_result($recepient_result, 0, "UserTypeID") == 2) {
$notiurl = "LMSteacher_inbox.php";
} else {
$notiurl = "LMSstud_inbox.php";
}
mysql_query("INSERT INTO Noti_tbl(NotiTo,NotiFrom,NotiContent,NotiDate,NotiTime,NotiType,NotiUrl)
VALUES('$recepient','$inboxfrom','has sent you a message','$inboxdate','$inboxtime','Message','$notiurl')");
//---------------------------------------------------------
$countto = 0;
$cont = generateRandomString(128);
$folder = "./Attachments/".$cont;
$name = $_FILES['file']['name'];
if (!empty($name)){
while (is_dir($folder)){
$cont = generateRandomString(128);
$folder = "./Attachments/".$cont;
}
mkdir($folder, 0700, true);
}
while ($countto < count($_FILES['file']['name'])){
$name = $_FILES['file']['name'][$countto];
$type = $_FILES['file']['type'][$countto];
$tmp_name = $_FILES['file']['tmp_name'][$countto];
$folder = "Attachments/".$cont."/";
move_uploaded_file($tmp_name, $folder.$name);
$fileurl = $cont."/".$name;
$dummypost = mysql_query("SELECT * FROM Inbox_tbl ORDER BY InboxID DESC");
$msgid = mysql_result($dummypost, 0, "InboxID");
mysql_query("INSERT INTO Attachments_tbl(FileUrl,FileName,AttachType,AttachID)
VALUES('$fileurl','$name','Message',$msgid)");
$countto++;
}
//----------------------------------------------
$count++;
}
}
header('Location: ' . $_SERVER['HTTP_REFERER']);
?>
now the result after I put multiple recepients and multiples is that... The first recepient will get the attachments.. meaning the folder of attachment will be randomy generated and the files would be put in there.... but on the next recepient the attachments would not be moved on their respective folder.. I can see the folder have been made but the files arent moved..
MY question is.. does the "temp_name" disappear after you use the "move_uploaded_file" code? Because I think thats is the reason the files arent not move.. Is so can you suggest any alternate code i can use?
move_uploaded_file() relocates the file to the set target location with rendering the tmp_name useless afterwards.
What you should do is to create a "puffer" folder where you originally move the uploaded file, and then call copy() as many times as you need to deliver the file to the recipient folders. When the file is put to every needed location, you can unlink() the file from this puffer folder.
Alternatively, you might put the file to only one location (to eliminate redundancy and overuse of storage space), and make links in your Attachments_tbl to this same file in a set attachments folder. However, this needs remodelling of how your system works to make sure that the (now one and only) attachment file is only removed after every record pointing to it is removed also.
Yes, the file is moved, this is why you can't find it. I suggest that you:
Move the inner while loop (the one for the uploaded files) before the first while loop (for the recipients), and move the uploaded files to a location that you specify
Create a new inner while loop that copies the files from the location you specified earlier to each user's attachments folder
Related
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 want to allow users to upload images without conflicting problems that may be caused by multiple users uploading images that potentially have the same image name. I am stumped on how to execute this and I have no idea where to start..
Here is my code:
if(isset($_POST['submitimage'])){
move_uploaded_file($_FILES['file']['tmp_name'],"pictures/".$_FILES['file']['name']);
$con = mysqli_connect("localhost","root","","database");
$q = mysqli_query($con,"UPDATE users SET image = '".$_FILES['file']['name']."' WHERE user_id = '".$_SESSION['user']."'");
header("Location: index.php");
}
?>
Any help would be amazing. Thank you!
My solution is to generate a random string for each uploaded file, i.e.:
<?php
if(!empty($_POST['submitimage'])){
//get file extension.
$ext = pathinfo($_FILES['file']['name'])['extension'];
//generate the new random string for filename and append extension.
$nFn = generateRandomString().".$ext";
move_uploaded_file($_FILES['file']['tmp_name'],"pictures/".$nFn);
$con = mysqli_connect("localhost","root","","database");
$q = mysqli_query($con,"UPDATE users SET image = '{$nFn}' WHERE user_id = '{$_SESSION['user']}'");
header("Location: index.php");
}
function generateRandomString($length = 10) {
return substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), 0, $length);
}
?>
PHP has a build in function to generate unique files on your server. This function is known as tempnam(). If you read the comments on that website carefully though, there is a small chance you'll get unwanted behaviour from that function if to many processes call it at the same time. So a modification to this function would be as follows:
<?php
function tempnam_sfx($path, $suffix){
do {
$file = $path."/".mt_rand().$suffix;
$fp = #fopen($file, 'x');
}
while(!$fp);
fclose($fp);
return $file;
}
?>
Because the file is kept open while it's being created, it can't be accessed by another process and therefor it's impossible to ever create 2 files with the same name simply because a couple of your website visitors happened to upload pictures at the exact same moment. So to implement this in your own code:
<?php
function tempnam_sfx($path, $suffix){
do {
$file = $path."/".mt_rand().$suffix;
$fp = #fopen($file, 'x');
}
while(!$fp);
fclose($fp);
return $file;
}
$uploaddir = 'pictures'; // Upload directory
$file = $_FILES['file']['name']; // Original file
$ext = pathinfo($path, PATHINFO_EXTENSION); // Get file extension
$uploadfile = tempnam_sfx($uploaddir, $ext);
move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile);
$con = mysqli_connect("localhost","root","","database");
$q = mysqli_query($con,"UPDATE users SET image = '".basename($uploadfile)."' WHERE user_id = '{$_SESSION['user']}'");
header("Location: index.php");
?>
One way you could do this, is by generating a few random numbers (and possibly attaching them to current date in number format) and give the image the number sequence.
if(isset($_POST['submitimage'])){
//generate 3 sequences of random numbers,you could do more or less if you wish
$randomNumber=rand().rand().rand();
move_uploaded_file($_FILES['file']['tmp_name'],"pictures/".$randomNumber."jpg");
$con = mysqli_connect("localhost","root","","database");
$q = mysqli_query($con,"UPDATE users SET image = '".$randomNumber.".jpg' WHERE user_id = '".$_SESSION['user']."'");
header("Location: index.php");
}
?>
Note : you could also look into generating random strings if numbers are not your thing.
I am writing an application in PHP where the user submits a form of data and a file name is chosen based off of the data, like so:
$filename = "./savelocation/".$name."_".$identification."_".$date.'.txt';
I am trying to use the file_exists() function to check to see if a file with the same name exists. If it does, the final name is changed to prevent overwriting the submitted form data. Here is my implementation:
$file = "./savelocation/".$name."_".$identification."_".$date.'.txt';
$file = preg_replace('/\s+/', '', $file);
$filepath = "./savelocation/".$name."_".$identification."_".$date.'.txt';
if(file_exists($filepath))
{
$file = "./savelocation/"."INVALIDFILE".'.txt';
}
This prevents people from overwriting applications by changing the name to a single file which acts as the 'default file' in which it doesn't matter if it is overwritten. However, I know this is wrong. My logic was that the if statement would return true, which would execute the code inside of the statement changing the file name to the 'default file'. Is this even a good way to prevent duplicate submissions?
Try this...if there is a match on the file name, break from the loop and redirect
$userFile = $name."_".$identification."_".$date.'.txt;
$fileArray = glob('./savelocation/*');
$arrCount = count($fileArray);
$i = 1;
$msg = null;
foreach ($fileArray as $FA) {
$fileSubstring = str_replace("\.\/savelocation\/", "", $FA);
if ($i > $arrCount) {
break;
} else if ($userFile === $fileSubstring) {
$msg = 'repeat';
break;
} else null;
$i++;
}
if (isset($msg)) header('location: PageThatChastisesUser.php');
Alternatively, if you tweak your code a bit to change your file name, this should work:
if(file_exists($file)) {
$file = str_replace("\.txt", "duplicate\.txt", $file);
}
Change the file name in a way that identifies itself to you as a duplicate.
Here's one way of doing it:
$file = "./savelocation/".$name."_".$identification."_".$date.'.txt';
$file = preg_replace('/\s+/', '', $filen);
$filepath = "./savelocation/".$name."_".$identification."_".$date.'.txt';
$i = 1;
while(file_exists($filepath))
{
$filepath = "./savelocation/".$name."_".$identification."_".$date.'_'.$i.'.txt';
$i++;
}
Thank you in advance. I've checked similar questions and they are not helping because the work flow is set up differently.
Trying to get working:
1.user uploads image via form field
2.(SCRIPT 1) on other page script assigns unique name (SCRIPT 2), saves image file to server and image URL is uploaded to SQL. Goes to new page at end of script.
Problem is I'm not getting errors, the script runs and the new page opens but there is no file saved on the server and no data inserted into the SQL table (the entry date adds but not the image URL). My PHP.ini instructions far exceeds the size of the images I've been testing with. The folder location is chamode 0777. I'm posting the whole script because with getting errors it's hard to see where problem lies.
Image processing
<?php
require_once 'unique_gen.php';
$page_path = $_POST['page_path'];
$imgloc = "/avatars/";
//up one directory level
$store_loc = "..".$imgloc;
$link_loc = "http://www.webapge.com".$imgloc;
//Upload and characterize image file
if(isset($_FILES['image'])){
//File
$upload['image'] = $_FILES['image'];
//Verify
if ($upload['image']["error"] > 0){
die ("File Upload Error: " . $upload['image']["error"]);
}else{
//Upload
$img_ext = end(explode('.', $upload['image']['name']));
//Unique code generator
$image_name = implode('.', array(unique_generator(),$img_ext));
while(file_exists($store_loc.$image_name)){
$image_name = implode('.', array(unique_generator(),$img_ext));
}
$image_name = $upload['image']['name'];
//Move file to another location
move_uploaded_file($upload['image']["tmp_name"],$store_loc.$image_name) or exit("<br>Error, IMAGE file not moved!");
//Save location as link
$link_to_img = $link_loc.$image_name;
}
}else{
$image_name = "";
}
//connect to db
$con=mysqli_connect("localhost","usernm","pssword","dbName");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Insert to SQL
$sql="INSERT INTO comments (avatar, entry_date)
VALUES
('$_POST[link_to_image]', now())";
//verify insert
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
//direct to new page using variable
header('Location: http://www.weBsite.com/' . $page_path);
//close session
mysqli_close($con);
?>
Unique generator
<?php
function unique_generator($lot_size = 15){
$alpha_s = range('a', 'z');
$alpha_l = range('A', 'Z');
$numbers = range(0, 9);
$char = array_merge($alpha_l,$alpha_s,$numbers);
$code = "";
for($i = 0; $i < $lot_size; $i++){
$key = rand(0,count($char)-1);
$code .= $char[$key];
}
return $code;
}
?>
Try putting this at the top of your script:
<?php
error_reporting(E_ALL);
ini_set('display_errors','1');
?>
This at the bottom:
<?php
print_r(array_keys(get_defined_vars()));
print_r(array_values(get_defined_vars()));
?>
So I am creating trying to create a PHP script where the client can create a folder with a 10 digit name of random letters and numbers, and than save the document they are currently working on into that folder. Its like a JSfiddle where you can save what you are currently working on and it makes a random folder. My issue is that it wont create my directory, and the idea is correct, and it should work. However, PHP isn't saving an Error Log so I cannot identify the issue. Here's what I got so far.
PHP
save_functions.php
<?php
function genRandomString() {
$length = 10;
$characters = "0123456789abcdefghijklmnopqrstuvwxyz";
$string = '';
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters))];
}
return $string;
}
<?php
function createFolder() {
$folderName = genRandomString(); //Make a random name for the folder
$goTo = '../$folderName';//Path to folder
while(is_dir($goTo)==true){ //Check if a folder with that name exists
$folderName = genRandomString();
$goTo = '../$folderName';
}
mkdir($goTo,7777); //Make a directory with that name at $goTo
return $goTo; //Return the path to the folder
}
?>
create_files.php
<?php
include('save_functions.php');//Include those functions
$doc = $_POST['doc'];//Get contents of the file
$folder = createFolder();//Make the folder with that random name
$docName = '$folder/style.css';//Create the css file
$dh = fopen($docName, 'w+') or die("can't open file");//Open or create the file
fwrite($dh, $doc);//Overwrite contents of the file
fclose($dh);//Close handler
?>
The call to mkdir($goTo,7777) has wrong mode, this is usually octal and not decimal or hex. 7777 is 017141 in octal and thus tries to set non-existent bits. Try the usual 0777.
But why don't you just use tempnam() or tmpfile() in your case?