I have a website backend that lets you upload images to my site, like an alternative to FTP, I want to use this as a backend to my image portfolio, what I want, is once these images upload, it adds this image to my HTML, by adding new DOM elements being new to PHP though, I currently do not know how to do this.
here is my php (modified from W3Schools)
[upload.php]
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo " " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 9000000) {
echo "Sorry, your file is too large. (10mb limit)";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
and the HTML I want to append to:
[index.html]
<body>
<div class="parent">
<!-- image preview, onlick go to lightbox -->
<a href="#img1" class="">
<img src="image1.png" class="">
</a>
<!-- image lightbox -->
<a href="#" class="lightbox" id="img1">
<span style="background-image: url('1.png')"></span>
</a>
</div>
</body>
I want the PHP to add to my container, with the same exact structure as both the #img1 DOM elements, so that it creates a new lightbox, also meanting that it should have a new #img tag, that will add from the last, for example, say the newest is #img6, when uploading to my PHP, the PHP will add a #img7 element etc etc. and the new elements should be in my parent div.
It should also replace the src and background-image from 1.png to whatever the image I have just uploading is.
The result I want from from uploading an image with this new code should look like this
<body>
<div class="parent">
<!-- image preview, onlick go to lightbox -->
<a href="#img1" class="">
<img src="image1.png" class="">
</a>
<!-- image lightbox -->
<a href="#" class="lightbox" id="img1">
<span style="background-image: url('1.png')"></span>
</a>
<!-- image preview, onlick go to lightbox -->
<a href="#img2" class="">
<img src="uploadedthruphp.png" class="">
</a>
<!-- image lightbox -->
<a href="#" class="lightbox" id="img2">
<span style="background-image: url('uploadedthruphp.png')"></span>
</a>
You should use ul instead of div and append li elements with every uploaded image in your HTML code. Insert javascript snippets in the PHP part where the image upload is successful. You can echo the PHP variable $target_file there:
index.html
<body>
<ul id="parent">
<!-- image preview, onlick go to lightbox -->
<li>
<a href="#img1" class="">
<img src="image1.png" class="">
</a>
<!-- image lightbox -->
<a href="#" class="lightbox" id="img1">
<span style="background-image: url('1.png')"></span>
</a>
</li>
</ul>
</body>
upload.php:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
...
.....
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var links=document.getElementsByTagName('a');
var hrefs = [];
var target_file = '<?php echo $target_file; ?>';
for (var i = 0; i<links.length; i++)
{
const myArray = links[i].href.split("#");
str = myArray[1].replace("img", "");
hrefs.push(str);
}
hrefs.sort();
var last = parseInt(hrefs[hrefs.length - 1]);
var next = last + 1;
var nextLink = "#img"+next;
var nextID = "img"+next;
var html = '';
html += '<li>';
html += '<img src="'+target_file+'" class="">';
html += '<span style="background-image: url('+target_file+')"></span>';
html += '</li>';
$("#parent").append(html);
</script>
<?php
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
Related
The images are fetched from the PHP PDO database from the directory "Images" where there are multiple images in it using SQL queries. When I try to click on the source link of the image and try to open the modal image, only the first image is been viewed by all other images too. I tried to change the ID names, but still it is showing the same first page. I have attached my code and the output below. Requesting anyone to help me in this and also the procedure to change the ID values.
if($data=$stmt->fetchAll(PDO::FETCH_ASSOC)) // to display all the images from the given condition
{
$link_id=0;
foreach($data as $row)
{
//$img=$row['images'];
$id=$row['id'];
$link_id=$link_id+1;
$query="SELECT images FROM pictures WHERE id=$id";
$stmt2=$conn->query($query);
$pictures=$stmt2->fetchAll(PDO::FETCH_ASSOC);
foreach($pictures as $rowimg)
{
$img=$rowimg['images'];
?>
<b><a id='<?php echo $link_id;?>' class='link_class' onclick='myfunc();'> <?php echo $img;?> </a></b>
<br><br>
<div id='modal_id' class='modal_class'>
<div class='modal_content_class'>
<img id='<?php echo $id;?>' class='img_class' src="images/<?php echo $img;?>" width='300' height='260'>
<span id='close_id' class='close_class' onclick="modal.style.display='none'">×</span>
</div>
</div>
<script>
var modal = document.getElementById("modal_id");
var closebtn =modal.getElementsByClassName("close_class");
function myfunc()
{
modal.style.display='block';
document.getElementById('<?php echo $id; ?>'). src="images/<?php echo $img;?>";
console.log(123);
};
</script>
}
}
}
Output
Output
i'm developing a book page preview website which fetches book all page images (thumbnail) from file server through mysql database, clicking on a thumbnail will display that image on main div, also by clicking next or prev button it has to change the image from thumbnail and display it on main div.
i have done fetching images and click on thumbnail will display the image on main div and the buttons also working but when i change image by button it's not displaying on main div this my problem. i'm new to this php and javascript, i have followed the codes from this http://jsfiddle.net/Bgj4b/, i have put days on this still not figured out please help me.
This is my problem Demo: https://jsfiddle.net/Looper/5r6qb5k3/
This is my actual codes
PHP/HTML
<button class="left-arrow" id="left-arrow">Left</buttom>
<img src="" alt="book" class="main-img" id="main-img">
<button class="right-arrow" id="right-arrow">Right</buttom>
<ul class="book-list id="book-list">
<?php if ($total_page > 0) : ?>
<?php foreach ($results as $row) : ?>
<li class="book p-2">
<span class="page-number"><?php echo $page_num++ ?></span>
<img src="<?php echo PAGE_URL . "/" . $b_id . "/" . $row->page_name ?>" alt="Book Image">
</li>
<?php endforeach ?>
<?php endif ?>
</ul>
JavaScript
$("#book-list li").click(function(e) {
var target = e.target;
var src = target.src;
$("#showcase-book-img").fadeOut(function() {
$(this).on('load', function() {
$(this).fadeIn();
});
$(this).attr("src", src);
});
$("#book-list li").removeClass("active");
$(this).addClass("active");
});
$("#left-arrow").click(function(){
if($("#book-list li.active").next("#book-list li").length>0){
$("#book-list li.active").next().trigger("click");
} else {
$("#book-list li:first").trigger("click");//go to first
}
return false;
});
$("#right-arrow").click(function(){
if($("#book-list li.active").prev("#book-list li").length>0){
$("#book-list li.active").prev().trigger("click");
} else {
$("#book-list li:last").trigger("click");//go to end
}
return false;
});
$("#book-list li:first").trigger("click");
It was wrong: You were firing event in li element. It has to be applied over its images.
Here the forking correction.
How can I hide all the images in a recordset except the image with the mouse hover on?
Images are displayed from the database and I am trying to manipulate how the images respond when a user hovers on any particular image.
Based on what I have read here on stackoverflow I came up with the following that actually works but with one limitation
On page load it works fine but once you start moving from image to image nothing happens.
I want only the active or image with hover to show while hiding the rest.
$(document).ready(function() {
$('.teamDisplay').hover(function(){
var infoFont = $(".imageDiv")
var $imgLink = $(this).children(infoFont).attr("data-imgPath");
$('.memberPicBg').css('background-image', 'url(' + $imgLink + ')');
$('.teamDisplay').addClass('imageDivOff');
$(this).addClass('imageDivOn');
}, function(){
$('.memberPicBg').css('background-image', 'url(' + $imgLink + ')');
$('.teamDisplay').addClass('imageDivOn');
$(this).addClass('imageDivOff');
});
});
I am also using css to show or hide the images but the hover function appears to work just once on page load.
How do I trigger this hover function each time a new image has focus?
This is the website with the feature I hope to replicate
UPDATE
The html code
`<div class="memberPicBg">
<?php do { ?>
<span class="teamDisplay">
<?php
// Show If File Exists (region1)
if (tNG_fileExists("../images/team/", "{members.tmemberphoto}")) {
?>
<span class="imageDiv" data-imgPath="../images/team/<?php echo $row_members['tmemberphoto']; ?>">
<span class="teamMemberNameH"><?php echo $row_members['tmember']; ?></span>
<span class="teamMemberTitleH"><?php echo $row_members['tmemberposition']; ?></span><br /><br />
<img src="../images/team/<?php echo $row_members['tmemberphoto']; ?>" alt="<?php echo my_meta_description($row_members['tmember'],6); ?>" border="0" /> </span>
<?php
// else File Exists (region1)
} else { ?>
<span class="teamMemberNameH"><?php echo $row_members['tmember']; ?></span>
<span class="teamMemberTitleH"><?php echo $row_members['tmemberposition']; ?></span>
<?php }
// EndIf File Exists (region1)
?>
</span>
<?php } while ($row_members = mysql_fetch_assoc($members)); ?>
</div>`
NB: apologising if I am not clear enough.
I made a simple image gallery, I'm adding a password protected upload. With some help I'm using this php (thanks to sulthan-allaudeen). Attached the code I'm using.
The problem is that I can't find a way to have on the left side the thumbnails of all the images in the folder, but with this code I have the full-width images only. any idea?
thanks
<body>
<div id="containerfoto">
<div id="gallery">
<div id="minipics">
<?php
$dir = 'Images/photo/';
$files = scandir($dir);
$i = 1;
foreach ($files as $key)
{
if ($i>3)
{
$j = $i-3;
echo "<a href='Images/photo/".$key."'><img src ='Images/photo/".$key."'>".$key."</a>";
}
$i++;
}
?>
<div style="clear:left"> </div>
</div>
<div id="zoom">
<img src="Images/foto/foto7.jpg" id="bigimage" alt="">
<h3 id="titolo">Click to enlarge images.</h3>
</div>
</div>
</div>
<script>
window.onload=function(){
if(!document.getElementById || !document.getElementsByTagName) return;
links=document.getElementById("minipics").getElementsByTagName("a");
for(i=0;i<links.length;i++)
links[i].onclick=function(){Show(this);return(false)}
}
function Show(obj){
bigimg=document.getElementById("bigimage");
bigimg.src=obj.getAttribute("href");
smallimg=obj.getElementsByTagName("img")[0];
t=document.getElementById("titolo");
t.removeChild(t.lastChild);
t.appendChild(document.createTextNode(smallimg.title));
}
</script>
</body>
Scandir() put's the file names within your directory into an array. Therefore, we can print each image using a for loop. I've given you an example below:
<?php
$dir = 'Images/photo/';
$files = scandir($dir);
for($number = 0; $number <= count($files); $number++) { ?>
<div class="thumbnail">
<img src="<?php echo $dir; echo $files{$number} ?>">
</div>
<?php } ?>
Now you just need to apply some css to the .thumbnail class and it should do the trick. For starters, you just need to apply some width and height to .thumbnail img, let me know if you need help with that too.
I have a div containing php that loads a random image from a directory. This bit works fine when i reload the page. The code:
<div id="imageArea">
<?php
$dir = 'images/assets/';
$images = scandir($dir);
$i = rand(2, sizeof($images)-1);
?>
<img src="images/assets/<?php echo $images[$i]; ?>" alt="<?php echo str_replace(array('.jpg', '.png', '.gif'), '', $images[$i]); ?>"/>
</div>
And further down the page i have another div that contains a button. I want it so that when people click this button it loads a new random image, i guess it would reload the div, but i don't want it to reload the page, is that possible? The button:
<div id="newPic">
<input type="button" value="Reload" id="Reload"/>
</div>
I have tried:
<script>
$(document).ready(function(){
$("#Reload").click(function(){
$("#imageArea").html("result reloaded successfully");
});
});
</script>
and:
$(document).ready(function(){
$("#Reload").click(function(){
$("#imageArea").html(ajax_load).load(loadUrl);
});
});
I am new to php and javascript and so i have been following other peoples instructions.
Thank you
split your php script to another file (just echo the img tag), and then use ajax to call that page.
$("#reload").click(function(){
$.ajax({
url:"demo.php",success:function(ajax_load){
$("#imageArea").html(ajax_load)
}});
});
php file
<?php
$dir = 'images/assets/';
$images = scandir($dir);
$i = rand(2, sizeof($images)-1);
?>
<img src="images/assets/<?php echo $images[$i]; ?>" alt="<?php echo str_replace(array('.jpg', '.png', '.gif'), '', $images[$i]); ?>"/>
have you tried to use ajax to update the div with the image?
here's the code
$(document).ready(function(){
$('#clickme').click(function(){
var number = 1 + Math.floor(Math.random() * 10);
$('#contentimg').attr('src','0'+number+'.jpg');
});
});
this would work given that the images are in the same folder else give the src of image accordingly