Trying to upload multiple images to a folder choose from a drop down list. I managed to make it work perfectly but all of a sudden it stopped working. The move_uploaded_file() function returns false. I have no idea why. I used echo to print out path and its 100% correct. I also checked destination directory permissions (set to 777).
I'm no expert in php, I followed multiple tutorials and guides to come up with the below code.
<!DOCTYPE html>
<html lang="en" class="no-js">
<head>
<meta charset="UTF-8">
<title>Welcome</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="css/component.css" />
<link rel="icon" href="/MobileApp/Portal/favicon.png">
<script>(function(e,t,n){var r=e.querySelectorAll("html")[0];r.className=r.className.replace(/(^|\s)no-js(\s|$)/,"$1js$2")})(document,window,0);</script>
<style type="text/css">
body{ font: 14px sans-serif; padding-left:15px; padding-top:15px; text-align: center;}
</style>
</head>
<body>
<?php
if(isset($_POST['submit']) & isset($_POST['s1'])){
$choice = $_POST['s1'];
$fixedPath = 'MobileApp/Images/';
$slash = "/";
// Count total files
$countfiles = count($_FILES['file']['name']);
// Looping all files
for($i=0;$i<$countfiles;$i++){
$filename = $_FILES['file']['name'][$i];
$chosenPath = $fixedPath.$choice.$slash.$i;
//$chosenPath = $fixedPath.$choice.$slash.$filename;
echo $chosenPath;
// Upload file
if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $chosenPath)){
echo "Good";
}
else {
echo "bad";
echo $FILES['files']['error'];
}
//move_uploaded_file($_FILES['file'],$chosenPath/.$_FILES['tmp_name']);
}
}
else {
echo "Please choose a folder";
}
?>
<p>
<legend>Files Upload</legend>
<div class="box">
<form method='post' action='' enctype='multipart/form-data' style="text-align: center">
<input type="file" name="file[]" id="file" class="inputfile inputfile-1" data-multiple-caption="{count} files selected" multiple />
<label for="file">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="17" viewBox="0 0 20 17">
<path d="M10 0l-5.2 4.9h3.3v5.1h3.8v-5.1h3.3l-5.2-4.9zm9.3 11.5l-3.2-2.1h-2l3.4 2.6h-3.5c-.1 0-.2.1-.2.1l-.8 2.3h-6l-.8-2.2c-.1-.1-.1-.2-.2-.2h-3.6l3.4-2.6h-2l-3.2 2.1c-.4.3-.7 1-.6 1.5l.6 3.1c.1.5.7.9 1.2.9h16.3c.6 0 1.1-.4 1.3-.9l.6-3.1c.1-.5-.2-1.2-.7-1.5z" />
</svg>
<span>Choose a fileā¦</span>
</label>
</div>
<input type='submit' name='submit' value='Upload' class="btn btn-warning" padding-top="15px" style="width:500px">
<BR>
<BR>
<fieldset>
<p>
<label>User's folder:</label>
<form method='post' action='' name='s1'>
<select name="s1" style="width:400px">
<option value="" selected="selected">-----</option>
<?php
foreach(glob(dirname( dirname( dirname( __FILE__ ) ) ) . DIRECTORY_SEPARATOR . 'Images' . DIRECTORY_SEPARATOR . '*') as $filename){
//foreach(glob(dirname(__FILE__) . '/MobileApp/Images/') as $filename){
$filename = basename($filename);
echo "<option value='" . $filename . "'>".$filename."</option>";
}
?>
</select>
</form>
</p>
</fieldset>
</form>
</p>
</body>
</html>
UPDATE:
I have done some tweaking in my code and narrowed down the issue to this line of code:
move_uploaded_file($_FILES['file']['tmp_name'][i], $chosenPath)
but can't see my issue..
I think the only change is needed here
$chosenPath = $fixedPath.$choice.$slash.$filename;
instead of
$chosenPath = $fixedPath.$choice.$slash.$i;
the second argument for the move_uploaded_file should be a destination filename. Only that one change worked for me.
One more thing that you need to provide the destination directory path from the root directory, that means $fixedPath = 'MobileApp/Images/'; this should be a path from root directory like /var/www/html/../../MobileApp/Images/ (it's only an example your actual directory path can be different) check this link to find the relative path of the destination directory
Related
i put this code at /var/www/html as index.php and i chmod 777 to this file
<?php
if(isset($_POST['btn-upload']))
{
$img = rand(1000,100000)."-".$_FILES['img']['name'];
$img_loc = $_FILES['img']['tmp_name'];
$folder="uploads/";
if(move_uploaded_file($img_loc,$folder.$img))
{
echo "<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%3Ealert('Upload%20Sukses!!!')%3B%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="<script>" title="<script>" />";
}
else
{
echo "<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%3Ealert('Upload%20Gagal')%3B%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="<script>" title="<script>" />";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload file dengan PHP</title>
</head>
<body>
<br />
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="img" />
<button type="submit" name="btn-upload">upload</button>
</form>
<p>
</body>
</html>
it shows blank screen, but if i run this php code
<?php
echo "test"
?>
it run perfectly
I got errors after setup my website on public and when I finished I tried to upload the image and get errors. Is this because my website doesn't use database?
Warning: move_uploaded_file(uploads/Capture.PNG): failed to open stream: No such file or directory in /storage/ssd5/873/2077873/public_html/upload.php on line 28
Warning: move_uploaded_file(): Unable to move '/storage/ssd5/873/2077873/tmp/phpuRC82y' to 'uploads/Capture.PNG' in /storage/ssd5/873/2077873/public_html/upload.php on line 28
My code:
<html>
<head>
<title>image sharer</title>
<style>
footer {
font-family: sans-serif;
position:absolute;
bottom:0;
width:100%;
}
</style>
</head>
<body>
<h1><font color="green">#img</font><font color="blue">serv</font></h1>
<form action="upload.php" method="post" enctype="multipart/form-data">
image selector :<input type="file" name="image"><br/><br/>
<input type="submit" name="upload" value="upload">
</form>
<?php
if(isset($_POST['upload'])){
$image_name = $_FILES['image']['name'];
$image_type = $_FILES['image']['type'];
$image_size = $_FILES['image']['size'];
$image_tmp_name= $_FILES['image']['tmp_name'];
#$desc = $_POST['desc'];
move_uploaded_file($image_tmp_name,"uploads/$image_name");
echo "<img src='uploads/$image_name' width='400' height='250'><br>";
echo "your image : ";
}
?>
<footer>
tos - faq - contact us
<span id="footerRight" class="copyright footerFont"><strong>#imgserv v1.1 </strong>
</span>
</div>
</footer>
</body>
</html>
The problems are not caused by the fact your website does not use a database.
The error message does point out that the elected upload directory cannot be found. Before attempting to write to that directory it would be better to test that it exists and if it does not create the necessary file structure. The function createdir below will recusively create the folder structure.
The upload handling code referenced a non-existant form field desc so you would likely have found an issue with that also.
<?php
function createdir( $path=null, $perm=0644 ) {
if( !file_exists( $path ) ) {
createdir( dirname( $path ) );
mkdir( $path, $perm, true );
clearstatcache();
}
}
$uploadstatus = false;
if( isset( $_POST['upload'], $_FILES['image'] ) ){
$obj=(object)$_FILES['image'];
$name=$obj->name;
$tmp=$obj->tmp_name;
$size=$obj->size;
$error=$obj->error;
$type=$obj->type;
if( $error == UPLOAD_ERR_OK && is_uploaded_file( $tmp ) ){
$target_directory = $_SERVER['DOCUMENT_ROOT'] . '/uploads';
$target_file = $target_directory . DIRECTORY_SEPARATOR . $name;
if( !file_exists( $target_directory ) ){
createdir( $target_directory );
}
$uploadstatus = move_uploaded_file( $tmp, $target_file );
}
}
?>
<html>
<head>
<title>image sharer</title>
<style>
footer {
font-family: sans-serif;
position:absolute;
bottom:0;
width:100%;
}
</style>
</head>
<body>
<h1><font color="green">#img</font><font color="blue">serv</font></h1>
<form action="upload.php" method="post" enctype="multipart/form-data">
<label>Image selector :<input type="file" name="image"></label><br/>
<label>Description: <input type='text' name='desc' /></label><br/>
<input type="submit" name="upload" value="upload">
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && $uploadstatus==true ){
echo "
<img src='/uploads/{$name}' width='400' height='250' />
<br />
Your image : {$name} - {$_POST['desc']}";
}
?>
</form>
<footer>
tos -
faq -
contact us
<span id="footerRight" class="copyright footerFont"><strong>#imgserv v1.1 </strong></span>
</div>
</footer>
</body>
</html>
uploads folder is missing in your directory..please create uploads directory in your website folder
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 trying to make a button that deletes an image which is uploaded on to my server. However, when I've uploaded an image then click delete nothing works it removes the image from the page but when I check the site directory it's still there. Plus there is no echo message appearing for DELETION COMPLETE either just DELETION FAILED, so it makes me wonder if it works at all and is just refreshing the page. No sure why this is, also is there a way to make it only show the loading image gif when the image is being rendered? Here's what I've got:
<?php
ob_clean();session_start();
if (isset($_GET['logout'])){
session_destroy();
}
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] == false) {
header("Location: index.php");
}
$loadingimage = false;
if(isset($_FILES['UploadFileField'])){
$allowed = array('jpg','png','jpeg');
$name = $_FILES["UploadFileField"]["name"];
$tmp = $_FILES['UploadFileField']['tmp_name'];
$type = $_FILES['UploadFileField']['type'];
$newName = "Image Attachment.jpg";
$types = array('jpg','png','jpeg');
$ext = pathinfo($name, PATHINFO_EXTENSION);
if(in_array($ext,$types)){
move_uploaded_file($tmp, "UPLOADS/$newName");
echo '<font size="3"><p align="center"><b>UPLOAD SUCCESSFUL: </font><font color="#000000" size="3">Your document has now been uploaded and is ready to send.</b></p></font>';
$loadingimage = true;
}
else {
if(!$tmp){
echo '<font size="3"><p align="center"><b>UPLOAD FAILED: </font><font color="#000000" size="3">No document has been selected.</b></p></font>';
}
else {
echo '<font size="3"><p align="center"><b>UPLOAD FAILED: </font><font color="#000000" size="3">Uploaded document was an incorrect extension type, please use ".jpg", ".jpeg", or "png" only.</b></p></font>';
}
}
}
if (isset($_POST['submit'])){
header( 'Location: Review.php' );
}
if (isset($_POST['delete'])){
if ($loadingimage == true){
echo '<font size="3"><p align="center"><b>DETLEION COMPLETE: </font><font color="#000000" size="3">Image no longer available</b></p></font>';
unlink('UPLOADS/Image Attachment.jpg');
$loadingimage = false;
}
else{
echo '<font size="3"><p align="center"><b>DETLEION FAILED: </font><font color="#000000" size="3">No image available for deletion</b></p></font>';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Attach Image</title>
<link href="CSS/boilerplate.css" rel="stylesheet" type="text/css">
<link href="CSS/master.css" rel="stylesheet" type="text/css">
<script src="JAVASCRIPT/respond.min.js"></script>
</head>
<body link="black">
<div class="gridContainer clearfix">
<div id="borderDiv">
<div id="navDiv">
<div id="backNavDiv">
<font color="white"><p align="left"><b> < Completed By</b></p></font>
</div>
<div id="logoutDiv">
<font color="white"><p align="right"><b>Log Out > </b></p></font>
</div>
</div>
<div id="headerDiv">
<p>Attach Image</p>
</div>
<?php
if($loadingimage == false){
echo '<div id="imageDiv"><img src="IMAGES/loading.gif"></div>';
}
else{
echo '<div id="imageDiv"><img src="UPLOADS/Image Attachment.jpg"></div>';
}
?>
<div id="loginBtnDiv">
<div id="uploadAreaDiv">
<form action="AttachImage.php" method="post" enctype="multipart/form-data" name="FileUploadForm" id="FileUploadForm">
<label for="UploadFileField"></label>
<input type="file" name="UploadFileField" id="UploadFileField"/>
<input type="submit" name="UploadButton" id="UploadButton" value="Upload"/>
</form>
</div>
<form action="AttachImage.php" method="post" enctype="multipart/form-data" name="delete" id="delete">
<input id="delete" name="delete" type="submit" value="Delete">
</form>
<form action="AttachImage.php" method="post" enctype="multipart/form-data" name="FileForm" id="FileForm">
<input id="submit" name="submit" type="submit" value="Next">
</form>
</div>
</div>
</div>
<div id="logoDiv">
<img src="IMAGES/Logo.png">
</div>
</body>
</html>
As I commented before, because you define $loadingimage = false;, you will only be able to delete the file if the file is being uploaded at the very same time - which seems rather pointless.
You should rather check if the file exists than using your $loadingimage variable for unlinking the file.
You could change
if ($loadingimage == true){
with
if (file_exists("UPLOADS/Image Attachment.jpg")) {
This will only delete the file if it exists, and prevent unlink from causing warnings.
Your $loadingimagevariable is always false. So you will never execute the unlink() function. If you think that it will be true because you set it to true in if(isset($_FILES['UploadFileField'])){}, it will not, because your page is reloaded and you passed the $_POST['delete'] to the page and $loadingimage variable will be set to false again. So remove the condition
if($loadingimage==true){} and your code should work. I don't see any reason why you're making this condition at all.
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.