How to display images right after they clicked the upload button?
Here is my HTML Code:
form.php
<html>
<body>
<form action="uploadFile.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
And here is my uploadFile.php code:(updated, but still not getting any result)
<?php
// prevent timezone warnings
date_default_timezone_set('Philippines/Manila');
// set the upload location
$UPLOADDIR = "images/";
// if the form has been submitted then save and display the image(s)
if(isset($_POST['Submit'])){
// loop through the uploaded files
foreach ($_FILES as $key => $value){
$image_tmp = $value['tmp_name'];
$image_type=$value['type'];
$image = $value['name'];
$image_file = "{$UPLOADDIR}{$image}";
//check if there's existing file name
if ($image != 0){
echo 'File Already Exists!';
}
else {
// move the file to the permanent location
if(move_uploaded_file($image_tmp,$image_file)){
// this is where the displaying part goes
echo <<<HEREDOC
<div style="float:left;margin-right:10px">
<img src="$editedShear" alt="This is your image" height=200 width=200/></br>
</div>
HEREDOC;
}
else{
echo "<h1>image file upload failed, image too big after compression</h1>";
}
}
}}
else{
?>
<?php
}
?>
To do that you need to upload the image using some kind of ajax upload. if you don't know what is that, please read here http://en.wikipedia.org/wiki/Ajax_%28programming%29. You can find some free solutions and examples online. Here I found a stack overflow question that might help you with links to such a solutions
Ajax file upload
Upload your image in a folder which contains your php/html file,
and in img tag write the img name:
<img src="<?php echo $img;?>" width="400" height="600"/>
/* i put image so that it has default
<img id="blah" src="images/male.png" alt="your image" style="width:250px;height:200px;" />
/*put accept and its format so that you can only choose the image only
<input type='file' name="image" onchange="readURL(this);" accept="image/gif,image/png,image/jpg,image/jpeg" />
/*changing the url of an image you can do it in jquery
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah')
.attr('src', e.target.result)
/*set the width and height of an image
.width(250)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
after that do your upload code
What is the easiest way to upload images and display the uploaded images on same page?
page "index.php"
<body>
<div id="body">
<form action="upload.php" name="img_compress" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<button type="submit" name="btn-upload">upload</button>
</form>
<br /><br />
<?php
if(isset($_GET['success']))
{
?><br><br><br>
<?php
$sql="SELECT * FROM tbl_uploads ORDER BY id DESC";
$result_set=mysql_query($sql);
while($row=mysql_fetch_array($result_set))
{
?>
<img src="uploads/<?php echo $row['file'] ?>" width="100%" height="100%">
<?php
}
?>
<?php
}
else if(isset($_GET['fail']))
{
?>
<label>Problem While File Uploading !</label>
<?php
}
else
{
?>
<label>Try to upload any files(PDF, DOC, EXE, VIDEO, MP3, ZIP,etc...)</label>
<?php
}
?>
</div>
</body>
code for upload "upload.php"
<?php
include_once 'dbconfig.php';
if(isset($_POST['btn-upload']))
{
$file = $_FILES['file']['name'];
$file_loc = $_FILES['file']['tmp_name'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
$folder="uploads/";
$new_size = $file_size/1024;
$new_file_name = strtolower($file);
$final_file=str_replace(' ','-',$new_file_name);
if(move_uploaded_file($file_loc,$folder.$final_file))
{
$sql="INSERT INTO tbl_uploads(file,type,size) VALUES('$final_file','$file_type','$new_size')";
mysql_query($sql);
?>
<script>
window.location.href='index.php?success';
</script>
<?php
}
else
{
?>
<script>
alert('error while uploading file');
window.location.href='index.php?fail';
</script>
<?php
}
}
?>
below one is fields for storing images
enter image description here
Add an iframe after your form:
<iframe name="resultFrame" width="500" height="300"></iframe>
And add the target="resultFrame" attribute in your form like this:
<html>
<body>
<form action="uploadFile.php" method="post"
enctype="multipart/form-data" target="resultFrame">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
<iframe name="resultFrame" width="500" height="300"></iframe>
</body>
</html>
Related
I'm very new to coding.
I'm trying to upload an image (any file for now) in a particular folder.
<?php
$name = $_FILES["file"]["name"];
$tmpName = $_FILES["file"]["tmp_name"];
if(isset($name)){
if(!empty($name)){
$location = "uploads/";
$destination_path = getcwd().DIRECTORY_SEPARATOR;
if (move_uploaded_file($tmpName,$destination_path.$location.$name)) {
echo "uploaded!";
}
else {
echo "boo";
}
}
else {
echo "please choose a file";
}
}
?>
<html>
<body>
<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<br>
<br>
<input type="submit" value="SUBMIT">
</form>
</body>
</html>
Everything is getting executed properly until the "move_uploaded_file" if-condition. Getting the else-echo-statement("boo")
I try upload image to mysql database and display it along with the description of image using php. After i upload the image and display it , a broken image was displayed but the description of the image was displayed without any error. How can I solve this problem ? Appreciate your help
<?php
$msg = "";
//if upload button is pressed
if(isset($_POST['upload']))
{
// the path to store the uploaded image
$target = "images/".basename($_FILES['image']['name']);
// connect to database
$db = mysqli_connect("localhost","root","","product");
// Get all the submitted data from the form
$image = $_FILES['image']['name'];
$text = $_POST['text'];
$sql = "INSERT INTO product_list (image, text) VALUES ('$image','$text')";
mysqli_query($db,$sql); // stores the submitted data into the database table : product_list
// move uploaded image to the folder : image
if (move_uploaded_file($_FILES['image']['tmp_name'],$target))
{
$msg = "Image and text uploaded successfully";
}else
{
$msg = "There was a problem uploading image";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Image Upload With Description</title>
<link rel="stylesheet" type="text/css" href="formstyle.css">
</head>
<body>
<div id="content">
<?php
$db = mysqli_connect("localhost","root","","product");
$sql = "SELECT * FROM product_list";
$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_array($result))
{
echo "<div id='img_div'>";
echo "<img src='".$row['image']."'>";
echo "<p>".$row['text']."</p>";
echo "</div>";
}
?>
<form method="post" action="try.php" enctype="multipart/form-data">
<input type="hidden" name="size" value="1000000">
<div>
<input type="file" name="image">
</div>
<div>
<textarea name="text" cols="40" rows="4" placeholder="Details of product"></textarea>
</div>
<div>
<input type="submit" name="upload" value="Upload Image">
</div>
</form>
</div>
</body>
</html>
This is my result :
You are storing it in the DB without the images directory. You either need to store it with that, or always remember to call it that way in your image calls.
echo "<img src='images/".$row['image']."'>";
or make your the record you are writing the same as the filesystem location.
$image = 'images/' . $_FILES['image']['name'];
Note you are open to SQL injections and file inclusion injections with this code.
try this
<?php
$msg = "";
//if upload button is pressed
if(isset($_POST['upload']))
{
// the path to store the uploaded image
$destination_path = getcwd().DIRECTORY_SEPARATOR;
$target_path = $destination_path . basename( $_FILES["image"]["name"]);
// connect to database
$db = mysqli_connect("localhost","root","","product");
// Get all the submitted data from the form
$image = $_FILES['image']['name'];
$text = $_POST['text'];
$sql = "INSERT INTO product_list (image, text) VALUES ('$image','$text')";
mysqli_query($db,$sql); // stores the submitted data into the database table : product_list
//#move_uploaded_file($_FILES['image']['tmp_name'], $target_path)
// move uploaded image to the folder : image
if (move_uploaded_file($_FILES['image']['tmp_name'],$target_path))
{
$msg = "Image and text uploaded successfully";
}else
{
$msg = "There was a problem uploading image";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Image Upload With Description</title>
<link rel="stylesheet" type="text/css" href="formstyle.css">
</head>
<body>
<div id="content">
<?php
$db = mysqli_connect("localhost","root","","product");
$sql = "SELECT * FROM product_list";
$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_array($result))
{
echo "<div id='img_div'>";
echo "<img src='".$row['image']."'>";
echo "<p>".$row['text']."</p>";
echo "</div>";
}
?>
<form method="post" action="index.php" enctype="multipart/form-data">
<input type="hidden" name="size" value="1000000">
<div>
<input type="file" name="image">
</div>
<div>
<textarea name="text" cols="40" rows="4" placeholder="Details of product"></textarea>
</div>
<div>
<input type="submit" name="upload" value="Upload Image">
</div>
</form>
</div>
</body>
</html>
This is my file uploader:
<form action="done.php" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit" value="upload">Upload</button>
</form>
This is what happens now:
If I do not select any file and I click on "submit", I will be redirected to the done.php.
What I need:
If there is no file selected and I click on submit, I want to stay on my site and get an error messagage "No file selected".
done.php:
if(isset($_FILES['file'])) {
$file = $_FILES['file'];
$target_file = 'files/'.basename($_FILES["file"]["name"]);
$filename = $target_file;
if (file_exists($target_file)) {
echo "file already existes";
}
else {
move_uploaded_file($_FILES["file"]["tmp_name"], $target_file);
}
}
I updated my code now like Florian suggested:
done.php:
if(isset($_FILES['file'])) {
$file = $_FILES['file'];
$target_file = 'files/'.basename($_FILES["file"]["name"]);
$filename = $target_file;
if (file_exists($target_file)) {
echo "file already existes";
}
else {
move_uploaded_file($_FILES["file"]["tmp_name"], $target_file);
}
}
else {
echo 'No file selected. Back to upload form';
}
What happens now is, when I do not select any file I get the error message: "file already exists". I do not understand why.
Extend your done.php as follow:
if(!file_exists($_FILES['file']['tmp_name']) || !is_uploaded_file($_FILES['file']['tmp_name'])) {
$file = $_FILES['file'];
$target_file = 'files/'.basename($_FILES["file"]["name"]);
$filename = $target_file;
move_uploaded_file($_FILES["file"]["tmp_name"], $target_file);
} else {
echo 'No file selected. Back to upload form';
// maybe you want to include the upload form here or do something else
}
<html>
<body>
<script>
function unlock(){
document.getElementById('buttonSubmit').removeAttribute("disabled");
}
</script>
<form action="done.php" method="post" enctype="multipart/form-data">
<input type="file" onchange="unlock();" name="file">
<button type="submit" id="buttonSubmit" value="upload" disabled>Upload</button>
</form>
</body>
</html>
Depending on your "View-Code" it could be something like that
<form action="done.php" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="hidden" name="todo" value="fileupload"?>
<button type="submit" value="upload">Upload</button>
</form>
<?php if($_POST && !$_FILES):?>
<h3>"No file selected".</h3>
<?php endif;?>
<html>
<head>
<style>
li
{
display: inline-block;
}
</style>
<script>
function formValidation()
{
if(document.getElementById("fileName").value==""||document.getElementById("fileName").value==null)
{
alert("no file selected");
return false;
}
else
return true;
}
</script>
</head>
<body>
<form action="done.php" method="post" enctype="multipart/form-data" onSubmit="return formValidation()">
<input id="fileName" type="file" name="file">
<button type="submit" value="upload">Upload</button>
</form>
</body>
</html>
You can check it with
if(strlen($_FILES[$mcFile]['name'])==0){
echo "Error No file selected ";
}
OR
if ($_FILES["file"]["error"] > 0){
echo "Error No file selected ";
}
These both are the way to check files validation at server end
i am able to display image on screen but i want to display the image using session.Please help me.
$_SESSION['user_name6'] = $_FILES["file"]["name"];
if(isset($_SESSION['user_name6']))
{
echo "<img src=<?php echo $_SESSION[user_name6]; ?> width=300 height=400
alt=Image path Invalid name=image />";
}
else
{
print "no pic here";
}
I do not know what you will actually do but this is the approach that best fits
when you put a file type in your form, you need to use the global variable Files
form.html
<form action="process.php" method="post" enctype="multipart/form-data">
<label for="picture">Picture:</label>
<input type="file" name="picture" id="picture"><br>
<input type="submit" name="submit" value="Upload">
</form>
process.php
<?php
session_start();
//make sure you have created the **upload** directory
$filename = $_FILES["picture"]["tmp_name"];
$destination = "upload/" . $_FILES["picture"]["name"];
move_uploaded_file($filename, $destination); //save uploaded picture in your directory
$_SESSION['user_name6'] = $destination;
header('Location: display_picture.php');
display_picture.php
<?php
session_start();
?>
<div>
<img src="<?php echo $_SESSION['user_name6']; ?>" alt="picture"/>
</div>
i have this page for upload:
<?php
require ('incs/db.php');
require_once ('incs/funcs.php');
?>
<?php
if (array_key_exists('upload', $_POST)) {
$directory = str_replace(basename($_SERVER['PHP_SELF']),'',$_SERVER['PHP_SELF']);
$uploadHandler = $_SERVER['DOCUMENT_ROOT']. $directory . 'images/';
// $uploadHandler = "echtitipi".$_SERVER['HTTP_HOST']. '/images/';
$max_file_size = 30000;
define('UPLOAD_DIR', $uploadHandler);
$ext= end(explode(".", $_FILES['image']['name']));
$name = rand(1111111,9999999).'.'.$ext;
if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadHandler. $name))
{
$upload = true;
$title = $_POST ['title'];
$sql = "INSERT INTO photo (id, keyword, photoName)
VALUES ('','$title','$name')
";
$result = mysql_query ( $sql, $con );
}
else
{
$upload = false;
$msg = 'Cant Upload!';
}
}
?>
<?php
include ('incs/header.php');
?>
<?php
getUrlQuery();
?>
<script language="javascript">
<!--
function pick(symbol, path) {
if (window.opener && !window.opener.closed)
window.opener.document.form.img.value = symbol;
window.opener.document.form.imgbox.src = path;
window.close();
}
// -->
</script>
<form action="upload.php" method="post" enctype="multipart/form-data" name="uploadImage" id="uploadImage">
<p>
<label for="image">
Tanım:
</label>
<input type="text" name="title" id="title" />
<label for="image">
Upload image:
</label>
<input type="file" name="image" id="image" />
</p>
<p>
<input type="submit" name="upload" id="upload" value="Upload" />
</p>
</form>
<?php
if($upload == true)
{
echo "<a hrf(because spam!)=\"javascript:pick('$name','images/$name')\"><im(g) src=\"images/$name\" border=\"0\" alt=\"use\"></a>";
}
?>
<?php
include ('incs/footer.php');
?>
`
this upload image to curretnt root's images folder. My current folder is admin:
root/admin/images
root/images
when i use
$uploadHandler = "http://".$_SERVER['HTTP_HOST']. '/images/';
script doesnot work.
<?php
if($upload == true)
{
echo "<a hrf=\"javascriptick('$name','{$uploadHandler}$name')\"><im(g) src=\"{$uploadHandler}$name\" border=\"0\" alt=\"use\"></a>";
}
?>
the image couldnot add to editor. I guess There is a problem with javascript.
what is wrong in script
echo "<a hrf=\"javascriptick('$name','{$uploadHandler}$name')\"><im(g) src=\"{$uploadHandler}$name\" border=\"0\" alt=\"use\"></a>";
change into
echo "<img src=\"{$uploadHandler}$name\" border=\"0\" alt=\"use\">";
I guess this will help...
Im sorry for bad dictation because i cant write the right script because sending errors(link and images)
above code uploaded code to
/www/admin/images
and save information to database and add image to tinymce editor. But I want to upload code to:
www/images
when I use :
$uploadHandler = $_SERVER['DOCUMENT_ROOT'].'/images/';
and
"<img src=\"images/$name\" border=\"0\" alt=\"use\">"
the image couldnot add to editor. This is my problem.