Image and Link Uploader and Drop And Drag PHP Javascript

Post Reply
darknkreepy3#
Site Admin
Posts: 253
Joined: Tue Oct 27, 2009 9:33 pm

Image and Link Uploader and Drop And Drag PHP Javascript

Post by darknkreepy3# »

Here's The scripting to allow Javascript and PHP to work with AJAX and Jquery to have drop and drag listed images with links that store in a text file.

The fun parts in this program are:
Using Jquery to make drop and drag sortable DIV objects
Saving a jpeg checked in size and type to a name a user makes to the img/ folder
deleting existing images or nothing if a new node and then deleting the dom parent->child (node to delete)
Making jquery calls from javascript for deleting items and saving them too
Using querySelectorAll to find all items with wildcard expressions for similar IDs

I made a structure you can change but you need:

[site]
|_____iconz
|_____mS
-----|_____home
----------|_____img
|_____menus
|_____php

del_16px.png image in [iconz]
homeImgs.txt in [menus]
menu.php routines for newline array text file stuff [php]

edit_homeImgs.php

Code: Select all

<?php
	/*
	edit_homeImgs.php v1.0 by Kristoffe Brodeur. ©2015 All Rights Reserved.
	10-20-2015
	*/
	$to_root="../../";
	require $to_root."php/menu.php";
	$cssHead='<link type="text/css" rel="stylesheet" href="homeImgs.css" />';
	$imgListFile=$to_root."menus/homeImgs.txt";
	$existingStr="";
	$iconSize="240";
	//
	if(file_exists($imgListFile))
		{
		$imgArr=readMenuArray($imgListFile);
		$c=count($imgArr);
		//
		for($a=0;$a<$c;$a++)
			{
			$tmpArr=explode(",",$imgArr[$a]);
			$dirStr=$tmpArr[0];
			$fileTgt="img/".$dirStr.".jpg";
			//
			if(!file_exists($fileTgt))
				{
				$fileTgt="img/_noimageyet.jpg";
				}
			$imgFile="<img src='$fileTgt' width='".$iconSize."px' />";
			
			$boxStr="i_$a";
			$existingStr.="
				<div class='imgBox' id='$boxStr'>
					<div class='aTitle'>Delete<br /><img src='".$to_root."iconz/del_16px.png' onclick='delBox(\"".$boxStr."\",\"".$dirStr."\");' /></div>
					<div class='imgIcon'><div id='img".$a."'>$imgFile</div><br />
						<input type='button' value='ADD IMAGE' onclick='init_upload(\"img".$a."\",\"".$dirStr."\");'>
					</div>
					<div class='imgName'>Image Filename<br /><input id='_name[]' name='_name[]' size='16' value='".$tmpArr[0]."' readonly></div>
					<div class='imgLink'>HYPERLINK <input name='_link[]' size='48' value='".$tmpArr[1]."'></div>
					<div class='clearBoth'></div>
				</div>
			";
			}
		}
	else
		{
		
		}
?>

<?php require $to_root."mS/widgets/admin_htmldec.php";?>
	<body>
		<div id="wrap">
			<div id='upload_image'>
			
				<input class="b_floatLeft" type="button" value="ADD AREA" onclick="addGroup();">
			
				<div id='upload_formArea'>
					<fieldset>
						<legend id='legendArea'>UPLOAD IMAGE</legend>
						<form name='upImg' id='upImg' enctype='multipart/form-data' method='POST' action=''>
							<input type='file' name='imgFile' id='imgFile'>
							<input type='hidden' id='dirArea' name='dirArea' value=''>
							<input type='submit' value='SUBMIT' >
							</form>
					</fieldset>
				</div>
				<div id="debug">debug area</div>
				<div id="previewArea"></div>
				<input type="button" value="SAVE" onclick="checkImgNames();">
			</div>
			Existing Images and Links for Homepage Slider At Top<hr />
			
			<form name="existing" id='existing' method="POST" action="save_homeImgs.php">
				<div id="imgListObj"><?php echo $existingStr;?></div>
			</form>
		</div>
	</body>
</html>

