image retrieval from directory and session variable issues - php - javascript

I have a problem when retrieving the images from a directory on my server, so what the main sequence is: in a page (multiupload.php) I added the input, allowed the image to be previewed and when the user submitted, a new directory with their session id would be created, the images would then be stored in the unique directory and the page would then be directed to (drag.php). The newly loaded page has a canvas with different divs to controls filters that are attached to that canvas. My problem lies with retrieving the image with the specified s_id as a directory name from one page to the other.
Q: Am i retrieving session variables properly? or using them appropriately?
This is the necassary snippets from multiupload.php's upload script.
<?php
$dir_id = session_id(md5(uniqid()));
session_start($dir_id);
$path = "uploads/";
$dir = $path.$dir_id;
$path = $path.$dir_id."/";
if (file_exists($dir)) {
system('/bin/rm -rf ' . escapeshellarg($dir));
} else {
mkdir($path);
chmod($path, 0722);
}
$_SESSION["id"] = $dir_id;
$_SESSION["directory"] = "/" . $dir;
$_SESSION["path_name"] = $path;
?>
I define the directory, whole path and the id for the directory. I would like to retrieve the id in the next page, but it's not doing it correctly.
and this is the retrieval code from drag.php
$realPath = 'uploads/'. echo $_SESSION['id'];
$handle = opendir(dirname(realpath(__FILE__)).$realPath;
while($file = readdir($handle)){
if($file !== '.' && $file !== '..'){
echo '<img src="uploads/'.$file.'" border="0" />';
}
}
My end result is that I would like all images to be drawn on the page. For now I would like them to be drawn anywhere aslong as they're visible.
If my question isn't clear, feel free to edit or comment where I should change. If you need more code or information, please let me know.

Please modify your code to this code:
<?php
$dir=$_SESSION['id'];
$realPath = '/uploads/'.$dir;
$handle = opendir(dirname(realpath(__FILE__)).$realPath);
while($file = readdir($handle)){
if($file !== '.' && $file !== '..'){
echo '<img src="'.$realPath.'/'.$file.'" border="0" width="200" />';
}
}
?>
I have use this code an I get the o/p like this:

<?php
$dir_id = session_id(md5(uniqid()));
session_start();
$path = "uploads/";
$dir = $path.$dir_id;
$path = $path.$dir_id."/";
if (file_exists($dir)) {
system('/bin/rm -rf ' . escapeshellarg($dir));
} else {
mkdir($path);
chmod($path, 0722);
}
$_SESSION["id"] = $dir_id;
$_SESSION["directory"] = "/" . $dir;
$_SESSION["path_name"] = $path;
?>
In any file.php, which u need get session:
<?php
session_start();
$realPath = 'uploads/'.$_SESSION['id'];
$handle = opendir(dirname(realpath(__FILE__)).$realPath;
while($file = readdir($handle)){
if($file !== '.' && $file !== '..'){
echo '<img src="uploads/'.$file.'" border="0" />';
}
}
?>
I advice to you read that: http://www.w3schools.com/php/php_sessions.asp when i was started with php 6 years ago - it was rly helpful

session_start does not take any argument. It's just to put a cookie and to read the session variables. (exposed in $_SESSION). You have to use session_start() on every pages to be able to read the $_SESSION variables.

this will give only image file from directory using session variable.
<?php
$dir=$_SESSION['id'];
$realPath = '/uploads/'.$dir;
$handle = opendir(dirname(realpath(__FILE__)).$realPath);
while($file = readdir($handle)){
if($file !== '.' && $file !== '..'){
if(fnmatch('*.jpg', $file) || fnmatch('*.png', $file) || fnmatch('*.jpeg', $file)){
echo '<img src="'.$realPath.'/'.$file.'"/>';
}
}
}
?>

Related

Returning array values (image file names to javascript) from php

Hi I have a php file which is reading all the image files in a directory as so:
<?php
$dir = "Images/";
$arrayjs = array();
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
if($file != "." && $file != ".."){
$arrayjs[] = $file;
echo "filename:" . $file . "<br>";
}
}
closedir($dh);
}
}
header('Content-type:application/json;charset=utf-8');
echo json_encode($arrayjs);
?>
and I want to get the resulting array in javascript. This code is not working. Any idea why?
<script type = "text/javascript">
$(function() {
$.getJSON('fileNames.php', function(data) {
console.log('yaa');
$(data).each(function(key, value) {
console.log(value);
});
});
});
</script>
getJson performs an ajax call, which will read the contents of the file as its written/displayed, so your echo "filename:" . $file . "<br>"; is becoming part of that meaning your json is becoming invalid
comment out that line and you should be fine
<?php
$dir = "Images/";
$arrayjs = array();
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
if($file != "." && $file != ".."){
$arrayjs[] = $file;
//echo "filename:" . $file . "<br>";
}
}
closedir($dh);
}
}
header('Content-type:application/json;charset=utf-8');
echo json_encode($arrayjs);
?>
The method wants nothing but valid json to be echo'd/displayed

