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
}
Related
Please i need your help on this. Any time i transfer this file into remote server through ftp, it often get missing on the server somehow. I always have to re-upload it. Recently all i get are errors like this PHP Warning: require(maxUpload.class.php): failed to open stream: No such file or directory.
I know the errors are due to due to my require() function.
Is there any reason this file keep getting lost on the remote server?
<?php
require 'maxUpload.class.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>
<title>Upload Page</title>
</head>
<body>
<?php
$myUpload = new maxUpload();
//$myUpload->setUploadLocation(getcwd().DIRECTORY_SEPARATOR);
$myUpload->uploadFile();
?>
</body>
This is maxUpload.class.php
<?php
class maxUpload{
var $uploadLocation;
function maxUpload(){
$this->uploadLocation = getcwd().DIRECTORY_SEPARATOR."/images". DIRECTORY_SEPARATOR;
}
function setUploadLocation($dir){
$this->uploadLocation = $dir;
}
function showUploadForm($msg='',$error=''){
?>
<div id="container">
<div id="content">
<?php
if ($msg != ''){
echo '<p class="msg">'.$msg.'</p>';
} else if ($error != ''){
echo '<p class="emsg">'.$error.'</p>';
}
?>
<form action="" method="post" enctype="multipart/form-data" >
<center>
<label>Upload Image (Jpeg Only)
<input name="myfile" type="file" size="30" />
</label>
<label>
<input type="submit" name="submitBtn" class="sbtn" value="Upload" />
</label>
</center>
</form>
</div>
</div>
<?php
}
function uploadFile(){
if (!isset($_POST['submitBtn'])){
$this->showUploadForm();
} else {
$msg = '';
$error = '';
if (!file_exists($this->uploadLocation)){
$error = "The target directory doesn't exists!";
} else if (!is_writeable($this->uploadLocation)) {
$error = "The target directory is not writeable!";
} else {
$target_path = $this->uploadLocation . basename( $_FILES['myfile']['name']);
if(#move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
$msg = basename( $_FILES['myfile']['name']).
" <b style='color:white;'>was uploaded successfully!</b>";
} else{
$error = "The upload process failed!";
}
}
$this->showUploadForm($msg,$error);
}
}
}
?>
Your file is not missing, this error also indicate that you are giving wrong path to the file, make sure maxUpload.class.php is in same folder. you need to give correct path to require() function where to locate this file.
You can also use getcwd() to Gets the current working directory.
something like echo getcwd();. you can use chdir() function to go to specific folder by giving correct path chdir("../");
i don't know your folder structure but add
require '../maxUpload.class.php' or
require '/maxUpload.class.php'
I need to upload the image to a server and store to the directory created by PHP using current timestamp. Below is the relevant part of the code, but not working as expected, it's not creating a folder as well it's not printing to the console. What could be the issue?
Edit:
Modified php based on below comment
upload.php
<?php
//get unique id
$up_id = uniqid();
?>
<?php
//process the forms and upload the files
if ($_POST) {
//specify folder for file upload
$user = "user";
//console.log("debug.......");
echo "debug.......";
if (!file_exists("/var/www/Scan")) {
mkdir("/var/www/Scan", 0777, true);
}
$folderName = date("Y-m-d") . "_" . date("h_i_sa") . "_" . $user;
if (!file_exists("/var/www/Scan/$folderName")) {
mkdir("/var/www/Scan/$folderName", 0777, true);
}
$folder = "/var/www/Scan/$folderName";
//specify redirect URL
$redirect = "upload.php?success";
//upload the file
move_uploaded_file($_FILES["file"]["tmp_name"], "$folder" . $_FILES["file"]["name"]);
//do whatever else needs to be done (insert information into database, etc...)
//redirect user
header('Location: '.$redirect); die;
}
//
?>
<!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>Upload your file</title>
<!--Progress Bar and iframe Styling-->
<link href="style_progress.css" rel="stylesheet" type="text/css" />
<!--Get jQuery-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.js" type="text/javascript"></script>
<!--display bar only if file is chosen-->
<script>
$(document).ready(function() {
//
//show the progress bar only if a file field was clicked
var show_bar = 0;
$('input[type="file"]').click(function(){
show_bar = 1;
});
//show iframe on form submit
$("#form1").submit(function(){
if (show_bar === 1) {
$('#upload_frame').show();
function set () {
$('#upload_frame').attr('src','upload_frame.php?up_id=<?php echo $up_id; ?>');
}
setTimeout(set);
}
//document.getElementById("message").innerHTML = "";
});
//
});
</script>
</head>
<body>
<div id="outPopUp">
<h1 >Upload your file </h1>
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
<br />
<br />
<!--Choose a file to upload<br />-->
<!--APC hidden field-->
<input type="hidden" name="APC_UPLOAD_PROGRESS" id="progress_key" value="<?php echo $up_id; ?>"/>
<!---->
<!-- <input name="file" type="file" id="file" size="30"/>-->
<label class="custom-file-upload">
<input name="file" type="file" id="file" onclick="myFunction()" />
Choose Video
</label>
<!--Include the iframe-->
<br />
<br />
<iframe id="upload_frame" name="upload_frame" color= black frameborder="0" border="0" src="" scrolling="no" scrollbar="no" > </iframe>
<br />
<!---->
<br />
<input class="btn btn-blue" name="Submit" type="submit" id="submit" value="Submit" />
<br />
<br />
<?php if (isset($_GET['success'])) { ?>
<span style="color:#FFFFFF;" id="message" class="notice">Your file has been uploaded.</span>
<?php } ?>
</form>
</div>
<script>
function myFunction() {
document.getElementById("message").innerHTML = "";
}
/*document.getElementById('file').onchange = function () {
//alert('Selected file: ' + this.value);
var path = this.value;
var fileName = path.replace(/.*(\/|\\)/, '');
alert('Selected file: ' + fileName);
//myFunction(fileName);
};*/
</script>
</body>
</html>
try a simple example for understanding:
<?php
//php content
if ($_POST) { //here we are checking $_POST values that $_POST has some values.
//specify folder for file upload
$tempDir = __DIR__ . DIRECTORY_SEPARATOR . 'upload'; //it means make a directory uploads where this php file is kept.
if (!file_exists($tempDir)) { // if $tempDir is not there, so it will create that directory.
mkdir($tempDir);
}
if(!empty($_FILES))//now checking your uploaded file is not empty
{
$nm=$_FILES['file']['name']; //here $nm get the name of the file
$tmp=$_FILES['file']['tmp_name'];//$tmp get the temporary file stored path
$mDir = __DIR__ . DIRECTORY_SEPARATOR . 'uploads'. DIRECTORY_SEPARATOR .time().$nm; //this your destination path with time+nameof file as a name of file.
if(move_uploaded_file($tmp,$mDir)) //uploading file to your destination path, if uploaded then it will go in the if scope and echo.
{
echo "file uploaded with timestamp in uploads folder";
//now redirect from here any where
}
else
{
echo "fail to upload a file";
}
}
}
?>
I'm having issues uploading zip files and can't seem to find an answer.
Index.php
<form id="convertFile" action="convert.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="exampleInputFile">File input</label>
<input name="upload" type="file" id="inputFile">
</div>
<div class="form-group">
<button type="submit">Submit</button>
</div>
</form>
convert.php:
if(isset($_FILES)){
echo $_FILES['upload']['name'];
}else{
echo json_encode(array('status'=>'error'));
}
When I upload a zip file, I get: Notice: Undefined index: upload in C:\wamp\www\xmlconverter\convert.php on line 3
This is what chrome shows in the post header:
------WebKitFormBoundaryuFNy5dZtFj7olmD5
Content-Disposition: form-data; name="zip_file"; filename="123.zip"
Content-Type: application/x-zip-compressed
------WebKitFormBoundaryuFNy5dZtFj7olmD5--
This works on any other major file format, but can't get it to read the zip file. If I var_dump $_FILES or $_POST they are empty.
What am I missing? Why does all other files work but zip does not.
Thank you
using wamp and php 5.5.12
Where is your zip file type definition?
Anyways, let say this was the html form to upload zip files you'd have the following:
<!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" />
<title>Untitled Document</title>
</head>
<body>
<?php if($message) echo "<p>$message</p>"; ?>
<form enctype="multipart/form-data" method="post" action="">
<label>Choose a zip file to upload: <input type="file" name="zip_file" /></label>
<br />
<input type="submit" name="submit" value="Upload" />
</form>
</body>
</html>
On the server-side script which handles the post you'd have:
<?php
if($_FILES["zip_file"]["name"]) {
$filename = $_FILES["zip_file"]["name"];
$source = $_FILES["zip_file"]["tmp_name"];
$type = $_FILES["zip_file"]["type"];
$name = explode(".", $filename);
$accepted_types = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');
foreach($accepted_types as $mime_type) {
if($mime_type == $type) {
$okay = true;
break;
}
}
$continue = strtolower($name[1]) == 'zip' ? true : false;
if(!$continue) {
$message = "The file you are trying to upload is not a .zip file. Please try again.";
}
$target_path = "/home/var/yoursite/httpdocs/".$filename; // change this to the correct site path
if(move_uploaded_file($source, $target_path)) {
//if you also wanted to extract the file after upload
//you can do the following
$zip = new ZipArchive();
$x = $zip->open($target_path);
if ($x === true) {
$zip->extractTo("/home/var/yoursite/httpdocs/"); // change this to the correct site path
$zip->close();
unlink($target_path);
}
$message = "Your .zip file was uploaded and unpacked.";
} else {
$message = "There was a problem with the upload. Please try again.";
}
}
?>
I used a script very similar to one posted by #unixmiah without issue on my cPanel based server. Worked great (and has for year now) but ran into issue of error "PHP, undefined index" when using locally with wamp.
Here is the mod that worked for me:
<?php
function rmdir_recursive($dir) {
foreach(scandir($dir) as $file) {
if ('.' === $file || '..' === $file) continue;
if (is_dir("$dir/$file")) rmdir_recursive("$dir/$file");
else unlink("$dir/$file");
}
rmdir($dir);
}
if(!empty($_FILES)){
//added above to script and closing } at bottom
if($_FILES["zip_file"]["name"]) {
$filename = $_FILES["zip_file"]["name"];
$source = $_FILES["zip_file"]["tmp_name"];
$type = $_FILES["zip_file"]["type"];
$name = explode(".", $filename);
$accepted_types = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');
foreach($accepted_types as $mime_type) {
if($mime_type == $type) {
$okay = true;
break;
}
}
$continue = strtolower($name[1]) == 'zip' ? true : false;
if(!$continue) {
$message = "<b>The file you are trying to upload is not a .zip file! Please try again...</b>";
}
$target_path = "somedir/somesubdir/".$filename; // change this to the correct site path
if(move_uploaded_file($source, $target_path)) {
$zip = new ZipArchive();
$x = $zip->open($target_path);
if ($x === true) {
$zip->extractTo("somedir/somesubdir/"); // change this to the correct site path
$zip->close();
unlink($target_path);
}
$message = "<h2>ZIP file was uploaded and content was replaced!</h2>";
} else {
$message = "There was a problem with the upload. 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=UTF-8" />
<title>QikSoft ZIP Upper</title>
</head>
<body>
<?php if(!empty($message)) echo "<p>$message</p>"; ?>
<form enctype="multipart/form-data" method="post" action="">
<label><h3>Upload Your ZIP:</h3> <input type="file" name="zip_file" /></label>
<br /><br />
<input type="submit" name="submit" value="START UPLOAD" />
</form>
</body>
</html>
Also note that the echo message has been changed:
<?php if(!empty($message)) echo "<p>$message</p>"; ?>
One thing that does not work is file restriction. Currently allows other types besides ZIP. Anyone with fix, be greatly appreciated.
It's echo $_FILES['upload']['tmp_name'];
Try checking and adjusting the post_max_size value in your php.ini file, this worked for me as the default is 3M, raised the value to 128M and everything was peachy
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.
how to write code to upload image and save path into mysql db?
i have tried but none are working.
One way is to upload image and store it in a folder on server, and save name to mysql database. Here's an example ::
First we'll create a form to upload ::
//file.html
Upload your file to the database...
<form action="upload.php" method="post" enctype="multipart/form-data" name="uploadform">
<input type="hidden" name="MAX_FILE_SIZE" value="350000">
<input name="picture" type="file" id="picture" size="50">
<input name="upload" type="submit" id="upload" value="Upload Picture!">
</form>
Then we create upload.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=iso-8859-1" />
<title> Upload Image </title>
<?php
// if something was posted, start the process...
if(isset($_POST['upload']))
{
// define the posted file into variables
$name = $_FILES['picture']['name'];
$tmp_name = $_FILES['picture']['tmp_name'];
$type = $_FILES['picture']['type'];
$size = $_FILES['picture']['size'];
// if your server has magic quotes turned off, add slashes manually
if(!get_magic_quotes_gpc()){
$name = addslashes($name);
}
// open up the file and extract the data/content from it
$extract = fopen($tmp_name, 'r');
$content = fread($extract, $size);
$content = addslashes($content);
fclose($extract);
// connect to the database
include "connect.php";
// the query that will add this to the database
$addfile = "INSERT INTO files (name, size, type, content ) VALUES ('$name', '$size', '$type', '$content')";
mysql_query($addfile) or die(mysql_error());
if(!empty($_FILES))
{
$target = "upload/";
$target = $target . basename( $_FILES['picture']['name']) ;
$ok=1;
$picture_size = $_FILES['picture']['size'];
$picture_type=$_FILES['picture']['type'];
//This is our size condition
if ($picture_size > 5000000)
{
echo "Your file is too large.<br>";
$ok=0;
}
//This is our limit file type condition
if ($picture_type =="text/php")
{
echo "No PHP files<br>";
$ok=0;
}
//Here we check that $ok was not set to 0 by an error
if ($ok==0)
{
Echo "Sorry your file was not uploaded";
}
//If everything is ok we try to upload it
else
{
if(move_uploaded_file($_FILES['picture']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['picture']['name']). " has been uploaded <br/>";
}
else
{
echo "Sorry, there was a problem uploading your file.";
}
}
}
mysql_close();
echo "Successfully uploaded your picture!";
}else{die("No uploaded file present");
}
?>
</head>
<body>
<div align="center">
<img src="upload/<?php echo $name; ?>"
<br />
upload more images
</div>
</body>
</html>
//getpicture.php
**//Finally the connect.php**