<script>
	var iconSize="<?php echo $iconSize;?>";
	var imgListObj=document.getElementById('imgListObj');
	var debug=document.getElementById('debug');
	var form_existing=document.getElementById('existing');
	$('#imgListObj').sortable();
	var nID=-1;
	var replaceImgID="";
	var upload_formArea=document.getElementById('upload_formArea');
	var imgFileName="";
	//
	function delBox(sBox,sTitle)
		{
		//
		if(confirm("delete ["+sBox+":"+sTitle+"]?"))
			{
			var delNode=document.getElementById(sBox);
			delNode.parentNode.removeChild(delNode);
			//
			if(sTitle!="-----")//new node without image saved
				{
				JQ_delImg(sTitle);//delete associated image from img/ folder
				}
			}
		}
	//
	function init_upload(sID,sFile)
		{
		replaceImgID=sID;
		imgFileName=sFile;
		//don't need this now
		newImgArr=sFile.split("^");
		var dirArea=document.getElementById('dirArea');
		var legendArea=document.getElementById('legendArea');
		dirArea.value=sFile;
		legendArea.innerHTML="UPLOAD IMAGE | "+sFile;
		}
	//
	function check_img()
		{
		//check whether client browser fully supports all File API
		if (window.File && window.FileReader && window.FileList && window.Blob)
			{
			//alert("check_img");
			var fileInp=document.getElementById('imgFile');
			var file=fileInp.files[0];
			var fSize=file.size;
			var fType=file.type;
			//
			switch(fType)
				{
				case 'image/jpeg':
					break;
				default:
					debug.innerHTML=("["+fType+"] Unsupported file type. JPG only");
					return false;
				}
			//
			var fMax=2*1024*1024;//2mb php default, can be changed in php.ini and server side files per folder
			//alert(fSize+":"+fMax);
			//
			if(fSize>fMax)
				{
				//alert("too big");
				debug.innerHTML=("Filesize too big. "+fMax+" : "+fSize);
				return false;
				}	
			else
				{
				debug.innerHTML=("Filesize ok. "+fMax+" : "+fSize);
				}
			}
		else
			{
			//Error for older unsupported browsers that doesn't support HTML5 File API
			alert("Please upgrade your browser, because your current browser lacks some new features we need!");
			}
		}
	//
	function img_ok(sentData)
		{
		//alert("ok");
		debug.innerHTML=sentData;
		var previewArea=document.getElementById('previewArea');
		var imgDiv=document.getElementById('img_'+newImgArr[1]);
		var newImg="<?php echo $to_root;?>mS/home/img/"+imgFileName+".jpg?r="+new Date().getTime();
		var imgStr="<img src='"+newImg+"' width='<?php echo $iconSize;?>px' />";
		var repImg=document.getElementById(replaceImgID);
		repImg.innerHTML=imgStr;
		previewArea.innerHTML=imgStr;
		imgDiv.innerHTML=imgStr;
		}
	//
	function img_deleted(sentData)
		{
		debug.innerHTML=sentData;
		}
	//
	$(document).ready(function()
		{
		//
		$("form#upImg").submit(function(event)
			{
			event.preventDefault();
			var formData=new FormData($(this)[0]);
			//
			$.ajax(
				{
				url:			'save_homeImg.php',
				type:			'POST',
				data:			formData,
				async:			false,
				cache:			false,
				contentType:	false,
				processData:	false,
				beforeSend:		check_img,
				success:		img_ok
				});
			return false;
			});
		//
		JQ_delImg=function(sImg)
			{
			$.ajax(
				{
				url:		'del_homeImg.php',
				type:		'POST',
				data:		'img='+sImg,
				success:	img_deleted
				});
			return false;
			};
		});
	//
	function addGroup()
		{
		nID++;
		imgListObj.innerHTML+="<div class='imgBox' id='n_"+nID+"'><div class='aTitle'>Delete<br /><img src='<?php echo $to_root;?>iconz/del_16px.png' onclick='delBox(\"n_"+nID+"\",\"-----\");' /></div><div class='imgIcon' id='new"+nID+"' ><img src='img/_null_.jpg' width='"+iconSize+"px' /><br /></div><div class='imgName'>Image Filename<br /><input id='_name[]' name='_name[]' size='16' value='' ></div><div class='imgLink'>HYPERLINK <input name='_link[]' size='48'></div><div class='clearBoth'></div></div>";		
		}
	//
	function checkImgNames()
		{
		var imgListObj=document.getElementById('imgListObj');
		var newBoxArr=imgListObj.querySelectorAll(".imgBox");
		var lenB=newBoxArr.length;
		var newTestArr=new Array();
		var allNamesArr=new Array();
		//
		for(var a=0;a<lenB;a++)
			{
			//make an array of all image filenames so any redundancy can be stopped before saving
			var tmpArr3=newBoxArr[a].querySelectorAll('[id^="_name"]');
			//
			if(tmpArr3.length>0)
				{
				allNamesArr.push(tmpArr3[0]);
				}
			
			var tmpArr=newBoxArr[a].querySelectorAll('[id^="new"]');//new nodes made from the ADD button
			//
			if(tmpArr.length>0)
				{
				var tmpArr2=newBoxArr[a].querySelectorAll('[id^="_name"]');//the _name[] input field
				if(tmpArr2.length>0)
					{
					if(tmpArr2[0].value=="")//is it still empty? a name is needed to rename the uploaded image later
						{
						newTestArr.push(tmpArr2[0]);
						}
					}
				}
			}
		var emptyTest=0;
		var redun=0;
		var alertMsg="";
		var alertCnt=0;
		//
		if(newTestArr.length>0)
			{
			alertCnt++;
			alertMsg=alertCnt+"). Please Fill In Image Filename For New Images\n";
			}
		var len3=allNamesArr.length;
		//
		for(var r=0;r<len3;r++)
			{
			for(var c=0;c<len3;c++)
				{
				//
				if(r!=c)
					{
					//debug.innerHTML+=allNamesArr[r].value+":"+allNamesArr[c].value+"<br />";
					//
					if(allNamesArr[r].value==allNamesArr[c].value)
						{
						redun=1;
						debug.innerHTML="REDUNDANT NAME:"+allNamesArr[c].value+"<br />";
						}
					}
				}
			}
		//
		if(redun==1)
			{
			alertCnt++;
			alertMsg+=alertCnt+"). Image Filename Redundancy. All filenames must be unique.";
			}
		//
		if(alertMsg=="")
			{
			form_existing.submit();
			}
		else
			{
			alert(alertMsg);
			}
		}