Delete file from a directory with php NO DATABASE

I am stuck on my codes from 2 days now. I have already tried more then 100 tutorials/guide but none of them solve my problem. Mostly guide is for database.
I am using ready made gallery plugin to display images on my website. This gallery does not use database. For that I made admin panel with upload function. Now i am looking for function to delete uploaded photos from admin panel. one pic at a time or multiple option will be more then good.
Right now with this code i am displaying images in Admin Page at main.php which i uploaded before:
<?php
$folder_path = 'gallery-images/'; //image's folder path
$num_files = glob($folder_path . "*.{jpeg,jpg,gif,png,bmp}", GLOB_BRACE);
$folder = opendir($folder_path);
if($num_files > 0)
{
while(false !== ($file = readdir($folder)))
{
$file_path = $folder_path.$file;
$extension = strtolower(pathinfo($file ,PATHINFO_EXTENSION));
if($extension=='jpg' || $extension =='png' || $extension == 'gif' || $extension == 'bmp')
{
?>
<img src="<?php echo $file_path; ?>" height="250" />
<?php
}
}
}
else
{
echo "the folder was empty !";
}
closedir($folder);
?>
And i am trying this delete code in delete.php
<?php
$filename = $_POST['fname'];
$path = $_POST['directory'];
if(file_exists($path."/".$filename)) {
unlink($path."/".$filename); //delete file
}
?>
So i need a function to delete file from server with confirmation and with delete button. Right now file just open with a click. This function will be only for admin, So i think i am safe with delete function as i read in similar topics.
Thanks in Advance.
EDIT 1:
So far this code successfully delete a file from server (Answer from #Jocelyn):
<h3>Delete Now!</h3>
<?php
if(isset($_GET['delete']))
{
unlink(__FILE__);
}
?>
Change this unlink(__FILE__); to unlink("$file_path");
EDIT 2:
Sorry, it does delete file from server but its deleting all the files in that directory.
Is there anyway to delete only one file which i click.
Right now all photos appearing from one link of code, i think thats the problem.
The link is this from which photos are appearing:
<img src="<?php echo $file_path; ?>" height="250" />
A very quickly cobbled together example of how you might achieve your goal using ajax to send the filename to the delete.php script. No doubt that because it's not tested there may well be issues - but it's a starting point.
<?php
/* delete.php */
$img=!empty( $_GET['name'] ) ? $_GET['name'] : false;
$result=false;
if( $img ){
/*
here you would typically check that the path sent via ajax exists
and then use unlink to delete the file before sending a response
to the ajax callback function - the callback would then inform the
user that the file has been deleted ( or not! )
For testing though a simple message will suffice so that files are not deleted unnecessarily!!!
-- uncomment the line below to actually attempt deletion of file.
*/
if( file_exists( $img ) ){
#$result = #unlink( $img );
clearstatcache();
}
echo $result ? 'The file '.$img.' was deleted' : 'The file '.$img.' could not be deleted';
}
?>
<?php
$root='c:/wwwroot';
?>
<!-- /* admin page that lists images */ -->
<html>
<head>
<title>Delete images - no database</title>
<script>
function ajax(imagename,callback){
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if( xhr.status==200 && xhr.readyState==4 ){
callback.call( this, xhr.response );
}
};
xhr.open( 'GET', 'delete.php?name='+imagename, true );
xhr.send();
}
function deleteimage(e){
e.preventDefault();
ajax.call( this, e.target.dataset.path+'/'+e.target.dataset.name, cbdeleteimage );
}
function cbdeleteimage(r){
alert( r );
}
function bindEvents(){
var col=document.querySelectorAll('img.delete');
for( var n in col )if( col[ n ].nodeType==1 ) col[n].addEventListener( 'click', deleteimage, false );
}
document.addEventListener( 'DOMContentLoaded', bindEvents, false );
</script>
</head>
<body>
<?php
$dir = 'gallery-images/'; /* YOUR path */
$dir = $root . '/images/misc/'; /* MY test path */
$files=preg_grep( '#(\.jpg|\.jpeg|\.png|\.bmp|\.gif)#i', glob( $dir . '*.*' ) );
$html=array();
foreach( $files as $file ){
if( $blocal ) $file=str_replace( $root, '', $file ); /* remove MY site root from file names */
$name = pathinfo( $file, PATHINFO_BASENAME );
$path = pathinfo( $file, PATHINFO_DIRNAME );
$html[]="<img class='delete' src='{$file}' data-name='{$name}' data-path='{$path}' />";
}
echo implode( PHP_EOL, $html );
?>
</body>
</html>
So this is the final code which is perfectly fine for noobs like me who stuck with their work:
this is Delete.php to delete only a requested file
<?php
$file = $_GET['delete'];
if(isset($_GET['delete']))
{
unlink("./gallery-images/$file");
header("Location:home.php");
}
?>
This is upload.php to upload file with rename to auto increment value:
<?php
// Upload and Rename File
if (isset($_POST['submit']))
{
$filename = $_FILES["file"]["name"];
$file_basename = substr($filename, 0, strripos($filename, '.')); // get file extention
$file_ext = substr($filename, strripos($filename, '.')); // get file name
$filesize = $_FILES["file"]["size"];
$allowed_file_types = array('.png','.jpg','.jpeg');
$count = count (glob ('gallery-images/*'));
if (in_array($file_ext,$allowed_file_types) && ($filesize < 10000000))
{
// Rename file
$newfilename = ($count + 1) . $file_ext;
if(file_exists("gallery-images/" . $newfilename))
{
// file already exists error
echo "You have already uploaded this file.";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"], "gallery-images/" . $newfilename);
header("Location: home.php");
exit;
}
}
elseif (empty($file_basename))
{
// file selection error
echo "Please select a file to upload.";
}
elseif ($filesize > 10000000)
{
// file size error
echo "The file you are trying to upload is too large.";
}
else
{
// file type error
echo "Only these file typs are allowed for upload: " . implode(', ',$allowed_file_types);
unlink($_FILES["file"]["tmp_name"]);
}
}
?>
This is home.php to display image with delete feature:
Upload Form:
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload: <br />
<input type="file" name="file" id="file"><br /><br />
<input type="submit" value="Upload Image" name="submit">
</form>
Display photos from directory:
<?php
$folder_path = 'gallery-images/'; //image's folder path
$num_files = glob($folder_path . "*.{jpeg,jpg,png}", GLOB_BRACE);
$folder = opendir($folder_path);
$file = '$file_path';
if($num_files > 0)
{
while(false !== ($file = readdir($folder)))
{
$file_path = $folder_path.$file;
$extension = strtolower(pathinfo($file ,PATHINFO_EXTENSION));
if($extension=='jpg' || $extension =='png' || $extension == 'jpeg' || $extension == 'bmp')
{
?>
<img src="<?php echo $file_path; ?>" height="175" />
<?php
}
}
}
else
{
echo "the folder was empty !";
}
closedir($folder);
?>
Delete confirmation popup script:
<script>
function deleletconfig(){
var del=confirm("Are you sure you want to delete this record?");
if (del==true){
}
return del;
}
</script>
Hope this will be helpful for learners.
Thanks.

