Jump to content

imgrooot

Members
  • Posts

    383
  • Joined

  • Last visited

  • Days Won

    1

Posts posted by imgrooot

  1. Common sense tells you that you cannot have a one-to-one mapping between the gigantic set of all possible strings and the relatively small set of all 16-charater strings. You can either have non-reversible fixed-sized hashes, or you can have reversible dynamic-sized ciphertexts.

     

    What are you trying to achieve?

    It's what a client requested. For now, he asked if I could do the encryption. Decryption hasn't come up yet. I was just curious.

     

    I am assuming it's possible. It should be no different than encrypting  a password but with certain defined parameters no? I suppose one way would be to use a database. Have a column for the original input and the second column for the encrypted text. Then it's simply a matter of retrieving it from the database no?

  2. Say I have a form field where I input any text(numbers,text,symbols, or mixed). I want to encrypt that input into 16 characters long encryption string that includes at least one uppercase letter, one lowercase letter, one number and one special character? 

     

    How can that be done?  Also I want to decrypt it back to original input as well. Can that be one?

     

     

  3. One thing to think about is that although this query may not be the most optimal, it's also not the most frequently used - unless you have thousands of people joining at a time.  If you had millions of users then it may be a slight issue.

    So it's not such a big deal to do it this way, although it's still interesting to see other solutions.

     

    Good to know. That's what I wanted to know.

  4. Ah, shoot, I forgot a step:

    $x = mt_rand(0, $count - 1);
    Or

    FLOOR(RAND() * COUNT(1)) AS x

     

    Alright so based on what you said, here are the queries.  It seems to work. But I've noticed this selects the the user with lowest user_id and checks if all it's positions are filled. If they are, then it goes to the next user with the higher user_id and checks the same thing.  Is this suppose to do that? If so, this might be even better solution than before.

    $count = $db->prepare("SELECT COUNT(1) FROM users WHERE filled_positions < :filled_positions");
    $x = mt_rand(0, $count - 1);
    
    $find_random_user = $db->prepare("SELECT user_id FROM users WHERE filled_positions < :filled_positions LIMIT :x, 1");
    $find_random_user->bindParam(':x', $x);
    
  5. Looking for more than just "a user" (who? did they sign up? are they in a pending state?) "the database" (list of users? list of pending users? list of users with temporary access?) "certain condition" (pending state? failed subscription renewal? didn't follow instructions?) "site" (what kind of site?) "has thousands of users" (logical users stored in the database? actual users who connect? concurrent?) and "better way to do this" (what is the purpose? does it meet your needs right now? asking about best practices?)

     

    Believe it or not, in the software industry, a question can have multiple correct answers that depend on circumstances. And I, for one, am not going to rack my brain for all the answers I can think of only to discover none of them are actually relevant to you.

     

    Or maybe you want the tldr version?

     

    I understand. I am good now. "Jacques1" has answered my question. Cron job is what I'm looking for.

  6.  

    The whole approach sounds odd.

     

    The standard workflow for user management looks more like this:

    • When the user account is initially created, you store the timestamp and set an “activated” flag to “false”.
    • Within a certain timeframe (in your case 24 hours), the user can activate their account, i. e. set the flag to “true”.
    • As long as the account isn't activated, the user only has limited permissions (or no permissions at all, whatever is appropriate).
    • If you absolutely must clean up dead accounts, you can set up a cron job which does this regularly. But as requinix already said, deleting data is rarely a good idea. Nowadays, a few extra bytes of MySQL records really don't hurt your HDD/SSD, and you never know when that data might be useful (debugging, statistics, ...). Get rid of sensitive information, though.

     

     

    I understand the normal process of registering user and sending them an email link to activate their account.  Unfortunately my process has to be little different. The user is activated with the signup. So no activation email link is required. They have 24 hours to make a payment or else their account is deleted. I'll take your advice to keep their essential data(user's primary info) and delete all other data.

     

    I have never used cron job before but it seems to be exactly what I am looking for.

  7. 1. Maybe? Technical details and a precise description would make it easier to answer.

    2. Maybe? Technical details and a precise description would make it easier to answer.

     

    Oh. Advice: don't delete stuff. I'd give you a better alternative but technical details and-- well, you know.

     

    What technical details are you looking for?

     

    I do not require you to give me a code example.  I am simply looking for alternative methods. Word description should suffice.

  8. Having an empty if() condition block is bad form. Besides, if you are pulling the data from the database, why don't you build the whole array dynamically? The fact that the names of your variables are global_payment_due_1, global_payment_due_2, global_payment_due_3 could be an indication of a poor database schema.

     

    Are there always going to be three (and exactly three) events on the page or could it vary? This is really nothing more than a JSON array, so there isn't even any need to have all those if/else statements at all. Just query the data from the database in an appropriate matter and output the results as a JSON string. Can you show the code to retrieve the data and create those variables?

     

    Yes there are always going to be exactly three events on the page. It's just that starting out, the last 2 events will be hidden until the payment from the first event is paid. I can do it with empty if condition or simply hide them with css if they are not active.

     

    Please show me your example of how you would do this properly.

     

    This is how I am currently retrieving the data and creating the variables.

    $findUser = $db->prepare("SELECT users.*, images.*, matrix.* FROM users
    LEFT JOIN matrix ON users.user_id = matrix.user_id
    LEFT JOIN images ON users.user_id = images.user_id
    WHERE users.user_id = :user_id AND users.active = :active");
    $findUser->bindParam(':user_id', $session_user_id);
    $findUser->bindValue(':active', 1);
    $findUser->execute();
    $resultFindUser = $findUser->fetchAll(PDO::FETCH_ASSOC);
    if(count($resultFindUser) > 0) {
       foreach($resultFindUser as $row) {
    
        $global_payment_due_1         = trim($row['d_1_payment_due']);
        $global_payment_approved_1    = trim($row['d_1_payment_approved']);
    
        $global_payment_due_2         = trim($row['d_2_payment_due']);
        $global_payment_approved_2    = trim($row['d_2_payment_approved']);
    
        $global_payment_due_3         = trim($row['d_3_payment_due']);
        $global_payment_approved_3    = trim($row['d_3_payment_approved']);
        
       }
    }
    
  9. Alright so I've managed to solve the issue. I'm not sure if this is the correct way but it works.

     

    The issue was that if any one of those 3 dates were empty, then I would receiving the looping errors. All 3 dates have to be active.  Since I am retrieving the dates from the database, I simply did an if else to check if each date was empty or not.

     

    Here's the updated code.

    <script>
    $( document ).ready(function() {
    
        //Create object with the list of due dates
        //The 'name' will correspond to the field ID to populate the results
        var dueDates = {
          <?php if($global_payment_due_1 == '0000-00-00 00:00:00') {} else { ?>
            'date1':'<?php echo $global_payment_due_1; ?>',
          <?php } ?>
          <?php if($global_payment_due_2 == '0000-00-00 00:00:00') {} else { ?>
            'date2':'<?php echo $global_payment_due_2; ?>',
          <?php } ?>
          <?php if($global_payment_due_3 == '0000-00-00 00:00:00') {} else { ?>
            'date3':'<?php echo $global_payment_due_3; ?>',
          <?php } ?>
        };
    
        var timer = setInterval(function() {
            //Instantiate variables
            var dueDate, distance, days, hours, minutes, seconds, output;
            //Set flag to repeat function
            var repeat = false;
            // Get todays date and time
            var now = new Date().getTime();
            //Iterate through the due dates
            for (var dueDateId in dueDates) {
                //Get the due date for this record
                dueDate = new Date(dueDates[dueDateId]);
                // Find the distance between now an the due date
                distance = dueDate - now;
                // Time calculations for days, hours, minutes and seconds
                days    = Math.floor(distance  / (1000 * 60 * 60 * 24));
                hours   = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
                seconds = Math.floor((distance % (1000 * 60)) / 1000);
                //Determine the output and populate the corresponding field
                output = "OVERDUE";
                if (distance > 0)
                {
                    output = days + "d " + hours + "h " + minutes + "m " + seconds + "s";
                    repeat = true; //If any record is not expired, set flag to repeat
                }
                document.getElementById(dueDateId).innerHTML = output;
                //If flag to repeat is false, clear event
                if(!repeat) {
                    clearInterval(timer);
                }
            }
        }, 1000);
    });
    </script>
    
    
  10. This is the code from my previous topic. It was for getting 3 countdown counters to work on the same page.  It does that.  But I didn't notice this up until now. 

    It gives me this error and it keeps counting up the errors in firebug.

    TypeError: document.getElementById(...) is null
    

    This is the code. Can you tell me what's wrong with it?

    <script>
    $( document ).ready(function() {
    
        //Create object with the list of due dates
        //The 'name' will correspond to the field ID to populate the results
        var dueDates = {
            'date1':'<?php echo $global_payment_due_1; ?>',
            'date2':'<?php echo $global_payment_due_2; ?>',
            'date3':'<?php echo $global_payment_due_3; ?>'
        };
    
        var timer = setInterval(function() {
            //Instantiate variables
            var dueDate, distance, days, hours, minutes, seconds, output;
            //Set flag to repeat function
            var repeat = false;
            // Get todays date and time
            var now = new Date().getTime();
            //Iterate through the due dates
            for (var dueDateId in dueDates) {
                //Get the due date for this record
                dueDate = new Date(dueDates[dueDateId]);
                // Find the distance between now an the due date
                distance = dueDate - now;
                // Time calculations for days, hours, minutes and seconds
                days    = Math.floor(distance  / (1000 * 60 * 60 * 24));
                hours   = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
                seconds = Math.floor((distance % (1000 * 60)) / 1000);
                //Determine the output and populate the corresponding field
                output = "OVERDUE";
                if (distance > 0)
                {
                    output = days + "d " + hours + "h " + minutes + "m " + seconds + "s";
                    repeat = true; //If any record is not expired, set flag to repeat
                }
                document.getElementById(dueDateId).innerHTML = output;
                //If flag to repeat is false, clear event
                if(!repeat)
                {
                    clearInterval(timer);
                }
            }
        }, 1000);
    });
    </script>
    
    
  11. You want now + difference between now and then + two weeks? Isn't that the same as then + two weeks?

     

    Now that I think about it, I guess your right.

     

    Anyways I have solved the issue already. Here it is.

    // find the time difference between now and the expiry date
          $expiry_date      = '2017-04-20 09:02:23';
          $then             = new DateTime($expiry_date);
          $now              = new DateTime();
          $remaining_days   = $then->diff($now)->format("%a");
          
          // I want to add two weeks to the new date.
          $current          = new DateTime();
          $two_weeks        = new DateInterval('P2W');
          $total_date       = $current->add($two_weeks)->format('Y-m-d H:i:s');
    
          // current date + 2 weeks + remaining days difference
          $dateTime = new DateTime($total_date);
          $new_date = $dateTime->modify('+'.$remaining_days.' days');
    
    
          echo $new_date->format('Y-m-d H:i:s');
    

  12. // find the time difference between now and the expiry date
    $expiry_date = '2017-04-20 09:02:23';
    $then = new DateTime($expiry_date);
    $now = new DateTime();
    $remaining_time = $then->diff($now);

    // I want to add two weeks to the new date.
    $two_weeks = $now->add(new DateInterval('P2W'))->format('Y-m-d H:i:s');

    // new date that combines the remaining time from above and adds 2 weeks to create a new date. This is the issue here. How do I combine these two dates properly? The new date has to be in this format ('Y-m-d H:i:s')
    $new_date = $remaining_time + $two_weeks;

     

  13. <html>
    <head>
     
    <script>
     
        //Create object with the list of due dates
        //The 'name' will correspond to the field ID to populate the results
        var dueDates = {
            'date1':'2017-03-03 02:16:02',
            'date2':'2017-05-05 19:01:58',
            'date3':'2017-06-05 05:32:33'
        };
     
        var timer = setInterval(function() {
            //Instantiate variables
            var dueDate, distance, days, hours, minutes, seconds, output;
            //Set flag to repeat function
            var repeat = false;
            // Get todays date and time
            var now = new Date().getTime();
            //Iterate through the due dates
            for (var dueDateId in dueDates)
            {
                //Get the due date for this record
                dueDate = new Date(dueDates[dueDateId]);
                // Find the distance between now an the due date
                distance = dueDate - now;
                // Time calculations for days, hours, minutes and seconds
                days    = Math.floor(distance  / (1000 * 60 * 60 * 24));
                hours   = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
                seconds = Math.floor((distance % (1000 * 60)) / 1000);
                //Determine the output and populate the corresponding field
                output = "OVERDUE";
                if (distance > 0)
                {
                    output = days + "d " + hours + "h " + minutes + "m " + seconds + "s";
                    repeat = true; //If any record is not expired, set flag to repeat
                }
                document.getElementById(dueDateId).innerHTML = output;
                //If flag to repeat is false, clear event
                if(!repeat)
                {
                    clearInterval(timer);
                }
            }
        }, 1000);
     
    </script>
     
    </head>
    <body>
     
    Date 1: <div id="date1"> </div><br>
     
    Date 2: <div id="date2"> </div><br>
     
    Date 3: <div id="date3"> </div><br>
    </body>
    </html>

     

    That works perfectly.  Thank you so much!

  14. Here is my countdown counter code. It works. But I would like to show multiple of these countdown counters with different dates, on a single page. I tried duplicating them and giving them different "due" id name but I the result I get is like this "NaNd NaNh NaNm NaNs".

     

    What's the proper way to duplicate the code below and give them different dates?

    <div id="due"></div>
    <script>
    
        // Set the date we're counting down to
        var countDownDate = new Date("2017-05-05 19:01:58c").getTime();
    
        // Update the count down every 1 second
        var x = setInterval(function() {
    
          // Get todays date and time
          var now = new Date().getTime();
    
          // Find the distance between now an the count down date
          var distance = countDownDate - now;
    
          // Time calculations for days, hours, minutes and seconds
          var days = Math.floor(distance / (1000 * 60 * 60 * 24));
          var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
          var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
          var seconds = Math.floor((distance % (1000 * 60)) / 1000);
    
          // Display the result in the element with id="due"
          document.getElementById("due").innerHTML = days + "d " + hours + "h "
          + minutes + "m " + seconds + "s ";
    
          // If the count down is finished, write some text
          if (distance < 0) {
            clearInterval(x);
            document.getElementById("due").innerHTML = "OVERDUE";
          }
        }, 1000);
    
    </script>
    
    
  15. Well, you're serving the response as standard text/html, but for some strange reason, you've then decided to create an empty image and output it with the imagejpeg() function. That's how an image interpreted as HTML looks like.

     

    A lot of the code is plain weird. For example, why on earth to you use a transaction for a single query and roll it back when there's an error? Just wait until you've finished all error checking and then insert the data.

     

    it's an old image upload code that I copied from a tutorial and then mixed it with my own. The original code actually created 2 images. One original and the other a thumb image. So I removed that thumb code but it looks like there might be some left and that might be causing it.

     

    Yep so this piece of code was causing it. I removed it in all four cases and no more gibbersh code. It's all good now.

    $thumb =	imagecreatetruecolor($width, $height);
    		imagegif($thumb);
    		imagecolortransparent($thumb, imagecolorallocatealpha($thumb, 0, 0, 0, 127));
    	        imagealphablending($thumb, false);
    	        imagesavealpha($thumb, true);
    

    In terms of why I am using transaction for a single query, i didn't realize it till now.  Some of the other pages have multiple queries that require the transaction so naturally I copied the code.  Thanks for pointing that out.

  16. The image uploads fine but I get this weird gibberish code after I submit. It goes away after i refresh the page.

    JFIF>CREATOR: gd-jpeg v1.0 (using IJG JPEG v90), default quality C    $.' ",#(7),01444'9=82<.342C  2!!22222222222222222222222222222222222222222222222222" }!1AQa"q2#BR$3br %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz w!1AQaq"2B #3Rbr $4%&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz?(((((((((((((((((((((((((((((((((((((((((((((((((((((
    

    Here's my code.

    if(isset($_POST['submit'])) {
    
      $errors = array();
    	$db->beginTransaction();
    
      if(isset($_FILES['image'])) {
    
    		if(!empty($_FILES['image']['name'])) {
    
    			$name 		=	$_FILES['image']['name'];
    			$temp 		=	$_FILES['image']['tmp_name'];
    			$type			=	$_FILES['image']['type'];
    			$size			=	$_FILES['image']['size'];
    			$ext 			=	pathinfo($name, PATHINFO_EXTENSION);
    			$size2		=	getimagesize($temp);
    			$width 		=	$size2[0];
    			$height 	=	$size2[1];
    			$upload 	=	md5( rand( 0, 1000 ) . rand( 0, 1000 ) . rand( 0, 1000 ) . rand( 0, 1000 ));
    
    			// Restrictions for uploading
    			$maxwidth	=	1500;
    			$maxheight	=	1500;
    			$allowed	=	array('image/jpeg', 'image/jpg', 'image/png', 'image/gif');
    
    			// Recognizing the extension
    			switch($type){
    
    				// Image/Jpeg
    				case 'image/jpeg':
    						$ext= '.jpeg';
    				break;
    
    				// Image/Jpg
    				case 'image/jpg':
    						$ext= '.jpg';
    				break;
    
    				// Image/png
    				case 'image/png':
    						$ext= '.png';
    				break;
    
    				// Image/gif
    				case 'image/gif':
    						$ext= '.gif';
    				break;
    			}
    			// check if extension is allowed.
    			if(in_array($type, $allowed)) {
    
    				// Checking if the resolution is FULLHD or under this resolution.
    				if($width <= $maxwidth && $height <= $maxheight) {
    					if ($size <= 5242880) {
    
    						$admin_dir	=	"images/";
    
    						if(!is_dir($admin_dir)){
    							mkdir($admin_dir, 0775, true);
    						}
    
    						// upload variables
    						$path =   $admin_dir . $upload . $ext;
    
    						// Resizing according to extension.
    						switch ($type) {
    
    							// Image/Jpeg
    							case 'image/jpeg';
    								$img   =	$temp;
    								$thumb =	imagecreatetruecolor($width, $height);
    													imagejpeg($thumb);
    													imagecolortransparent($thumb, imagecolorallocatealpha($thumb, 0, 0, 0, 127));
    													imagealphablending($thumb, false);
    													imagesavealpha($thumb, true);
    							break;
    
    							// Image/Jpg
    							case 'image/jpg';
    								$img   =	$temp;
    								$thumb =	imagecreatetruecolor($width, $height);
    													imagejpeg($thumb);
    													imagecolortransparent($thumb, imagecolorallocatealpha($thumb, 0, 0, 0, 127));
    													imagealphablending($thumb, false);
    													imagesavealpha($thumb, true);
    							break;
    
    							// Image/png
    							case 'image/png';
    								$img   =	$temp;
    								$thumb =	imagecreatetruecolor($width, $height);
    													imagepng($thumb);
    													imagecolortransparent($thumb, imagecolorallocatealpha($thumb, 0, 0, 0, 127));
    													imagealphablending($thumb, false);
    													imagesavealpha($thumb, true);
    							break;
    
    							// Image/gif
    							case 'image/gif';
    								$img   =	$temp;
    								$thumb =	imagecreatetruecolor($width, $height);
    													imagegif($thumb);
    													imagecolortransparent($thumb, imagecolorallocatealpha($thumb, 0, 0, 0, 127));
    													imagealphablending($thumb, false);
    													imagesavealpha($thumb, true);
    							break;
    						}
    
                $insert_date =	date('Y-m-d H:i:s');
    
                $insert = $db->prepare("INSERT INTO images(path, date_added) VALUES(:path, :date_added)");
                $insert->bindParam(':path', $path);
                $insert->bindParam(':date_added', $insert_date);
         				$result_insert = $insert->execute();
         				if($result_insert == false) {
         					$errors[] = 'Profile photo could not be uploaded.';
         				}
    
                if(empty($errors)) {
    							   $db->commit();
    
    							 move_uploaded_file($temp, $path);
    						   $success = 'Profile photo has been updated.';
    
    						} else {
    							$db->rollBack();
    					  }
    
    					} else {
    
    						$errors[] = 'The image size is bigger than 5mb.';
    
    					}
    				} else {
    
    					$errors[] = 'The image resolution exceeds the limit of 1500px by 1500px.';
    
    				}
    
    			} else {
    
    				$errors[] = 'You have uploaded a forbidden extension.';
    
    			}
    		} else {
    
    			$errors[] = 'An image is required.';
    		}
      }
    }
    ?>
    <form id="upload-form" action="" method="post" enctype="multipart/form-data">
    	<label>175px by 175px</label>
      <input type="file" name="image" />
      <input type="submit" id="upload-submit" value="Upload Image" name="submit">
    </form>
    
  17. Next time, try to ask specific questions. If you had told us right from the beginning which data you want, what you've tried and which errors you got, this would have been done in 5 minutes rather than two days.

     

     

     

     

    Because a) this is standard JSON and b) they cannot possibly know how you're parsing their data. There are more languages than PHP.

     

    Understood. I will do that from now on.

×
×
  • 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.