</script>
del_homeImg.php

Code: Select all

<?php
	/*
	del_homeImg.php v1.0 by Kristoffe Brodeur. ©2015 All Rights Reserved.
	10-26-2015
	!empty finds if isset and !empty at once, no need for both
	*/
	//
	if(!empty($_POST['img']))
		{
		$img=$_POST['img'];
		$file="img/".$img.".jpg";
		$result=unlink($file);
		}
	else
		{
		$result="nothing sent to delete";
		}
	echo $result;//sent back to ajax and javascript/jquery
?>
save_homeImg.php

Code: Select all

<?php
	/*
	save_homeImg.php v2.0 by Kristoffe Brodeur. ©2015 All Rights Reserved.
	10-20-2015
	*/
	//
	$to_root="../../";
	//
	if(isset($_POST['dirArea']))
		{
		$dirArea=$_POST['dirArea'];
		$path="img/";
		$imgName=strtolower($_FILES['imgFile']['name']);
		$imgSize=$_FILES['imgFile']['size'];
		$uploadedName=$_FILES['imgFile']['tmp_name'];
		echo "name:$imgName|size:$imgSize";
		//
		if(!is_dir($path))
			{
			mkdir($path);
			}
		$newName=$dirArea.".jpg";	
		//
		if(move_uploaded_file($uploadedName,$path.$newName))
			{
			echo "|1";//ok
			}
		else
			{
			echo "|0";//error
			}
		echo "|$dirArea";
		}
	else
		{
		echo "dirArea not set";
		}
?>
save_homeImgs.php

Code: Select all

<?php
	/*
	save_homeImgs.php v1.0 by Kristoffe Brodeur. ©2015 All Rights Reserved.
	10-26-2015
	*/
	$to_root="../../";
	$endChar="\n";//works for windows. maybe not linux
	$nodeStr="_name,_link";
	$nodeArr=explode(",",$nodeStr);
	$lenA=count($nodeArr);
	
	//
	for($a=0;$a<$lenA;$a++)
		{
		$tmp=$nodeArr[$a];
		${$tmp}=$_POST[$tmp];
		//echo $tmp."<br />";
		}
	$lenB=count($_name);
	$saveStr="";
	//
	for($b=0;$b<$lenB;$b++)
		{
		//echo $_name[$b]." | ".$_link[$b]."<br />";	
		$saveStr.=$_name[$b].",".$_link[$b];
		//
		if($b<$lenB-1)// no leftover endline causing a blank line
			{
			$saveStr.=$endChar;
			}
		}
	$file=$to_root."menus/homeImgs.txt";
	//
	if(file_exists($file))
		{
		fix_rights($file);
		}
	file_put_contents($file,$saveStr);
	fix_rights($file);
	//
	function fix_rights($sFile)
		{
		//windows testing and then linux hosting file owner bug fix
		//
		if(strtoupper(substr(PHP_OS,0,3))!='WIN') 
			{
			chown($sFile,posix_getuid());
			}	
		chmod($sFile,0755);
		}