Javascript array for all the files in a directory

I need to assign the list of all files of a directory (site_img) to a javascript array but not getting any luck.Can any one pls help .
i:e In the below code I want to assign the value of filename to an javascript array in each iteration of the for loop.
<?php
foreach(glob('./site_img/*.*') as $filename){
echo $filename;
echo "<br>";
}
?>
With PHP, here is a snippet that I use on one of my sites:
<?
$fileList = '';
$homePath = "a5780630"; //Dev
$homePath = "a2092434"; //Live
if ($handle = opendir('/home/'. $homePath .'/public_html/images/gallery/')) {
/* This is the correct way to loop over the directory. */
while (false !== ($file = readdir($handle))) {
if ($file != '.' && $file != '..') {
$fileList = $fileList . ',' . $file;
}
}
closedir($handle);
}
?>
That will give you a comma delimited string of all the files. Then in JS:
<script language="javascript">
var listOfImages = "<?php echo $fileList; ?>"
listOfImages = listOfImages.split(",");
</script>

How to send image from main page to another?

I have been searching for this answer for days and cannot come across an answer. Maybe because i do not understand them and can not apply them to what i am trying to do.
i am using php to save images on the server when the user presses submit and when that happens, i would like the image to appear on the next page in the image src. As you can see that the name of my next page is random but similar to my image name aside from the extensions. So i was wondering if that would play a part in helping me do something? as at the end of my php i go straight to the random stringed page that was created.
function findexts ($filename) {
$filename = $_FILES["file"]["name"];
$exts = split("[/\\.]", $filename) ;
$n = count($exts)-1;
$exts = $exts[$n];
return $exts;
}
if(isset($_POST['submit'])){
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 3000000)
&& in_array($extension, $allowedExts)) {
if ($_FILES["file"]["error"] > 0) {
//echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else {
$ext = findexts ($_FILES['file']['name']) ;
$newName = generateRandomString();
$fileName=$newName.".".$ext;
while (is_file("upload/" . $fileName)){
$newName = generateRandomString();
$fileName=$newName.".".$ext;
}
$target = "upload/";
move_uploaded_file($_FILES["file"]["tmp_name"],
$target . $fileName);
$newfile = fopen("img/" . $newName.".html", "w") or die("Unable to open file!");
$newImgWeb = $newName.".html";
copy("img/template.html","img/" . $newImgWeb);
fclose($newfile);
header("Location: img/$newImgWeb");
}
} else {
//echo "Invalid File"
}
} else {
}
this is my php and i don't know how i would go about doing it?
my html and php are seperate too, but are linked under the form action="upload_file.php"
<img src="../upload/<?php echo $fileName ?>">
but i'm just getting a bunch of errors, i have no clue on what i should do next. I'm just a beginner and learning a lot through doing this.
Also, i tried doing this in javascript where i would take the url of the current webpage, remove the begining url and leave with the end. So it would be like "adSEvF3A.html" then i removed the ".html" part and from there i couldn't identify which extensions to look for .png .jpg etc. so i couldn't do document.getElementById('image').src=newImg;
Thanks in advance!
I had realised that i needed to put
session_start();
at the begining of the php file that i want to obtain the variable from. When i was working with session_start(); i had done it all wrong, and thought that $_SESSION had to always be declared right below session_start(); i know many of you will think it's stupid to think that. But hey, at least i figured it out.
test1.php
session_start();
$var = "hello.jpg";
$_SESSION['image'] = $var;
the variable that i wanted to declare needed to be above the $_SESSION so that it can be stored inside it.
index.html
<?php
include ('test1.php');
$image = $_SESSION['image'];
?>
<img src="upload/<?php echo $image ?>">
and then it worked.
Thanks CMKanode for helping me!

