Jump to content

andrew_biggart

Members
  • Posts

    363
  • Joined

  • Last visited

  • Days Won

    1

Posts posted by andrew_biggart

  1. I have been wrecking my brain about this now for two weeks and cannot for the life of me figure out were I am going. I am only after some guidance, not asking someone to right my code for me.

     

    I have read dozens of tutorials and did a lot of research on this top as it is one of the key elements of my website, so I have to get it working properly. I have wrote a script which uploads and image, which I have got working fine. Now I am trying to add some code to resize the image and create a resized image.

     

    Once I have done that, I am going to be saving the original to an uploads folder, and saving the thumbnail to a thumbs directory.

     

    The problem that I am facing is that everything is working as intended apart from the imagecopyresampled() part of the script. When ever the new image is being created and saved into the thumbs directory, it is creating a pure black image every time.

     

    I cannot figure out why this is happening, can anyone point me in the right direction? Or spot something that I've missed?

     

     

    <?php
    session_start();
    
    $path_thumbs = "uploads/thumbs";
    $path_big        = "uploads";
    $createdby       = $_SESSION["ufullname"];		
    
    //the new width of the resized image, in pixels.
    
    $img_thumb_width = 570; // 
    
    $extlimit = "yes"; //Limit allowed extensions? (no for all extensions allowed)
    
    //List of allowed extensions if extlimit = yes
    
    $limitedext = array(".gif",".jpg",".png",".jpeg",".bmp");		
    
    //the image -> variables
    
    $file_type = $_FILES['pic']['type'];
    $file_name = $_FILES['pic']['name'];
    $file_size = $_FILES['pic']['size'];
    $file_tmp = $_FILES['pic']['tmp_name'];
    
    //check if you have selected a file.
    
    if(!is_uploaded_file($file_tmp)){
    
    	exit_status('Error: Please select a file to upload!');
    	exit(); //exit the script and don't process the rest of it!
    
    }
    
    //check the file's extension
    
    $ext = strrchr($file_name,'.');
    
    $ext = strtolower($ext);
    
    //uh-oh! the file extension is not allowed!
    
    if (($extlimit == "yes") && (!in_array($ext,$limitedext))) {
    
    	exit_status('Wrong file extension.');
    	exit();
    
    }
    
    //so, whats the file's extension?
    
    $getExt = explode ('.', $file_name);
    
    $file_ext = $getExt[count($getExt)-1];
    
    //create a random file name
    
    $rand_name = md5(time());
    
    $rand_name = $rand_name . rand(0,999999999);
    
    //the new width variable
    
    $ThumbWidth = $img_thumb_width;
    
    
    
    /////////////////////////////////
    
    ///// CREATE THE THUMBNAIL /////
    
    ///////////////////////////////
    
    
    
    //keep image type
    
    if($file_size){
    
    	if($file_type == "image/pjpeg" || $file_type == "image/jpeg"){
    
    		$new_img = imagecreatefromjpeg($file_tmp);
    
    	}elseif($file_type == "image/x-png" || $file_type == "image/png"){
    
    		$new_img = imagecreatefrompng($file_tmp);
    
    	}elseif($file_type == "image/gif"){
    
    		$new_img = imagecreatefromgif($file_tmp);
    
    	}
    
    	//list the width and height and keep the height ratio.
    
    	list($width, $height) = getimagesize($file_tmp);
    
    	//calculate the image ratio
    
    	$imgratio=$width/$height;
    
    	if ($imgratio>1){
    
    		$newwidth = $ThumbWidth;
    
    		$newheight = $ThumbWidth/$imgratio;
    
    	}else{
    
    		$newheight = $ThumbWidth;
    
    		$newwidth = $ThumbWidth*$imgratio;
    
    	}
    
    	//function for resize image.
    
    	if (function_exists(imagecreatetruecolor)){
    
    		$resized_img = imagecreatetruecolor($newwidth,$newheight);
    
    	}else{
    
    		die("Error: Please make sure you have GD library ver 2+");
    
    	}
    
    	//the resizing is going on here!
    
    	imagecopyresampled($resized_img, $new_img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    
    	//finally, save the image
    
    	imagejpeg($resized_img,"$path_thumbs/$rand_name.$file_ext", 100);
    
    
    }
    
    
    
    //ok copy the finished file to the thumbnail directory
    
    if(move_uploaded_file ($file_tmp, "$path_big/$rand_name.$file_ext")){
    
    	include('functions.php');
    
    	connect();
    
    	$link   = get_option('admin_url');
    
    	$sql    = " INSERT into mediaT ( name, url, link, createdon, createdby ) VALUES ( '$file_name', '$path_big/$rand_name.$file_ext', '$link$path_big/$rand_name.$file_ext', NOW(), '$createdby' ) ";
    	$result = mysql_query($sql);
    
    }
    
    exit_status('Something went wrong with your upload!');
    
    
    // Helper functions
    
    function exit_status($str){
    	echo json_encode(array('status'=>$str));
    	exit;
    }
    
    function get_extension($file_name){
    	$ext = explode('.', $file_name);
    	$ext = array_pop($ext);
    	return strtolower($ext);
    }
    ?>

  2. Ok after reading through the above code, I have a vague idea of what exactly you are trying to achieve. At the moment your code is very bloated and not very logical.

     

    At the moment you are still not setting the rank cookie OR session within your login script so the example I sent you will not work. Because you are already using cookies within your code we will stick with that.

     

    You can set this variable by adding the following line of code in your login script where you are already setting your cookies.

    <?php
        setcookie("lutari_rank",$check[username], time()+60*60*24*365, "/staff/");
    ?>
    

     

    Then on each page you want to lock off add something like this to the top of the page.

    <?php
       
       // Rank Limit
       $limit = 10;
       
       // Using a cookie
       $rank = $_COOKIE['utari_rank'];
    
       if ($rank < $limit) {
          header("$baseurl/index.php?error=You+can+not+view+this+page.");
          exit();
          die();
       }
    
       include ($_SERVER['DOCUMENT_ROOT'].'/staff/header.inc.php');
    ?>
    

     

    Hopefully this is what you are looking to achieve and I have explained it well enough. Obviously you will have to use the page id, section id category is or what ever bit of the website you are on to dictate the limit you are checking against.

     

    You would probably need to use if statements for this bit. Like if($pageid <10){ $limit = 10; }.

     

    On a second note I have noticed that you are using md5 on your password. Please do not use md5 for passwords. There are hundreds of password hashing posts on this forum that can recommend how to handle password. The one I have used for my custom CMS is called phpass. Google it. Wordpress also use it (Not that that makes it the be all and end all). Just a recommendation.

     

    If you continue to use md5, you might as well not bother locking off any sections of your website as md5 can be broken in less than 10 minutes with a standard computer.

     

     

  3. The easiest way to do this would be to set a session or a cookie with the user rank, whenever a user logs in. Then at the top of the page try something like the following.

     

    <?php 
    session_start();
            
           // Rank Limit
           $limit = 7;
    
            // Using a session 
    $rank = $_SESSION['rank'];
    
           // Using a cookie
           $rank = $_COOKIE['rank'];
    
    if ($rank < $limit) {
    	header("your-page-name.php");
    	exit();
    	die();
    }
    ?>

  4. Thank you for your help isset1988. However the code you sent me was completely different to the code that I have. I would like to try and the problem with the code I currently have and use that if possible as I have put a lot of time into it. If I cannot figure out what is wrong then I will consider using a different method.

     

    This is the code I currently have which is creating the resized image at the correct size, however it still creating a completely black image instead of copying the original image.

     

    Can anyone spot any possible issues with the code below?

     

    <?php
    session_start();
    
    $path_thumbs = "uploads/thumbs";
    $path_big    = "uploads";
    $createdby   = $_SESSION["ufullname"];		
    
    //the new width of the resized image, in pixels.
    
    $img_thumb_width = 570; // 
    
    $extlimit = "yes"; //Limit allowed extensions? (no for all extensions allowed)
    
    //List of allowed extensions if extlimit = yes
    
    $limitedext = array(".gif",".jpg",".png",".jpeg",".bmp");		
    
    //the image -> variables
    
    $file_type = $_FILES['pic']['type'];
    $file_name = $_FILES['pic']['name'];
    $file_size = $_FILES['pic']['size'];
    $file_tmp = $_FILES['pic']['tmp_name'];
    
    //check if you have selected a file.
    
    if(!is_uploaded_file($file_tmp)){
    
    	exit_status('Error: Please select a file to upload!');
    	exit(); //exit the script and don't process the rest of it!
    
    }
    
    //check the file's extension
    
    $ext = strrchr($file_name,'.');
    
    $ext = strtolower($ext);
    
    //uh-oh! the file extension is not allowed!
    
    if (($extlimit == "yes") && (!in_array($ext,$limitedext))) {
    
    	exit_status('Wrong file extension.');
    	exit();
    
    }
    
    //so, whats the file's extension?
    
    $getExt = explode ('.', $file_name);
    
    $file_ext = $getExt[count($getExt)-1];
    
    //create a random file name
    
    $rand_name = md5(time());
    
    $rand_name = $rand_name . rand(0,999999999);
    
    //the new width variable
    
    $ThumbWidth = $img_thumb_width;
    
    
    
    /////////////////////////////////
    
    ///// CREATE THE THUMBNAIL /////
    
    ///////////////////////////////
    
    
    
    //keep image type
    
    if($file_size){
    
    	if($file_type == "image/pjpeg" || $file_type == "image/jpeg"){
    
    		$new_img = imagecreatefromjpeg($file_tmp);
    
    	}elseif($file_type == "image/x-png" || $file_type == "image/png"){
    
    		$new_img = imagecreatefrompng($file_tmp);
    
    	}elseif($file_type == "image/gif"){
    
    		$new_img = imagecreatefromgif($file_tmp);
    
    	}
    
    	//list the width and height and keep the height ratio.
    
    	list($width, $height) = getimagesize($file_tmp);
    
    	//calculate the image ratio
    
    	$imgratio=$width/$height;
    
    	if ($imgratio>1){
    
    		$newwidth = $ThumbWidth;
    
    		$newheight = $ThumbWidth/$imgratio;
    
    	}else{
    
    		$newheight = $ThumbWidth;
    
    		$newwidth = $ThumbWidth*$imgratio;
    
    	}
    
    	//function for resize image.
    
    	if (function_exists(imagecreatetruecolor)){
    
    		$resized_img = imagecreatetruecolor($newwidth,$newheight);
    
    	}else{
    
    		die("Error: Please make sure you have GD library ver 2+");
    
    	}
    
    	//the resizing is going on here!
    
    	imagecopyresampled($resized_img, $new_img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    
    	//finally, save the image
    
    	imagejpeg($resized_img,"$path_thumbs/$rand_name.$file_ext", 100);
    
    
    }
    
    
    
    //ok copy the finished file to the thumbnail directory
    
    if(move_uploaded_file ($file_tmp, "$path_big/$rand_name.$file_ext")){
    
    	include('functions.php');
    
    	connect();
    
    	$link   = get_option('admin_url');
    
    	$sql    = " INSERT into mediaT ( name, url, link, createdon, createdby ) VALUES ( '$file_name', '$path_big/$rand_name.$file_ext', '$link$path_big/$rand_name.$file_ext', NOW(), '$createdby' ) ";
    	$result = mysql_query($sql);
    
    }
    
    exit_status('Something went wrong with your upload!');
    
    
    // Helper functions
    
    function exit_status($str){
    	echo json_encode(array('status'=>$str));
    	exit;
    }
    
    function get_extension($file_name){
    	$ext = explode('.', $file_name);
    	$ext = array_pop($ext);
    	return strtolower($ext);
    }
    ?>
    

  5. I have managed to write some code which now saves the image and resized image to the folders and database. However the images that are getting resized are just a back square. Any idea what is causing this?

     

    <?php
    session_start();
    
    $path_thumbs = "uploads/thumbs";
    $path_big    = "uploads";
    $createdby   = $_SESSION["ufullname"];		
    
    //the new width of the resized image, in pixels.
    
    $img_thumb_width = 570; // 
    
    $extlimit = "yes"; //Limit allowed extensions? (no for all extensions allowed)
    
    //List of allowed extensions if extlimit = yes
    
    $limitedext = array(".gif",".jpg",".png",".jpeg",".bmp");		
    
    //the image -> variables
    
    $file_type = $_FILES['pic']['type'];
    $file_name = $_FILES['pic']['name'];
    $file_size = $_FILES['pic']['size'];
    $file_tmp = $_FILES['pic']['tmp_name'];
    
    //check if you have selected a file.
    
    if(!is_uploaded_file($file_tmp)){
    
    	exit_status('Error: Please select a file to upload!');
    	exit(); //exit the script and don't process the rest of it!
    
    }
    
    //check the file's extension
    
    $ext = strrchr($file_name,'.');
    
    $ext = strtolower($ext);
    
    //uh-oh! the file extension is not allowed!
    
    if (($extlimit == "yes") && (!in_array($ext,$limitedext))) {
    
    	exit_status('Wrong file extension.');
    	exit();
    
    }
    
    //so, whats the file's extension?
    
    $getExt = explode ('.', $file_name);
    
    $file_ext = $getExt[count($getExt)-1];
    
    //create a random file name
    
    $rand_name = md5(time());
    
    $rand_name= rand(0,999999999);
    
    //the new width variable
    
    $ThumbWidth = $img_thumb_width;
    
    
    
    /////////////////////////////////
    
    // CREATE THE THUMBNAIL //
    
    ////////////////////////////////
    
    
    
    //keep image type
    
    if($file_size){
    
    	if($file_type == "image/pjpeg" || $file_type == "image/jpeg"){
    
    		$new_img = imagecreatefromjpeg($file_tmp);
    
    	}elseif($file_type == "image/x-png" || $file_type == "image/png"){
    
    		$new_img = imagecreatefrompng($file_tmp);
    
    	}elseif($file_type == "image/gif"){
    
    		$new_img = imagecreatefromgif($file_tmp);
    
    	}
    
    	//list the width and height and keep the height ratio.
    
    	list($width, $height) = getimagesize($file_tmp);
    
    	//calculate the image ratio
    
    	$imgratio=$width/$height;
    
    	if ($imgratio>1){
    
    		$newwidth = $ThumbWidth;
    
    		$newheight = $ThumbWidth/$imgratio;
    
    	}else{
    
    		$newheight = $ThumbWidth;
    
    		$newwidth = $ThumbWidth*$imgratio;
    
    	}
    
    	//function for resize image.
    
    	if (function_exists(imagecreatetruecolor)){
    
    		$resized_img = imagecreatetruecolor($newwidth,$newheight);
    
    	}else{
    
    		die("Error: Please make sure you have GD library ver 2+");
    
    	}
    
    	//the resizing is going on here!
    
    	imagecopyresized($resized_img, $new_img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    
    	//finally, save the image
    
    	ImageJpeg ($resized_img,"$path_thumbs/$rand_name.$file_ext");
    
    	ImageDestroy ($resized_img);
    
    	ImageDestroy ($new_img);
    
    }
    
    
    
    //ok copy the finished file to the thumbnail directory
    
    if(move_uploaded_file ($file_tmp, "$path_big/$rand_name.$file_ext")){
    
    	include('functions.php');
    
    	connect();
    
    	$link   = get_option('admin_url');
    
    	$sql    = " INSERT into mediaT ( name, url, link, createdon, createdby ) VALUES ( '$file_name', '$path_big/$rand_name.$file_ext', '$link$path_big/$rand_name.$file_ext', NOW(), '$createdby' ) ";
    	$result = mysql_query($sql);
    
    }
    
    exit_status('Something went wrong with your upload!');
    
    
    // Helper functions
    
    function exit_status($str){
    	echo json_encode(array('status'=>$str));
    	exit;
    }
    
    function get_extension($file_name){
    	$ext = explode('.', $file_name);
    	$ext = array_pop($ext);
    	return strtolower($ext);
    }
    ?>

  6. Ok, firstly thank you for your help. However I'm sure I worded the question properly. The problem I am having if figuring out how to save the original image into the uploads folder. Then I want to save the resized image to the thumbs folder and the database with the same name as the original.

     

    I have implemented the example you have suggested into my code, but again I am struggling to fogure out how to save the resized image. At current it is still saving the orginal and not the resized image.

     

    Thanks.

     

     

    <?php
    
    include('functions.php');
    
    $upload_dir = 'uploads/';
    $thumbs_dir = 'thumbs/';
    
    // Check if the upload and thumbs directories exist.
    // If they don't then we create them.
    
    if(!file_exists($upload_dir)) {
    
    	if(mkdir($upload_dir)) {
    
    		if(!file_exists($upload_dir . $thumbs_dir)) {
    
    			if(mkdir($upload_dir . $thumbs_dir)) {
    
    			}
    			else {
    				exit_status($upload_dir . 'directory could not be created! Please check your folder permissions.');
    			}
    
    		}
    
    	}
    	else {
    		exit_status($thumbs_dir . 'directory could not be created! Please check your folder permissions.');
    	}
    
    }
    
    $allowed_ext = array('jpg','jpeg','png','gif', 'pdf');
    $unique_id   = uniqid();
    
    if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
    	exit_status('Error! Wrong HTTP method!');
    }
    
    
    if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){
    
    	$pic = $_FILES['pic'];
    
    	if(!in_array(get_extension($pic['name']),$allowed_ext)){
    		exit_status('Only '.implode(',',$allowed_ext).' files are allowed!');
    	}	
    
    
    	// Move the uploaded file from the temporary 
    	// directory to the uploads folder:
    
    	$name        = $pic['name'];
    	$ext         = get_extension($pic['name']);
    	$new_name    = $unique_id . "." . $ext;
    	$createdby   = $_SESSION["ufullname"];
    
    	list($width, $height, $type, $attr) = getimagesize($pic); //this function find the width, height, type of the image $thumbName
    
    	if($width >= 570){
    		$t_w ='570';
    		$t_h = ($height/$width) * $t_w; 
    
    		resize_image($new_name,$name,$t_w,$t_h,$thumbs_dir,$upload_dir); //This Function resize the new	
    	}
    
    	if(move_uploaded_file($pic['tmp_name'], $upload_dir . $new_name)){
    
    		connect();
    
    		$link   = get_option('admin_url');
    
    		$sql    = " INSERT into mediaT ( name, url, link, createdon, createdby ) VALUES ( '$new_name', '$upload_dir$new_name', '$link$upload_dir$new_name', NOW(), '$createdby' ) ";
    		$result = mysql_query($sql);
    
    		exit_status('File was uploaded successfuly!');
    	}
    
    }
    
    exit_status('Something went wrong with your upload!');
    
    
    // Helper functions
    
    function exit_status($str){
    	echo json_encode(array('status'=>$str));
    	exit;
    }
    
    function get_extension($file_name){
    	$ext = explode('.', $file_name);
    	$ext = array_pop($ext);
    	return strtolower($ext);
    }
    ?>
    

     

     

  7. I know there are lots of examples out there, but I just can't get any of them to work when ever I try and implement them into my current code. I always seem to run into the same problem, which is saving the resized image into my uploads folder and also the database.

     

    I am currently using the following code to upload my images and then save them both into a folder called uploads, as well as saving them to the database. What I would like to do is check the width of all images uploaded, if the width is greater than 570px then resize it to that and save both the resized image into the uploads folder and database and ignore the orginal image.

     

    Can someone point me in the right direction please, as everything I have tried so far hasn't worked.

     

    <?php
    
    $upload_dir = 'uploads/';
    $thumbs_dir = 'thumbs/';
    
    // Check if the upload and thumbs directories exist.
    // If they don't then we create them.
    
    if(!file_exists($upload_dir)) {
    
    	if(mkdir($upload_dir)) {
    
    		if(!file_exists($upload_dir . $thumbs_dir)) {
    
    			if(mkdir($upload_dir . $thumbs_dir)) {
    
    			}
    			else {
    
    				exit_status($upload_dir . 'directory could not be created! Please check your folder permissions.');
    
    			}
    
    		}
    
    	}
    	else {
    
    		exit_status($upload_dir . 'directory could not be created! Please check your folder permissions.');
    
    	}
    
    }
    
    $allowed_ext = array('jpg','jpeg','png','gif', 'pdf');
    $unique_id   = uniqid();
    
    if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
    	exit_status('Error! Wrong HTTP method!');
    }
    
    
    if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){
    
    	$pic = $_FILES['pic'];
    
    	if(!in_array(get_extension($pic['name']),$allowed_ext)){
    		exit_status('Only '.implode(',',$allowed_ext).' files are allowed!');
    	}	
    
    
    	// Move the uploaded file from the temporary 
    	// directory to the uploads folder:
    
    	$name        = $pic['name'];
    	$ext         = get_extension($pic['name']);
    	$new_name    = $unique_id . "." . $ext;
    	$createdby   = $_SESSION["ufullname"];
    
    	if(move_uploaded_file($pic['tmp_name'], $upload_dir . $new_name)){
    
    		include('functions.php');
    
    		connect();
    
    		$link   = get_option('admin_url');
    
    		$sql    = " INSERT into mediaT ( name, url, link, createdon, createdby ) VALUES ( '$new_name', '$upload_dir$new_name', '$link$upload_dir$new_name', NOW(), '$createdby' ) ";
    		$result = mysql_query($sql);
    
    		exit_status('File was uploaded successfuly!');
    	}
    
    }
    
    exit_status('Something went wrong with your upload!');
    
    
    // Helper functions
    
    function exit_status($str){
    	echo json_encode(array('status'=>$str));
    	exit;
    }
    
    function get_extension($file_name){
    	$ext = explode('.', $file_name);
    	$ext = array_pop($ext);
    	return strtolower($ext);
    }
    ?>
    

  8. Ok I have made a few modifications to the tutorial code.

     

    The firs one being that I changed the html around abit to as follows:

     

    <div id="dropbox">
        <span class="not-dropable"><form method="post" action="media-upload-save.php" enctype="multipart/form-data" multiple=""><input type="file" id="pic" name="pic[]" multiple><input type="submit" value="Upload" /></form><br />Select a file to upload.</span>
        <span class="dropable">Drop images here to upload.<br /> <i>(You can drop up to 5 images at any one time. With a maximum filesize of 2MB)</i></span>
    </div><!-- / dropbox -->
    

     

    and then secondarily I added a check in the javascript to decide which part of html to show, depending on wether the users browser support drag and drop file uploads.

     

    if('draggable' in document.createElement('span')) {
    	$(".not-dropable").hide();
    	$(".dropable").show();
    }
    else {
    	$(".dropable").hide();
    	$(".not-dropable").show();
    }
    

     

    So how would I go about using the same php file with the standard file upload input? Every time I try and send the data to the php file normally I get the following error from the php file. From what I can gather it's not liking the method I am sending the data to the file. Do I have to use javascript to send both forms?

     

    (Something went wrong with your upload!)

  9. Detecting if it is supported isn't the issue as such. I would like to be able to display a form and regular file input instead of the your browser doesn't support html 5 uploads error message.

     

    I have got this working by adding changing a few things as you will see below. :

     

    $(function(){
    
    var dropbox = $('#dropbox'),
    	message = $('.message', dropbox);
    
    dropbox.filedrop({
    	// The name of the $_FILES entry:
    	paramname:'pic',
    
    	maxfiles: 10,
        	maxfilesize: 2,
    	url: 'media-upload-save.php',
    
    	uploadFinished:function(i,file,response){
    		$.data(file).addClass('done');
    		// response is the JSON object that post_file.php returns
    	},
    
        	error: function(err, file) {
    		switch(err) {
    			case 'BrowserNotSupported':
    				showForm('<span class="message">Your browser does not support drag and drop uploads!</span><form method="post"><input type="file" name="pic" id="pic" /><input type="submit" value="Upload" /></form>');
    				break;
    			case 'TooManyFiles':
    				alert('Too many files! Please select 5 at most!');
    				break;
    			case 'FileTooLarge':
    				alert(file.name+' is too large! Please upload files up to 2mb.');
    				break;
    			default:
    				break;
    		}
    	},
    
    	// Called before each upload is started
    	beforeEach: function(file){
    		if(!file.type.match(/^image\//) && !file.type.match(/^application\//)){
    			alert('Only images and pdfs are allowed!');
    
    			// Returning false will cause the
    			// file to be rejected
    			return false;
    		}
    	},
    
    	uploadStarted:function(i, file, len){
    		createImage(file);
    	},
    
    	progressUpdated: function(i, file, progress) {
    		$.data(file).find('.progress').width(progress);
    	}
        	 
    });
    
    var template = '<div class="preview">'+
    					'<span class="imageHolder">'+
    						'<img />'+
    						'<span class="uploaded"></span>'+
    					'</span>'+
    					'<div class="progressHolder">'+
    						'<div class="progress"></div>'+
    					'</div>'+
    				'</div>'; 
    
    
    function createImage(file){
    
    	var preview = $(template), 
    		image = $('img', preview);
    
    	var reader = new FileReader();
    
    	image.width = 100;
    	image.height = 100;
    
    	reader.onload = function(e){
    
    		// e.target.result holds the DataURL which
    		// can be used as a source of the image:
    		if (file.type == "application/pdf"){
    			image.attr('src','images/pdf.png');
    		}
    		else {
    			image.attr('src',e.target.result);
    		}
    	};
    
    	// Reading the file as a DataURL. When finished,
    	// this will trigger the onload function above:
    	reader.readAsDataURL(file);
    
    	message.hide();
    	preview.appendTo(dropbox);
    
    	// Associating a preview container
    	// with the file, using jQuery's $.data():
    
    	$.data(file,preview);
    }
    
    function showMessage(msg){
    	message.html(msg);
    }
    
    function showForm(html){
    	dropbox.html(html);
    }
    
    });

     

    However I struggling to figure out how to trigger the same process the drag and drop uploads have, but when ever the standard form is submitted.

  10. Apologies in advance, but I didn't know if I should post this issue in the PHP or Javascript section.

     

    http://tutorialzine.com/2011/09/html5-file-upload-jquery-php/

     

    I am currently using the above tutorial and trying to create a fallback feature for the bane of my life I.E.

     

    In the tutorial the author mentions that the php file included can be used to also accept uploads from a simple file input, which is what I'm trying to achieve.

     

    Can anyone point me in the right direction to create a fallback form when html 5 uploading is not available?

     

    Thanks.

  11. For anyone who is interested, and would like to either use this code or learn from it here is the working code.

     

    I have also added a user id cookie to use as a further check. It is used if the auth code cannot be found in the database, it checks if the user id row from the cookie auth code field is empty. If it isn't  it lets the user know that their authentication has expired because they have logged in on a new computer / browser and created a new auth code.

     

    Login.php

    	<?php include ('functions.php'); ?>
    <?php get_header('login'); ?>
        <div id="login-result">
        <?php
    	$redirect = htmlspecialchars(mysql_real_escape_string($_GET['redirect']));
    
    	if(isset($_COOKIE['authcode'])){
    
    		connect();
    
    		$authcookie  = htmlspecialchars(mysql_real_escape_string($_COOKIE['authcode']));
    
    		$sql         = "SELECT uid, username, firstname, lastname, role FROM usersT WHERE authcode='$authcookie'";
    		$result      = mysql_query($sql);
    		$count       = mysql_num_rows($result);
    		$row         = mysql_fetch_array($result);
    
    		$uid         = $row['uid'];
    		$username    = $row['username'];
    		$fname       = $row['firstname'];
    		$lname       = $row['lastname'];
    		$role        = $row['role'];
    
       
    		if($count==1){
    
    			$new_authcode  = random(30);
    			$sql2    = "UPDATE usersT SET status = '1', authcode = '$new_authcode' WHERE uid = '$uid'";
    			$result2 = mysql_query($sql2);
    
    			if($result2){
    
    				$_SESSION["uid"]       = $uid;
    				$_SESSION["username"]  = $username;
    				$_SESSION["uname"]     = $fname;
    				$_SESSION["ufullname"] = $fname . " " .$lname;
    				$_SESSION["urole"]     = $role;
    				setcookie("uid", $uid, time() + 86400 * 365 * 2);
    				setcookie("authcode", $new_authcode, time() + 86400 * 365 * 2);
    
    				if(!empty($redirect)) {
    					header( 'Location: '. $redirect ) ;
    					exit(); 
    				}
    				else {
    					header( 'Location: index.php' ) ;
    					exit();
    				}
    
    			}
    
    		}
    		else {
    
    			connect();
    			$uid3     = $_COOKIE['uid'];
    			$sql3     = "SELECT username FROM usersT WHERE uid = '$uid3' AND authcode != ''";
    			$result3  = mysql_query($sql3);
    			$count3   = mysql_num_rows($result3);
    			$row3     = mysql_fetch_array($result3);
    			$username = $row3['username'];
    
    			if($count3 > 0) {
    				setcookie("authcode", $authcode, time() - 86400 * 365 * 2);
    				echo "<div class=\"error rounded5 shadow\">Authentication expired for $username! Please login.</div>";
    			}
    
    		}
    
    
    	}
    ?>
        <?php
    	if (isset($_POST['admin_login'])){
    
    		if(isset($_POST["username"]) && isset($_POST["password"])){
    
    			connect();
    
    			$username_p        = htmlspecialchars(mysql_real_escape_string($_POST["username"]));
    			$password_p        = htmlspecialchars(mysql_real_escape_string($_POST["password"]));
    
    			if (strlen($password_p) < 73) {
    
    				$sql4          = "SELECT password FROM usersT WHERE username='$username_p'";
    				$result4       = mysql_query($sql4);
    				$row4          = mysql_fetch_array($result4);
    
    				//Password hashing
    				require("inc/password-hash.php");
    				$hasher        = new PasswordHash(8, false);
    				$stored_hash   = "*";
    				$stored_hash   = $row4['password'];
    				$check         = $hasher->CheckPassword($password_p, $stored_hash);
    
    				if($check){
    
    					$sql5      = "SELECT uid, username, firstname, lastname, role FROM usersT WHERE username='$username_p'";
    					$result5   = mysql_query($sql5);
    					$row5      = mysql_fetch_array($result5);
    
    					$uid       = $row5['uid'];
    					$username  = $row5['username'];
    					$fname     = $row5['firstname'];
    					$lname     = $row5['lastname'];
    					$role      = $row5['role'];
    
    					$authcode  = random(30);
    					$sql6      = "UPDATE usersT SET status = '1', authcode = '$authcode' WHERE uid = '$uid'";
    					$result6   = mysql_query($sql6);
    
    					if($result5 && $result6){
    
    						$_SESSION["uid"]        = $uid;
    						$_SESSION["username"]   = $username;
    						$_SESSION["uname"]      = $fname;
    						$_SESSION["ufullname"]  = $fname . " " .$lname;
    						$_SESSION["urole"]      = $role;
    						setcookie("uid", $uid, time() + 86400 * 365 * 2);
    
    						if(isset($_POST['remember'])) { 
    							setcookie("authcode", $authcode, time() + 86400 * 365 * 2); 
    						} // Check if the user wants to be remembered.
    
    						if(!empty($redirect)) {
    							header( 'Location: '. $redirect ) ;
    							exit(); 
    						} // Check if the user has been redirected from another page.
    						else {
    							header( 'Location: index.php' ) ;
    							exit();
    						}
    
    					} // Check if the users status has been updated.
    					else {
    						echo "<div class=\"error rounded5 shadow\">User status couldn't be updated!</div>";
    					}
    
    				} // Check the entered password against the stored hash.
    				else {
    					echo "<div class=\"error rounded5 shadow\">Invalid username or password!</div>";
    				}
    
    			} // Checked the character length of the password.
    			else {
    				echo "<div class=\"error rounded5 shadow\">Password must be 72 characters or less!</div>";
    			}
    
    		} // Check both fields have been filled in.
    
    	} // Check the user has submitted the data.	
    
    ?>
        </div><!-- / login-results -->
        <div id="login" class="rounded5 shadow">
    	<form name="loginform" id="loginform" action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
                <p>
                    <label for="username">Username<br>
                    <input type="text" name="username" id="username" class="rounded5" value="<?php echo $username_p; ?>" size="20" tabindex="10" /></label>
                </p>
                <p>
                    <label for="password">Password<br>
                    <input type="password" name="password" id="password" class="rounded5" value="<?php echo $password_p; ?>" size="20" tabindex="20" maxlength="72" /></label>
                </p>
                <p class="submit">
                	Keep me logged in <input type="checkbox" name="remember" id="remember"  /><br /><br /><a href="" class="left">Lost your password?</a>
                    <input type="submit" name="admin_login" id="admin_login" class="btn rounded10 right" value="Log In" tabindex="100" />
                </p>
                <div class="cleaner"></div><!-- / cleaner -->
            </form>
        </div><!-- / login-->
    <?php get_footer('login'); ?>
    

  12. Absolute schoolboy error, the problem was I was using '$authcode' as the variable in the WHERE statement but I was saving the cookie as '$authcookie'.

     

    Modified code:

     

    $authcookie  = htmlspecialchars(mysql_real_escape_string($_COOKIE['authcode']));
    $sql         = "SELECT uid, username, firstname, lastname, role FROM usersT WHERE authcode='$authcookie'";
    

     

    I have also removed the addslashes and session_register, thanks for the advice.

     

    I guess now this is working properly I won't need to worry about trash collection, because if the session times out they will get redirected to the login page, the cookie will be checked, re-log them in and redirect them. So basically they won't realise they have even been timed out. Obviously this won't happen if they haven't checked remember me... That'll teach them!

  13. I am trying to create a remember me checkbox for the login of my CMS.

     

    What I am trying to achieve is that whenever a user logs in with the checkbox ticked and auth code is created and stored in a cookie and also the database under their user info row. When I user closes their browser without logging out and then returns to the CMS a few days later etc I am trying to run some code straight away if they get redirected to the login page. The code will check to see if the auth code cookie exists, if it does it gets checked against the database records, if a match is found then log that user in. If it doesn't do nothing until the user uses the login form.

     

    I have written what I though was the perfect solution but it never seems to automatically log the user in, even if they haven't logged out. Some direction in this matter would be very helpful, thank you.

     

    I would also like to know if there is a way of using php to stop my session getting cleared by the trash collector after some inactivity?

     

     

     

    Login.php  (I am using PHpass for the password hashing)

     

    <?php include ('functions.php'); ?>
    <?php get_header('login'); ?>
        <div id="login-result">
        <?php
    	$redirect = htmlspecialchars(mysql_real_escape_string(addslashes($_GET['redirect'])));
    
    	if(isset($_COOKIE['authcode'])){
    
    		connect();
    
    		$authcookie  = htmlspecialchars(mysql_real_escape_string(addslashes($_COOKIE['authcode'])));
    
    		$sql         = "SELECT uid, username, firstname, lastname, role FROM usersT WHERE authcode='$authcode'";
    		$result      = mysql_query($sql);
    		$count       = mysql_num_rows($result);
    		$row         = mysql_fetch_array($result);
    
    		$uid         = $row['uid'];
    		$username    = $row['username'];
    		$fname       = $row['firstname'];
    		$lname       = $row['lastname'];
    		$role        = $row['role'];
    
       
    		if($count==1){
    			$sql2    = "UPDATE usersT SET status = '1' WHERE uid = '$uid'";
    			$result2 = mysql_query($sql2);
    
    			if($result2){
    
    				session_register("uid");
    				session_register("uname");
    				session_register("ulevel");
    				$_SESSION["uid"]       = $uid;
    				$_SESSION["username"]  = $username;
    				$_SESSION["uname"]     = $fname;
    				$_SESSION["ufullname"] = $fname . " " .$lname;
    				$_SESSION["urole"]     = $role;
    
    				if(!empty($redirect)) {
    					header( 'Location: '. $redirect ) ;
    					exit(); 
    				}
    				else {
    					header( 'Location: index.php' ) ;
    					exit();
    				}
    
    			}
    
    		}
    
    	}
    ?>
        <?php
    	if (isset($_POST['admin_login'])){
    
    		if(isset($_POST["username"]) && isset($_POST["password"])){
    
    			connect();
    
    			$username_p        = htmlspecialchars(mysql_real_escape_string(addslashes($_POST["username"])));
    			$password_p        = htmlspecialchars(mysql_real_escape_string(addslashes($_POST["password"])));
    
    			if (strlen($password_1) < 73) {
    
    				//Password hashing
    
    				$sql3          = "SELECT password FROM usersT WHERE username='$username_p'";
    				$result3       = mysql_query($sql3);
    				$row3          = mysql_fetch_array($result3);
    
    				require("inc/password-hash.php");
    				$hasher        = new PasswordHash(8, false);
    				$stored_hash   = "*";
    				$stored_hash   = $row3['password'];
    				$check         = $hasher->CheckPassword($password_p, $stored_hash);
    
    				if($check){
    
    					$sql4      = "SELECT uid, username, firstname, lastname, role FROM usersT WHERE username='$username_p'";
    					$result4   = mysql_query($sql4);
    					$row4      = mysql_fetch_array($result4);
    
    					$uid       = $row4['uid'];
    					$username  = $row4['username'];
    					$fname     = $row4['firstname'];
    					$lname     = $row4['lastname'];
    					$role      = $row4['role'];
    
    					$authcode  = random(30);
    					$sql5      = "UPDATE usersT SET status = '1', authcode = '$authcode' WHERE uid = '$uid'";
    					$result5   = mysql_query($sql5);
    
    					if($result5){
    
    						session_register("uid");
    						session_register("uname");
    						session_register("ulevel");
    						$_SESSION["uid"]        = $uid;
    						$_SESSION["username"]   = $username;
    						$_SESSION["uname"]      = $fname;
    						$_SESSION["ufullname"]  = $fname . " " .$lname;
    						$_SESSION["urole"]      = $role;
    
    						if(isset($_POST['remember'])) { 
    							setcookie("authcode", $authcode, time() + 86400 * 365 * 2); 
    						} // Check if the user wants to be remembered.
    
    						if(!empty($redirect)) {
    							header( 'Location: '. $redirect ) ;
    							exit(); 
    						} // Check if the user has been redirected from another page.
    						else {
    							header( 'Location: index.php' ) ;
    							exit();
    						}
    
    					} // Check if the users status has been updated.
    					else {
    						echo "<div class=\"error rounded5 shadow\">User status couldn't be updated!</div>";
    					}
    
    				} // Check the entered password against the stored hash.
    				else {
    					echo "<div class=\"error rounded5 shadow\">Invalid username or password!</div>";
    				}
    
    			} // Checked the character length of the password.
    			else {
    				echo "<div class=\"error rounded5 shadow\">Password must be 72 characters or less!</div>";
    			}
    
    		} // Check both fields have been filled in.
    
    	} // Check the user has submitted the data.	
    
    ?>
        </div><!-- / login-results -->
        <div id="login" class="rounded5 shadow">
    	<form name="loginform" id="loginform" action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
                <p>
                    <label for="username">Username<br>
                    <input type="text" name="username" id="username" class="rounded5" value="<?php echo $username_p; ?>" size="20" tabindex="10" /></label>
                </p>
                <p>
                    <label for="password">Password<br>
                    <input type="password" name="password" id="password" class="rounded5" value="<?php echo $password_p; ?>" size="20" tabindex="20" maxlength="72" /></label>
                </p>
                <p class="submit">
                	Keep me logged in <input type="checkbox" name="remember" id="remember" <?php if(isset($_COOKIE['remembered'])){ echo "selected=\"selected\""; } ?>  /><br /><br /><a href="" class="left">Lost your password?</a>
                    <input type="submit" name="admin_login" id="admin_login" class="btn rounded10 right" value="Log In" tabindex="100" />
                </p>
                <div class="cleaner"></div><!-- / cleaner -->
            </form>
        </div><!-- / login-->
    <?php get_footer('login'); ?>
    

     

     

     

     

    Logout.php

     

    <?php
    session_start();
    include ('functions.php');
    connect();
    $uid    = mysql_real_escape_string($_SESSION['uid']);
    $sql    = "UPDATE usersT SET status = '0', authcode = '' WHERE uid = '$uid'";
    $result = mysql_query($sql);
    
    if($result) {
    	session_unset(); 
    	session_destroy(); 
    	setcookie("authcode", $authcode, time() - 86400 * 365 * 2); 
    	header("location:" . get_option('home') . "/login.php");
    	exit();
    }
    else {
    	exit();
    }
    ?> 
    

     

     

    Redirect Code

     

    <?php 
    session_start();
    $url   = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
    $uid   = $_SESSION['uid'];
    if (!isset($uid)) {
    	header('location:login.php?redirect='.$url);
    	exit();
    	die();
    }
    ?>

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.