?>

<script>
	location.href="<?php echo $to_root;?>mS/home/edit_homeImgs.php";
</script>
menu.php

Code: Select all

<?php
/*
menu.php v3 by kristoffe brodeur. ©2010 All Rights Reserved.
01-24-2010 made the function return an error instead of endlessly looping when then menu file does not exist
11-08-2010 added draw_menu to allow multiple menus listed easily ($to_root,$fName)
12-27-2010 added draw_menus
04-23-2011 fixed missing subMenu now combined menu.php versions
		   fixed newline and cr lf differences per server reading the txt files
04-30-2011 added a return array, [0] is string for html menu, [1] is the page to load by default
11-19-2011 photog jquery addition ad_gallery
*/
//
if(isset($_GET['sub']))
	{
	$sub=$_GET['sub'];
	}
else
	{
	$sub=-1;
	}
//-----
function readMenuArray($link)
	{
	//
	if(file_exists($link))
		{
		$handle=@fopen($link,"r");
		$txtfile="";
		//
		while(!feof($handle))
			{$txtfile.=fgets($handle,4096);}
		//$menuItems=split("[\n]", $txtfile);
		$txtfile=preg_replace('/\r\n|\r/', "\n", $txtfile);//are there differences in the newline? linux read the txt file, windows? etc... normalize just to \n
		$menuItems=preg_split("/[\n]/",$txtfile);
		}
	else
		{
		//split happens with 2 or more items, ergo the ending array item ""
		$menuItems=Array("-^-^error: $link does not exist^-\n","");
		}
	return($menuItems);
	}
//-----
function draw_links_acf($to_root)
	{
	$menuArr=readMenuArray($to_root."menus/links.txt");
	$lenM=count($menuArr);
	$menuStr="";
	//
	for($a=0;$a<$lenM;$a++)
		{
		$tempArr=explode("^",$menuArr[$a]);
		$link=$to_root.$tempArr[0];
		$menuStr.="
		<a href='$link'><img src='".$to_root."iconz/".$tempArr[1].".gif' /></a><br>
		";
		}
	return $menuStr;
	}
//-----
function draw_menu_acf($to_root)
	{
	$menuArr=readMenuArray($to_root."menus/main.txt");
	$lenM=count($menuArr);
	$menuStr="";
	//
	for($a=0;$a<$lenM;$a++)
		{
		$tempArr=explode("^",$menuArr[$a]);
		$link=$to_root.$tempArr[0].$tempArr[1];
		$menuStr.="
		<a href='$link'>".$tempArr[2]."</a>
		";
		}
	return $menuStr;
	}
//-----
function draw_menu($to_root,$fName)
	{
	$menuItems=readMenuArray($to_root.$fName);
	$len=count($menuItems);//defined in menu.php
	$menu='<div class="menu">|';
	//looping through the text file with ^ are the delimiter for folder^file^title^*(submenu-not used)
	for($a=0;$a<$len-1;$a++)
		{
		$parts=explode("^",$menuItems[$a]);//can't use ^ with split, have to use explode, unless you use \^ to escape the special character
		$addy=$parts[0].$parts[1];
		$menu.=' <a href="'.$to_root.$addy.'" />'.$parts[2].'</a> |';
		}
	$menu.="</div>";
	return $menu;
	}
//-----
function draw_menus($to_root,$folder,$sentStrArr)
	{
	//
	$tArr=split(",",$sentStrArr);
	$lenT=count($tArr);
	$menuStr="";
	//
	for($a=0;$a<$lenT;$a++)
		{
		$menuStr.=draw_menu($to_root,$folder."/".$tArr[$a].".txt");
		}
	return $menuStr;
	}