how to know all file names of the images from whole website?

I want to get all images of my whole website in an array, and all of my images are in a folder called images and within that folder many subfolders are there, So now how can I get all the images' path in an array?
Is it possible just with jquery, javascript? If not, php is ok.
I found this recursive function that can give you the tree of a given directory, you can use the $exclude param to filter only image files
<?php
/**
* Get an array that represents directory tree
* #param string $directory Directory path
* #param bool $recursive Include sub directories
* #param bool $listDirs Include directories on listing
* #param bool $listFiles Include files on listing
* #param regex $exclude Exclude paths that matches this regex
*/
function directoryToArray($directory, $recursive = true, $listDirs = false, $listFiles = true, $exclude = '') {
$arrayItems = array();
$skipByExclude = false;
$handle = opendir($directory);
if ($handle) {
while (false !== ($file = readdir($handle))) {
preg_match("/(^(([\.]){1,2})$|(\.(svn|git|md))|(Thumbs\.db|\.DS_STORE))$/iu", $file, $skip);
if($exclude){
preg_match($exclude, $file, $skipByExclude);
}
if (!$skip && !$skipByExclude) {
if (is_dir($directory. DIRECTORY_SEPARATOR . $file)) {
if($recursive) {
$arrayItems = array_merge($arrayItems, directoryToArray($directory. DIRECTORY_SEPARATOR . $file, $recursive, $listDirs, $listFiles, $exclude));
}
if($listDirs){
$file = $directory . DIRECTORY_SEPARATOR . $file;
$arrayItems[] = $file;
}
} else {
if($listFiles){
$file = $directory . DIRECTORY_SEPARATOR . $file;
$arrayItems[] = $file;
}
}
}
}
closedir($handle);
}
return $arrayItems;
}
?>
source
And about the jQuery way, you can't access to the directory directly, you have to provide the list with an ajax call to your backend and give a json object so you render it with jQuery
try this PHP Script:
$dir = "images/*/";
//get all files with .jpg
$images = glob("" . $dir . "*.jpg");
$imgs = array();
// store images in $imgs - after that optional display
foreach($images as $image) {
$imgs[] = $image;
}
//display
foreach ($imgs as $img) {
echo '<img src="'.$img.'" />';
}
to store in a JS array:
$JSarray = json_encode($imgs);
echo "var JSarray = ". $JSarray . ";\n";
Use RecursiveDirectoryIterator , RecursiveIteratorIterator and RegexIterator to achieve this .
$imagesExtensions = array('jpg','png','gif'); //<=-- Add your extensions
$extensions = implode('|',$imagesExtensions);
$directory = new RecursiveDirectoryIterator('images');
$iterator = new RecursiveIteratorIterator($directory);//RecursiveDirectoryIterator::SKIP_DOTS);
$regex = new RegexIterator($iterator, "/^.+\.$extensions$/i", RecursiveRegexIterator::GET_MATCH);
foreach ($regex as $filename=>$object) {
echo $filename . '<br>';
$images[] = $filename; //<----- All images are stored in this array sequentially
}
OUTPUT :
images\google\client\ext\resources\themes\images\access\boundlist\trigger-arrow.png
images\google\client\ext\resources\themes\images\access\box\corners-blue.gif
images\google\client\ext\resources\themes\images\access\box\corners.gif
//....... Goes on..

Categories

Resources