This is my first question here, I hope I can explain my problem. I have PHP code where I want to upload a PDF file and select a date, then upload it to a folder in my project called "pdfs". Then I want to download it but only until the date I chose at the upload is reached.
My upload doesn't work and I don't know why, here is my code:
<?php
include_once 'headeradmin.php';
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/styleUpload.css">
<title>Umleitung hochladen</title>
</head>
<body>
<div class="container">
<div class="row">
<form action="umleitungen.php" method="post" enctype="multipart/form-data">
<h3>Umleitungen hochladen</h3>
<input type="file" name="fileToUpload" id="fileToUpload" accept="application/pdf"><br>
<p> Datum: <input type="date" name="ablaufdatum"></p> <br>
<button type="submit" name="save">Hochladen</button>
</form>
</div>
</div>
</body>
</html>
<?php
if (isset($_POST['submit'], $_POST['ablaufdatum']) && is_uploaded_file($_FILES['fileToUpload']['tmp_name'])) {
$date = strtotime($_POST['ablaufdatum']);
if (false === $date) {
return;
}
$mimeType = mime_content_type($_FILES['fileToUpload']['tmp_name']);
$allowedFileTypes = ['application/pdf'];
if (!in_array($mimeType, $allowedFileTypes, true)) {
return;
}
$destination = 'pdfs/' . date('Y-m-d', $date) . '_' . time() . '.pdf';
if (!file_exists($destination)) {
if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $destination)) {
echo 'Supi :)';
} else {
echo 'Upload fehlgeschlagen :/';
}
}
}
include_once 'footer.php';```
Check that the web server has permissions to write to the "pdfs/" directory.
I'm stuck with a simple php code, which must move a uploaded file from tmp to a desired location. Please find my code below. I'm not sure where i'm going wrong.
Any help is appreciated.
php code:
<?php
define("UPLOAD_DIR", "/srv/www/wordpress/mywebpage/uploads/");
$scr = $_FILES["jb_cv"]["tmp_name"];
$desttmp = $_FILES["jb_cv"]["name"];
$dest = UPLOAD_DIR .$desttmp;
echo " source file : ";
echo $scr."\t";
echo " destination file : ";
echo $dest;
$success = move_uploaded_file($scr,$dest);
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
}
?>
HTML code:
<html>
<head>
<title>Form</title>
</head>
<body>
<h1>Enter your name</h1>
<form method="post" action="move.php" id="contactform" name="contactform" enctype="multipart/form-data">
<label> Upload your CV</label> <input name="jb_cv" type="file" />
<input type="submit" value="SUBMIT" />
</form>
</body>
</html
I just made a file upload code and I was wondering why the file upload wasn't working? I checked the permission of my image folder in localhost and that seems to be ok. I don't know where the problem exactly is. Any ideas?
<?php
require "config.php";
require "functions.php";
require "database.php";
if(isset($_FILES['fupload'])){
$filename = addslashes($_FILES['fupload']['name']);
$source = $_FILES['fupload']['tmp_name'];
$target = $path_to_image_directory . $filename;
$description = addslashes($_POST['description']);
$src = $path_to_image_directory . $filename;
$tn_src = $path_to_thumbs_directory . $filename;
if (strlen($_POST['description'])<4)
$error['description'] = '<p class="alert">Please enter a description for your photo</p>';
if($filename == '' || !preg_match('/[.](jpg)|(gif)|(png)|(jpeg)$/', $filename))
$error['no_file'] = '<p class="alert">Please select an image, dummy! </p>';
if (!isset($error)){
move_uploaded_file($source, $target);
$q = "INSERT into photo(description, src, tn_src)VALUES('$description', '$src','$tn_src')";
$result = $mysqli->query($q) or die (mysqli_error($myqli));
if ($result) {
echo "Succes! Your file has been uploaded";
}
createThumbnail($filename);
}
}
?><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Upload</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<h1>My photos</h1>
<ul><?php getPhotos(); ?></ul>
<h2>Upload a photo</h2>
<form enctype="multipart/form-data" action="index.php" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<input type="file" name="fupload" /><br/>
<textarea name="description" id="description" cols="50" rows="6"></textarea><br/>
<input type="submit" value="Upload photo" name="submit" />
</form>
<?php
if (isset($error["description"])) {
echo $error["description"];
}
if (isset($error["no_file"])) {
echo $error["no_file"];
}
?>
</body>
</html>
Please make sure that you appended directory separator in $path_to_thumbs_directory.
And you don't need to use addslashes to $filename.
I'm doing data entry program based on PHP every thing is working no issue (still under construction) but there is a problem that I can't find a solution. The issue is when the database doesn't have any data the image path wont get registered.
Now I'm using uplodify to upload an image file at the same moment I'm sending some data as well. The data contains a name, contact details and description this will directly be inserted to the DB and I also upload image which will get saved in to a folder and the name get saved in the database. But this processes are handled by two different PHP files one is AddPOIPro.PHP which handles the data adding and the uplodify.php to handle file upload and the updating of the file name.
The first issue I had was uplodify was not adding the file name in the same row as the submitted data so what I did was to get the last ID and decrement it by one and the updated the row that works when there is data but when theirs no data it fails. So what should I do to over come this. Below is my complete scripts thank you for your time.
Form
<?php
/**
* #author SiNUX
* #copyright 2013
*/
include ('lId.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript" src="Upl/jquery.uploadify.min.js"></script>
<script type="text/javascript" src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
$(function() {
$('#imgUpload').uploadify({
'auto' : false,
'swf' : 'Upl/uploadify.swf',
'uploader' : 'Upl/uploadify.php',
'height' : 20,
'width' : 200,
}
// Put your options here
});
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#sendData").click(function(){
var name = document.getElementById("Name").value;
var desc = document.getElementById("Descrip").value;
var con = document.getElementById("ConInfo").value;
var dataString = 'Name='+name+'&Descrip='+desc+'&ConInfo='+con;
$.ajax({
type:'POST',
data:dataString,
url:'AddPoiPro.php',
success:function(data){
if(data="Data inserted") {
//alert("Data Success");
document.getElementById('msg').innerHTML= "<div style=\"background-color:#0F0; text-align:center; color: #060\">Data Saved</dive>";
$('#msg').delay(1500).fadeOut();
} else {
//alert("Not Inserted");
document.getElementById('msg').innerHTML= "<div style=\"background-color:#0F0; text-align:center; color: red\">Data Not Saved</div>";
}
}
});
});
});
</script>
<link rel="stylesheet" type="text/css" href="Upl/uploadify.css" />
<title>AddPOI</title>
</head>
<body>
<form method="post" enctype="multipart/form-data" name="form1" id="form1">
<p>
<label for="poiid">ID :</label>
<input type="text" name="poiid" id="poiid" readonly="readonly" style="width:70px;" value="<?php echo $tId; ?>" />
</p>
<p>
<label for="Name">POI Name :</label>
<input type="text" name="Name" id="Name" />
</p>
<p>
<label for="Descrip" style="alignment-adjust:middle">POI Description :</label>
<textarea name="Descrip" id="Descrip" cols="45" rows="5"></textarea>
</p>
<p>
<label for="ConInfo">Contact Infomation :</label>
<textarea name="ConInfo" id="ConInfo" cols="45" rows="5"></textarea>
</p>
<p>
<label for="Img">POI Image</label>
<input type="file" name="imgUpload" id="imgUpload" />
</p>
<p><div id="msg"></div></p>
<p>
<div align="center">
<input type="button" name="Submit" id="sendData" value="Submit" onclick="$('#imgUpload').uploadify('upload','*');" style="width:100px;" />
<input type="reset" name="reset" id="reset" value="Rest Data" style="width:100px;" />
</div>
</p>
</form>
</body>
</html>
Process PHP
<?php
/**
* #author SiNUX
* #copyright 2013
*/
include ('connect.php');
$getId = mysql_query("SELECT ID FROM poiinfo");
$row = mysql_fetch_array($getId);
$poiName = $_REQUEST['Name'];
$poiDes = $_REQUEST['Descrip'];
$poiCon = $_REQUEST['ConInfo'];
if($row['ID']== 1){
$updLn = "UPDATE `poiinfo` SET `Name`='$poiName',`Des.`='$poiDes',`Contact`='$poiCon' WHERE 1";
$updDone = mysql_query($updLn);
if ($updDone){
echo "Data inserted";
}else {
echo "Not Done";
}
}else {
$dbData = "INSERT INTO poiinfo(`Name`, `Des.`, `Contact`) VALUES ('$poiName','$poiDes','$poiCon')";
$putData = mysql_query($dbData);
if ($putData){
echo "Data inserted";
}else {
echo "Not Done";
}
}
?>
uplodify php
<?php
/*
Uploadify
Copyright (c) 2012 Reactive Apps, Ronnie Garcia
Released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
include ('../../POIWeb/connect.php');
include ('../../POIWeb/lId.php');
// Define a destination
$path = 'POIWeb/img/';
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $path ; // Relative to the root
/*$verifyToken = md5('unique_salt' . $_POST['timestamp']);
if (!empty($_FILES) && $_POST['token'] == $verifyToken) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
$targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name'];
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$targetFile);
echo $fName;
echo '1';
} else {
echo 'Invalid file type.';
}
}*/
//if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetFile = $targetPath . $_FILES['Filedata']['name'];
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
$tId = $tId--;
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$targetFile);
$fName = $_FILES['Filedata']['name'];
$imgPath = "UPDATE poiinfo SET Img = '$fName' WHERE ID = '$tId'";
mysql_query($imgPath);
echo '1';
} else {
echo 'Invalid file type.';
}
?>
Please help.
To get Last id you can do Query As Like Following
SELECT `ID`
FROM `poiinfo`
ORDER BY `ID` DESC
LIMIT 0 , 1
If you face any more problem then you can knock me..
I think this would be a better approach
$("#sendData").click(function(){
//upload the file programatically (Method Call'upload')[http://www.uploadify.com/documentation/uploadify/upload/]
// echo the name of the uploaded file (make sure to rename the file for uniquiness)
// create a hidden element with the filename as the value inside the form
// call the ajax submit and submit the form. You can use (onuploadsuccess)[http://www.uploadify.com/documentation/uploadify/onuploadsuccess/] to trigger the element creation and ajax submit functions
});
You current implementation can cause issues consider,
Request 1 : ID 10
Upload 1 : ID 10
Request 2 : ID 11
Request 3 : ID 12
Upload 2 : ID 12
Upload 3 : ID 12
I found the Solution to my problem had some help form the guys in StackOverflow Below is my full code is any one is having the same problem similar to me you can use this code. And if it works for you pls put a vote for me thank you.
My Data Entry Form
<?php
/**
* #author SiNUX
* #copyright 2013
*/
include ('lId.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript" src="Upl/jquery.uploadify.min.js"></script>
<script type="text/javascript">
$(function() {
$(function() {
$('#imgUpload').uploadify({
'auto' : false,
'swf' : 'Upl/uploadify.swf',
'uploader' : 'Upl/uploadify.php',
'height' : 20,
'width' : 200,
'fileTypeDesc' : 'Image Files',
'fileTypeExts' : '*.gif; *.jpg; *.png'
});
// Put your options here
});
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#save_data").click(function(){
var name = document.getElementById("Name").value;
var desc = document.getElementById("Descrip").value;
var con = document.getElementById("ConInfo").value;
var dataString = 'Name='+name+'&Descrip='+desc+'&ConInfo='+con;
$.ajax({
type:'POST',
data:dataString,
url:'AddPoiPro.php',
success:function(data){
if(data="Data inserted") {
//alert("Data Success");
document.getElementById('msg').innerHTML= "<div style=\"background-color:#0F0; text-align:center; color: #060\">Data Saved</dive>";
$('#msg').delay(1500).fadeOut();
} else {
//alert("Not Inserted");
document.getElementById('msg').innerHTML= "<div style=\"background-color:#0F0; text-align:center; color: red\">Data Not Saved</div>";
$('#msg').delay(1500).fadeOut();
}
}
});
});
});
</script>
<link rel="stylesheet" type="text/css" href="Upl/uploadify.css" />
<title>AddPOI</title>
</head>
<body>
<form method="post" enctype="multipart/form-data" name="form1" id="form1">
<p>
<label for="poiid">ID :</label>
<input type="text" name="poiid" id="poiid" readonly="readonly" style="width:70px;" value="<?php echo $tId; ?>" />
</p>
<p>
<label for="Name">POI Name :</label>
<input type="text" name="Name" id="Name" />
</p>
<p>
<label for="Descrip" style="alignment-adjust:middle">POI Description :</label>
<textarea name="Descrip" id="Descrip" cols="45" rows="5"></textarea>
</p>
<p>
<label for="ConInfo">Contact Infomation :</label>
<textarea name="ConInfo" id="ConInfo" cols="45" rows="5"></textarea>
</p>
<p>
<label for="Img">POI Image</label>
<input type="file" name="imgUpload" id="imgUpload" />
</p>
<p><div id="msg"></div></p>
<p>
<div align="center">
<input type="button" name="Submit" id="save_data" value="Submit" onclick="$('#imgUpload').uploadify('upload','*');" style="width:100px;" />
<input type="reset" name="reset" id="reset" value="Rest Data" style="width:100px;" />
</div>
</p>
</form>
</body>
</html>
My DataProcess PHP
<?php
/**
* #author SiNUX
* #copyright 2013
*/
include ('connect.php');
$getId = mysql_query("SELECT ID FROM dbname");
$row = mysql_fetch_array($getId);
$poiName = $_REQUEST['Name'];
$poiDes = $_REQUEST['Descrip'];
$poiCon = $_REQUEST['ConInfo'];
if($row['ID']== 1){
$updLn = "UPDATE `poiinfo` SET `Name`='$poiName',`Des.`='$poiDes',`Contact`='$poiCon' WHERE 1";
$updDone = mysql_query($updLn);
if ($updDone){
echo "Data inserted";
}else {
echo "Not Done";
}
}else {
$dbData = "INSERT INTO poiinfo(`Name`, `Des.`, `Contact`) VALUES ('$poiName','$poiDes','$poiCon')";
$putData = mysql_query($dbData);
if ($putData){
echo "Data inserted";
}else {
echo "Not Done";
}
}
?>
This was really tricky the uploadify PHP but got it to work the way I want.
Uplodify PHP (My Version)
<?php
/*
Uploadify
Copyright (c) 2012 Reactive Apps, Ronnie Garcia
Released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
include ('../../POIWeb/connect.php');
include ('../../POIWeb/lId.php');
// Define a destination
$path = 'POIWeb/img/';
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $path ; // Relative to the root
/*$verifyToken = md5('unique_salt' . $_POST['timestamp']);
if (!empty($_FILES) && $_POST['token'] == $verifyToken) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
$targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name'];
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$targetFile);
echo $fName;
echo '1';
} else {
echo 'Invalid file type.';
}
}*/
//if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetFile = $targetPath . $_FILES['Filedata']['name'];
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
$tId = $tId--;
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$targetFile);
$fName = $_FILES['Filedata']['name'];
$imgPath = "UPDATE poiinfo SET Img = '$fName' WHERE ID = '$tId'";
mysql_query($imgPath);
echo '1';
} else {
echo 'Invalid file type.';
}
?>
This script is working flawlessly now if some face the same situation which I faced use this and see if it works for you and you're allowed to make any changes as well.
Thank you.
What i want to know is how can I get a list [specifically array] of all the files name in a directory when I select it through upload button, after which I would upload that array of files to the database. As one file as a single entry. So how do I do that?
No to forget that I just need files names and I have to upload these names only not the actual files.
are the files on the server? if you hopping to have a button you click on browser and open a folder on the end user this will not work. most browsers only allow single file selection
If you are using ftp, this function will return all of the filenames of a directory in an array.
function ftp_searchdir($conn_id, $dir) {
if(!#ftp_is_dir($conn_id, $dir)) {
die('No such directory on the ftp-server');
}
if(strrchr($dir, '/') != '/') {
$dir = $dir.'/';
}
$dirlist[0] = $dir;
$list = ftp_nlist($conn_id, $dir);
foreach($list as $path) {
$path = './'.$path;
if($path != $dir.'.' && $path != $dir.'..') {
if(ftp_is_dir($conn_id, $path)) {
$temp = ftp_searchdir($conn_id, ($path), 1);
$dirlist = array_merge($dirlist, $temp);
}
else {
$dirlist[] = $path;
}
}
}
ftp_chdir($conn_id, '/../');
return $dirlist;
}
<?
if (isset($_POST[submit])) {
$uploadArray= array();
$uploadArray[] = $_POST['uploadedfile'];
$uploadArray[] = $_POST['uploadedfile2'];
$uploadArray[] = $_POST['uploadedfile3'];
foreach($uploadArray as $file) {
$target_path = "upload/";
$target_path = $target_path . basename( $_FILES['$file']['name']);
if(move_uploaded_file($_FILES['$file']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['$file']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Untitled Document</title>
</head>
<body>
<form enctype="multipart/form-data" action="upload-simple.php" method="POST">
<p>
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload:
<input name="uploadedfile" type="file" />
</p>
<p>Choose a file to upload:
<input name="uploadedfile2" type="file" />
</p>
<p>Choose a file to upload:
<input name="uploadedfile3" type="file" />
<input name="submit" type="submit" id="submit" value="submit" />
</p>
</form>
</body>
</html>
This Might be Solve your Problems
If the files already exist on the server you can use glob
$files = glob('*.ext'); // or *.* for all files
foreach($files AS $file){
// $file is the name of the file
}