//-----
function subMenuGallery_adGallery($link)
	{
	//
	if(!isset($sub))
		{
		$sub=0;
		}
	$subPage="";
	$subMenuArr=readMenuArray($link);
	$subMenuStr="";
	$lenS=count($subMenuArr);
	//
	if(isset($_GET['sub']))
		{
		$sub=$_GET['sub'];
		}
	$firstGallery="";
	//
	for($s=0;$s<$lenS;$s++)
		{
		$tmpArr=split(",",$subMenuArr[$s]);
		$galleryCode=$tmpArr[0];//just the gallery name for the jquery version for now (not as versatile but quick for photog)
		$styleBeg="";
		$styleEnd="";
		//
		if($s==$sub)
			{
			$subPage=$tmpArr[0];
			$styleBeg="<span class='subSel'>";
			$styleEnd="</span>";
			//echo $subPage;
			}
		$subMenuStr.="
				<div class='subItem'>
					<a href='#' onclick='load_galleryStr(\"".$galleryCode."\");'>$styleBeg".$tmpArr[1]."$styleEnd</a>
				</div>";	
		}
	$subMenuArr[0]=$subMenuStr;
	$subMenuArr[1]=$sub;
	$subMenuArr[2]=$subPage;
	return $subMenuArr;	
	}
//-----
function subMenuGallery($link,$sub)
	{
	//
	if(!isset($sub))
		{
		$sub=0;
		}
	$subPage="";
	$subMenuArr=readMenuArray($link);
	$subMenuStr="";
	$lenS=count($subMenuArr);
	//
	if(isset($_GET['sub']))
		{
		$sub=$_GET['sub'];
		}
	$firstGallery="";
	//
	for($s=0;$s<$lenS;$s++)
		{
		$tmpArr=split(",",$subMenuArr[$s]);
		$galleryCode="gallery.php?f=".$tmpArr[0];
		$styleBeg="";
		$styleEnd="";
		//
		if($s==$sub)
			{
			$subPage=$tmpArr[0];
			$styleBeg="<span class='subSel'>";
			$styleEnd="</span>";
			//echo $subPage;
			}
		$subMenuStr.="
				<div class='subItem'>
					<a href='#' onclick='load_subMenuG(\"".$galleryCode."\",$s)'>$styleBeg".$tmpArr[1]."$styleEnd</a>
				</div>";	
		}
	$subMenuArr[0]=$subMenuStr;
	$subMenuArr[1]=$sub;
	$subMenuArr[2]=$subPage;
	return $subMenuArr;	
	}
//-----
function subMenu($link,$sub)
	{
	//
	if(!isset($sub))
		{
		$sub=0;
		}
	$subPage="";
	$menuStr="";
	$menuArr=array();
	$mainArr=readMenuArray($link);
	$lenS=count($mainArr);
	//
	if(isset($_GET['sub']))
		{
		$sub=$_GET['sub'];
		}
	$pages="";
	//
	for($s=0;$s<$lenS;$s++)
		{
		$subArr=split(",",$mainArr[$s]);
		$styleBeg="";
		$styleEnd="";
		//
		if($s==$sub)
			{
			$subPage=$subArr[0];
			$styleBeg="<span class='subSel'>";
			$styleEnd="</span>";
			//echo $subPage;
			}
	
		$menuStr.="
			<div class='subItem'>
				<a href='#' onclick='load_subMenu(\"".$subArr[0]."\",$s)'>$styleBeg".$subArr[1]."$styleEnd</a>
			</div>";		
		//
		$pages.=$subArr[0];
		//
		if($a<$len-2)
			{
			$pages.=",";
			}
		}
	$menuArr[0]=$menuStr;
	$menuArr[1]=$subPage;
	$menuArr[2]=$pages;
	return $menuArr;
	}
//-----
function robotSubMenu($link)
	{
	//hidden but gives good tracking for site
	$menuStr="<div id='robotSubMenu'>";
	$mainArr=readMenuArray($link);
	$lenS=count($mainArr);
	//
	for($s=0;$s<$lenS;$s++)
		{
		$subArr=split(",",$mainArr[$s]);
		$menuStr.="<a href='".$subArr[0]."'>".$subArr[1]."</a>";
		}
	$menuStr.="</div>";
	return $menuStr;
	}
?>
Post Reply