Jump to content

happypete

Members
  • Posts

    124
  • Joined

  • Last visited

  • Days Won

    1

Posts posted by happypete

  1. Try this. Create an index.php, ageCheck.php & verified.php page and use the code below.

    Navigate to the verified.php page in the browser first (to check its working) you should automatically be redirected to the index.php page. 

    Now if you select "i'm 21" then you will be redirected to the verified page.

    index.php

    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Untitled Document</title>
    </head>
    
    <body>
    <form method="POST" action="ageCheck.php">
                        <input type="submit" name="valid_age" value="I'm 21" />
                        <input type="submit" name="invalid_age" value="Nope. I sit at the kid's table" />
    </form>
    </body>
    </html>

    When they select either of the button the details will be sent to the ageCheck.php page:

    ageCheck.php

    <?php
    //Start session
    session_start();
    
    /*
    * First, we want to make sure they came to this ageCheck.php via a form.
    * Then we can check to see if $_POST['valid_age'] is set, since it will only
    * be set if they pressed the "I'm 21" button.
    */
    if(isset($_POST)){
    if(isset($_POST['valid_age'])){
    	/*
    	 * Since they got here, it means they are of the right age.
    	 * Now we set the session value.
    	 */
    	$_SESSION['age_verified'] = true;
    	header("Location: verified.php");
    	exit;
    }else{
    	/*
    	 * To young! Just re-direct them to Google.
    	 */
    	header("Location: http://www.google.com");
    	exit;
    }
    }else{
    die("Trying to sneak in are we?");
    }
    
    ?>

    This page will send them to google.com if they have selected "Nope. I sit at the kid's table", or send them to verified.php if they selected "I'm 21"

    verified.php

    <?php
    //Start the session
    session_start();
    
    /*
    * If they haven't passed the age test
    * then the age_verified session will not
    * be set, since it is only set if they
    * say they are 21 years of age.
    */
    if(!isset($_SESSION['age_verified'])){
    header("Location: index.php");
    exit;
    }
    else { $verified = "your age has been verified!";
    }
    
    ?>
    
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Untitled Document</title>
    </head>
    
    <body>
    <?php echo $verified; ?>
    </body>
    </html>

    On the verified page it will again check if they are verified (and send them to index.php if not) of will echo "your age has been verified!"

     

    Any other page that you want them to visit and check they have been verified their age, add this code at the top. If they are not verified it will send then back to the index.php page

    <?php
    //Start the session
    session_start();
    
    /*
    * If they haven't passed the age test
    * then the age_verified session will not
    * be set, since it is only set if they
    * say they are 21 years of age.
    */
    if(!isset($_SESSION['age_verified'])){
    header("Location: index.php");
    exit;
    }
    else { $verified = "your age has been verified!";
    }
    
    ?>

     

  2. I'm getting the following errors:

     

    Notice: Undefined index: field

    Notice: Undefined index:content

     

    I'm getting a Status 200 and the content is passed:

     

    content zbzbfff<br>

    field text1

     

     

    so I cant work out why it says there are undefined index???

     

    ------------------------------------------------------

    error message:

    <br />
    <font size='1'><table class='xdebug-error xe-notice' dir='ltr' border='1' cellspacing='0' cellpadding='1'>
    <tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Notice: Undefined index: field in C:\wamp\www\archive\SmallProjects\cke-backup\save.php on line <i>9</i></th></tr>
    <tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>
    <tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left' bgcolor='#eeeeec'>Location</th></tr>
    <tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0007</td><td bgcolor='#eeeeec' align='right'>369704</td><td bgcolor='#eeeeec'>{main}(  )</td><td title='C:\wamp\www\archive\SmallProjects\cke-backup\save.php' bgcolor='#eeeeec'>..\save.php<b>:</b>0</td></tr>
    </table></font>
    <br />
    <font size='1'><table class='xdebug-error xe-notice' dir='ltr' border='1' cellspacing='0' cellpadding='1'>
    <tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Notice: Undefined index: content in C:\wamp\www\archive\SmallProjects\cke-backup\save.php on line <i>13</i></th></tr>
    <tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>
    <tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left' bgcolor='#eeeeec'>Location</th></tr>
    <tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0007</td><td bgcolor='#eeeeec' align='right'>369704</td><td bgcolor='#eeeeec'>{main}(  )</td><td title='C:\wamp\www\archive\SmallProjects\cke-backup\save.php' bgcolor='#eeeeec'>..\save.php<b>:</b>0</td></tr>
    </table></font>
    OK
    
    <?php
    
    ini_set('display_errors',1);
    error_reporting(E_ALL);
    
    
    include('inc/db.php');
    // Extract details from database
    $stmt = $db->prepare("SELECT * FROM data WHERE id=1");
    $stmt->execute();
    $e = $stmt->fetch();
    
    $edit = "yes";
    ?>
    
    <!DOCTYPE html>
    <!--[if lt IE 7 ]><html class="ie ie6" lang="en"> <![endif]-->
    <!--[if IE 7 ]><html class="ie ie7" lang="en"> <![endif]-->
    <!--[if IE 8 ]><html class="ie ie8" lang="en"> <![endif]-->
    <!--[if (gte IE 9)|!(IE)]><!--><html lang="en"> <!--<![endif]-->
    <head>
        <meta charset="utf-8">
        <title></title>
        <meta name="keywords" content=""/>
        <meta name="description" content=""/>
        <meta name="author" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
          <link rel="stylesheet" href="stylesheets/base.css">
        <!--[if lt IE 9]>
            <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
        <![endif]-->
        <!-- Favicons
        ================================================== -->
        <link rel="shortcut icon" href="images/favicon.ico">
        <link rel="apple-touch-icon" href="images/apple-touch-icon.png">
        <link rel="apple-touch-icon" sizes="72x72" href="images/apple-touch-icon-72x72.png">
        <link rel="apple-touch-icon" sizes="114x114" href="images/apple-touch-icon-114x114.png">
        <link href='http://fonts.googleapis.com/css?family=Coming+Soon' rel='stylesheet' type='text/css'>
        <script type="text/javascript">
      var _gaq = _gaq || [];
      _gaq.push(['_setAccount', 'UA-#######-##']);
      _gaq.push(['_trackPageview']);
    
      (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
      })();
    </script></head>
    <body onLoad="initialize()">
    
    
        <!--[if lte IE 9]><script src="js/respond.js"></script><![endif]-->
    
        <!-- ================================================== -->
    
    
    <div class="container">
    
        <div class="sixteen columns">
        
        <div id="message"></div>
                        
            <p><a id="vacationrentalbariloche"></a></p>
            <p> </p>
            <h1 <?php if ($edit == "yes") {  echo 'contenteditable="true" rel="text1"';} ?>>
            <?php echo html_entity_decode(stripslashes($e['text1'])) ?></h1>
            
            <h5 <?php if ($edit == "yes") {  echo 'contenteditable="true" rel="text2"';} ?>>
            <?php echo html_entity_decode(stripslashes($e['text2'])) ?></h5>
    
    </div><!-- container -->
            
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
            <!--<script src="jquery 1.9.0.js"></script>-->
    <script src="ckeditor/ckeditor.js"></script>
    <script src="ckeditor/customize-toolbar.js"></script>
    <script src="saving.js"></script>
            
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
            <script src="js/pikadate.js"></script>
            <script src="js/all.js"></script>
    
    </body>
    </html>
    

    saving.js:

    // JavaScript Document
    
    			/* This bit of code saves the editable area every 60 seconds when it is being edited, but I also want it so be saved when the user deselects the text area & it need to save multiple editable areas - only save the editable area that is being edited or was selected, DON'T save all editbale areas at once just the one being edited at the time. */
    
    			/* provide feedback to use that content saved when deselected 'content saved message' and every 60 seconds 'autosave message' */
    			/* instance will be created for every element, and for every element we will set listeners for focus and blur events */
    			/* when element is in focus, interval is set, to save data every 60 sec. Beside that, we will keep interval ID to destroy him once element is blured */
    			CKEDITOR.on(
    				"instanceReady", function(event) {
    					var element=event.editor.element.$;
    					$(element).on("focus", function(){
    						var intervalID=setInterval(function(){
    							saveData($(this), true);
    						}, 30000);  // 30000 = 30 seconds autosave
    						$(this).data("intervalID", intervalID);
    					});
    
    					$(element).on("blur", function(){
    						var intervalID=parseInt($(this).data("intervalID"), 10);
    						clearInterval(intervalID);
    						saveData($(this), false);
    					});
    				}
    			);
    			
    			//function saves data from CKEditor into the database, element is jQuery element that contain data that needs to be saved
    			//auto is just a flag that tells us what message to display after save - "autosave" or "update"
    			function saveData(element, auto)
    			{
    				$.ajax({
    					method:"post",
    					url:"save.php",
    					data:{"field":element.attr("rel"), "content":element.html()},
    					success: function(status){
    						if(status==="OK")
    						{
    							var message;
    							if(auto===true)
    							{
    								message="Autosave completed";
    							}
    							else
    							{
    								message="Saved";
    							}
    							
    							$('#message').html(message).stop().hide().fadeIn(200).fadeOut(2500);
    						}
    						else
    						{
    							alert(status);
    							//alert("Error: System cannot save your changes");
    						}
    					}
    				});
    			}
    

    and the PHP - save.php

    <?php
    
    include('inc/db.php');
    
    // Update data 
    $sql = "UPDATE data SET ".$_POST['field']."=:content WHERE id=1"; 
    
    
    $stmt = $db->prepare($sql);
    $content=$_POST['content'];
    $stmt->bindParam(":content", $content);
    $stmt->execute();
    $stmt->closeCursor();
    
    echo "OK";
    return;
    
    ?>
    
  3. Hi,

     

    I'm trying to combine an array (if that's the right way to describe it..??)

     

    I have this

    Array
    (
        [0] => Array
            (
                [0] => 2013-07-14
                [1] => 2013-07-15
                [2] => 2013-07-16
                [3] => 2013-07-17
            )
    
        [1] => Array
            (
                [0] => 2013-08-02
                [1] => 2013-08-03
                [2] => 2013-08-04
                [3] => 2013-08-05
                [4] => 2013-08-06
            )
    
        [2] => Array
            (
                [0] => 2013-10-06
                [1] => 2013-10-07
                [2] => 2013-10-08
                [3] => 2013-10-09
            )
    
    )
    

    and i want this:

    Array
    (
       [0] => 2013-07-14
       [1] => 2013-07-15
       [2] => 2013-07-16
       [3] => 2013-07-17
       [4] => 2013-08-02
       [5] => 2013-08-03
       [6] => 2013-08-04
       [7] => 2013-08-05
       [8] => 2013-08-06
       [9] => 2013-10-06
       [10] => 2013-10-07
       [11] => 2013-10-08
       [12] => 2013-10-09
    )
    
  4. I'm using the http://code.google.com/p/ics-parser/ to extract the start and end date from my ical file:

    $array =($ical1->events());
    $newArray = array();
    foreach ($array as $k => $v) {
      
      $newArray[$k]['startRange'] = date("Y-m-d", strtotime($v['DTSTART']));
      $newArray[$k]['endRange'] = date("Y-m-d", strtotime($v['DTEND']));
    
    }
    print_r(newArray)
    

    which returns this:

    Array
    (
        [0] => Array
            (
                [startRange] => 2013-07-14
                [endRange] => 2013-07-26
            )
    
        [1] => Array
            (
                [startRange] => 2013-08-02
                [endRange] => 2013-09-12
            )
    
        [2] => Array
            (
                [startRange] => 2013-10-06
                [endRange] => 2013-10-10
            )
    
        [3] => Array
            (
                [startRange] => 2013-10-17
                [endRange] => 2013-10-28
            )
    
        [4] => Array
            (
                [startRange] => 2013-11-05
                [endRange] => 2013-11-13
            )
    
        [5] => Array
            (
                [startRange] => 2013-11-14
                [endRange] => 2013-11-23
            )
    
        [6] => Array
            (
                [startRange] => 2013-12-18
                [endRange] => 2014-01-05
            )
    
    )
    

    OK, so I found this to print out all dates between a start and end date:

    $begin = new DateTime('2013-02-01');
    $end = new DateTime('2013-02-07');
    
    $daterange = new DatePeriod($begin, new DateInterval('P1D'), $end);
    
    foreach($daterange as $date){
        echo $date->format("Y-m-d") . "<br>";
    } 
    
    

    This prints out:

    2013-02-01
    2013-02-02
    2013-02-03
    2013-02-04
    2013-02-05
    2013-02-06
    

    The question:

     

    How do I do the same with the ical file to print out the start date, all the dates in between and the end date for each event and put it in an array like this:

    Array
    (
        [0] => 2014-03-12
        [1] => 2014-03-13
        [2] => 2014-03-14
        [3] => 2014-11-21
        [4] => 2014-11-22
        [5] => 2014-11-23
        [6] => 2014-11-24
        [7] => 2014-11-25
        [8] => 2014-11-26
    )
    
  5. Hi,

     

    I'm trying the following query but it seems to ignore the part about the date....

    "SELECT * FROM data WHERE incident = '1' OR incident = '2' OR incident = '3'  AND (DATE(date) BETWEEN 2013-08-19 AND 2013-10-04)" 
    

    I've tried different formats:

    "SELECT * FROM data WHERE incident = '1' OR incident = '2' OR incident = '3'  AND (date >= '2013-08-19' AND date <= '2013-10-04')"
    

    some guidance in the right direction would be great!

  6. awesome, thanks very much, it works :)

     

    I added this: [a-z]+ to the .htaccess file:

    RewriteEngine on
    RewriteRule ^([a-z]+[0-9]+)$ /item.php?id=$1
    

    then changed the links to this, so it would show link1 as opposed to just 1

    <ul>
        <li> <a href="/link1">Item 1</a></li>
        <li> <a href="/link2">Item 2</a></li>
        <li> <a href="/link3">Item 3</a></li>
        <li> <a href="/link4">Item 3</a></li>
    </ul>
    
  7.  

    Ask if you have more questions.

     

     

    Yes, sorry I'm still confused, I just can't get my head round it...

     

    index.php

     <!DOCTYPE html>
    <html lang="en">
    <head>
    	<meta charset="UTF-8" />
    </head>
    <body>
    <ul>
        <li> <a href="item1.php">Item 1</a></li>
        <li> <a href="item2.php">Item 2</a></li>
        <li> <a href="item3.php">Item 3</a></li>
        <li> <a href="item4.php">Item 3</a></li>
    </ul>
    </body>
    </html>
    

    item.php

    <?php $item = $_GET['id']; ?>
     <!DOCTYPE html>
    <html lang="en">
    <head>
    	<meta charset="UTF-8" />
    </head>
    <body>
    <?php echo $item; ?>
    </body>
    </html>
    

    .htaccess

    RewriteEngine on
    RewriteRule ^([0-9]+)$ /item.php?id=$1
    

    So if I click item1.php in the index.php page I want to be directed to item1.php  and $item should be '1'

     

    item1.php doesn't exist.....

  8. I am working on a database drive website. On my index page I have a menu like this:

    <ul>
        <li> <a href="item1.php">Item 1</a></li>
        <li> <a href="item2.php">Item 2</a></li>
        <li> <a href="item3.php">Item 3</a></li>
        <li> <a href="item4.php">Item 3</a></li>
    </ul>
    
    

    I currently have created separate pages (item1.php / item2.php / item3.php....) Each page calls data from a database based on row 'id': 'item1.php' uses: SELECT * FROM items WHERE id = 1 etc.

    All 'item' pages are identical except for the fact that they call different rows from the database: item1.php calls id=1, item2.php calls id=2 etc

    I'm thinking to use a single page (
    item.php) and populate it based on the $_GET['id'] ie: item.php?id=1

    Is there way to write clean URL's with .htaccess and have it so if clicking on the item1.php menu in the index page that it will call item.php but
    display it as item1.php and fill it will details from the database based on id=1 ?

    The idea is that I will have hundreds of pages item1.php to item999.php but don't want to have to create a new page for each database row when all pages will be identical except for the fact that they import a different row from the databse. At the same time I want pages item1.php to item999.php to be index by the search engines...

    I hope I have explained this properly...?

  9. I'm creating a CMS and was going to use a WYSIWYG editor but as they don' t work work on a lot of mobile devices & I only need simple inputs, I decided to just try plain text and convert it to HTML when saving it to the database.  I searched high and low with google to find a secure/usable solutions/functions etc but found none, so I came up with the following.

     

    Am I doing it the right way, is there a better way?

     

    I will probably also use 'http://htmlpurifier.org/' to remove scripts and malicious inputs etc..

    <?php
    $text = "Some text in one line
    an email address test@email.com
    A link without http: www.google.com
    Link with http:// http://www.google.com
    accents: montañas
    
    new paragraph
    *asteriks*
    
    
    new paragraph"
    ?>
    
     <!DOCTYPE html>
    <html lang="en">
    <head>
    	<meta charset="UTF-8" />
    	<title>Text to HTML</title>
    </head>
    <body>
    
    <form name="input" action="" method="post">
    <textarea name="message" rows="12" cols="50">
    <?php
    if($_SERVER['REQUEST_METHOD']=='POST') { echo ($_POST['message']); } else { echo $text;};
    ?>
    </textarea> 
    <input type="submit" value="Submit">
    </form> 
    
    <?php
    
     if($_SERVER['REQUEST_METHOD']=='POST')
        	{
    $message = ($_POST['message']);
    $message = htmlentities($message);
    $message = str_replace("\n\r" , '</p><p>', $message);
    $message = str_replace("<p></p>" , '<p> </p>', $message);
    $message = str_replace("\n" , '<br>', $message);
    $message = str_replace("<p><br>" , '<p>', $message);
    $message = str_replace("<br></p>" , '</p>', $message);
    $message = preg_replace('/([a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4})/' , '<a href="mailto:$1">$1</a>', $message);
    $message = preg_replace('/((ht|f)tp:\/\/[^\s&]+)/','<a href="$1">$1</a>', $message);
    
    
    echo "<p>$message</p><br>";
    echo htmlentities("<p>$message</p>");
    
    		}
    ?>
    </body>
    </html>
    

    This produces the following:

     

    Some text in one line
    an email address test@email.com
    A link without http: www.google.com
    Link with http:// http://www.google.com
    accents: montañas

    new paragraph
    *asteriks*

     

    new paragraph

     

    <p>Some text in one line <br>an email address <a href="mailto:test@email.com">test@email.com</a> <br>A link without http: www.google.com <br>Link with http:// <a href="http://www.google.com">http://www.google.com</a> <br>accents: montañas </p><p>new paragraph <br>*asteriks* </p><p> </p><p>new paragraph</p>

  10. this post might help: http://forums.phpfreaks.com/topic/268852-image-upload-validation-not-working/page-2?do=findComment&comment=1381699

     

    just resize the image twice (process.php): (this script below also creates a randon name, its just a copy and past from one of my projects)

    	// *** Create 'random number' + 'random_name' for image name
    	$imagename = time() . '_' . mt_rand(1000,9999) . '_' . 'randon_name' . '.jpg';
    	// What Directories to put the images
    	$largelocation = '/home/public_html/images/';
    	$thumblocation = '/home/public_html/images/thumb/';
    	//thumbnail location
    	$large = $largelocation . $imagename;
    	$thumb = $thumblocation . $imagename;
    	
    	// *** 1) Initialise / load image
    	$resizeObj = new resize($newPath);
    	// *** 2) Resize LARGE image (options: exact, portrait, landscape, auto, crop)
    	$resizeObj -> resizeImage(800, 600, 'auto'); //was 650, 487 wass 667, 500
    	// *** 3) Save image + define quality
    	$resizeObj -> saveImage($large, 85);
    	
    	// *** 4) Initialise / load image for second resize
    	$resizeObj = new resize($newPath);
    	// *** 5) Resize THUMB (options: exact, portrait, landscape, auto, crop)
    	$resizeObj -> resizeImage(150, 100, 'crop'); //was 220, 165
    	// *** 6) Save image + define quality
    	$resizeObj -> saveImage($thumb, 85);
    
  11. I want to use gmail rather than the webmail that comes with my hosting to keep my personal gmail email in the same place as my website email so I dont have to sign into 2 different accounts?

     

    So can I use SMTP to send via email using smtp:mydomain.com via my server AND use a gmail account or do I have to chnage the MX records and will then have problems with the smtp:mydomain.com going via my server?

  12. Hi,

     

    I have a website with a domain name (yourdomain.com) and a contact form on this site that sends out the contact form detail via email using an email address I set up in my hosting account (smtp@yourdomain.com) with the SMTP PHPMailer, it works fine.

     

    If I want to use info@mydomain.com with google apps for business emails, can I do both at once? I've read about needing to change the MX records if I want to use my domain name with gmail, but don't know if I change the MX record if the smpt@mydomain.com email will still work properly with my form, and if I can use both at once?

     

     

    The SMTP script I'm using: http://phpmailer.wor...pg=exampleasmtp

     

    Thank in advance

  13. I can across this simple/clean login script, can anyone tell me if there are any vunerabilities, is it secure - I intent to remove the bits about registering and just use if for the login part?

     

    https://code.google.com/p/php-pdo-secure-login-script-example/source/browse/branches/index.php

     

    <?php
    session_start();
    /**
    * Table
    CREATE TABLE IF NOT EXISTS `users` (
     `id` int(11) NOT NULL AUTO_INCREMENT,
     `username` varchar(45) DEFAULT NULL,
     `pass_hash` varchar(255) DEFAULT NULL,
     `pass_salt` varchar(255) DEFAULT NULL,
     PRIMARY KEY (`id`)
    ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=0 ;
    */
    //DB Stuff
    define('DBHOST','localhost');
    define('DBNAME','yourdb');
    define('DBUSER','root');
    define('DBPASS','');
    //End Config:---
    
    //Open a PDO Database connection
    try {
        $db = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME, DBUSER, DBPASS);
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    }catch (Exception $e){
        die('Cannot connect to mySQL server.');
    }
    
    class Login{
        public $db;
        public $user;
        public $pass;
        public $error;
        // sha512
        public $algo = '$6';
        // Cost parameter, 25k iterations
        public $cost = '$rounds=25000$';
        function __construct(PDO $db){
    		    $this->db = $db;
    		    $this->global_salt = sha1($_SERVER['HTTP_HOST']);
        }
        /**
    	 * Return a random seed for the mt_rand function
    	 */
        function make_seed(){
    		    list($usec, $sec) = explode(' ', microtime());
    		    return (float) $sec + ((float) $usec * 100000);
        }
        /**
    	 * Return a random unique salt for new created hash/crypt function salts
    	 */
        function unique_salt(){
    		    $salt = null;
    		    mt_srand($this->make_seed());
    		    for($i=0;$i < mt_rand(1,10);$i++){
    				    $salt = sha1($this->global_salt.$salt.mt_rand().uniqid().microtime(true));
    		    }
    		    return substr($salt,0,16);
        }
        /**
    	 * Hash a given password and store parts in:
    	 * $this->salt = a unique 16 byte salt
    	 * $this->hash = The full crypted hash sting including algo/cost/salt/crytedpassword
    	 * $this->full_salt = Just algo/cost/salt section, the first 33 bytes
    	 * $this->hashed_password = Just crytedpassword section, proceeding bytes after first 33 bytes
    	 *
    	 */
        function hash($password){
    		    $this->salt = $this->unique_salt();
    		    $this->full_hash = crypt($password, $this->algo.$this->cost.$this->salt);
    		    $this->full_salt = substr($this->full_hash, 0, 33);
    		    $this->hashed_password = substr($this->full_hash, 33);
    		    return $this->full_hash;
        }
        /**
    	 * Method to validate the given crypto hash against the given password
    	 */
        function check_password($hash, $salt, $password){
    		    $hash = ($this->algo.$this->cost.$salt.'$'.$hash);
    		    if($hash == crypt($password, substr($hash, 0, 33))){
    				    //Regenerate new hash and salt for given password
    				    $this->update_keys();
    				    $this->status = true;
    				    $_SESSION['logged_in']=true;
    				    return true;
    		    }else{
    				    $this->status = false;
    				    return false;
    		    }
        }
        /**
    	 * Set error
    	 */
        function set_error($type,$value){
    		    $this->error[$type]=$value;
        }
        /**
    	 * Output error
    	 */
        function error($type){
    		    echo (isset($this->error[$type]))?$this->error[$type]:null;
        }
        /**
    	 * Logout and regenirate session and redirect to index
    	 */
        static function logout(){
    		    unset($_SESSION['logged_in']);
    		    session_regenerate_id(true);
    		    exit(header('Location: ./index.php'));
        }
        function anti_brute($intval){
    		    if(!isset($_SESSION['access_time'])){
    				    $_SESSION['access_time']=time();
    		    }else{
    				    $t = time()-$_SESSION['access_time'];
    				    if($t <= $intval){
    						    $this->set_error('global','Time violation');
    						    $_SESSION['access_time']=time();
    						    return true;
    				    }
    				    $_SESSION['access_time']=time();
    				    return false;
    		    }
        }
        function process_login(){
    		    if($_SERVER['REQUEST_METHOD']=='POST'){
    				    $this->user   = (isset($_SESSION['userParam']) && isset($_POST[$_SESSION['userParam']]))?$_POST[$_SESSION['userParam']]:null;
    				    $this->pass   = (isset($_SESSION['passParam']) && isset($_POST[$_SESSION['passParam']]))?$_POST[$_SESSION['passParam']]:null;
    				    $this->create = (isset($_SESSION['createParam']) && isset($_POST[$_SESSION['createParam']]))?$_POST[$_SESSION['createParam']]:null;
    				    $cont = true;
    				    if($this->user == null || strlen($this->user) <= 2){$this->set_error('user','Please enter a username!'); $cont=false;}
    				    if($this->pass == null || strlen($this->pass) <= 2){$this->set_error('pass','Please enter a password!'); $cont=false;}
    
    				    if($cont==true){
    						    //Alls good continue
    						    if($this->create != null && $this->create=='1'){
    								    //Check user for new account
    								    if($this->check_user()==true){$this->set_error('user','Username already taken.');return;}
    								    //Create account
    								    $this->create_account();
    						    }else{
    								    //Stop really fast request 2 seconds
    								    if($this->anti_brute(2)==false){
    										    //Attempt to login
    										    $this->check_login();
    								    }
    						    }
    				    }else{
    						    //Error with form
    						    $this->set_error('global','Please fill in login form!');
    				    }
    		    }
        }
        function check_user(){
    		    $sql = 'SELECT 1 FROM users WHERE username=:username';
    		    $statement = $this->db->prepare($sql);
    		    $statement->bindParam(':username', $this->user, PDO::PARAM_STR);
    		    $statement->execute();
    		    $result = $statement->fetch(PDO::FETCH_ASSOC);
    		    if(!empty($result)){return true;}else{return false;}
        }
        function check_login(){
    		    $sql = 'SELECT pass_hash, pass_salt FROM users WHERE username=:username';
    		    $statement = $this->db->prepare($sql);
    		    $statement->bindParam(':username', $this->user, PDO::PARAM_STR);
    		    $statement->execute();
    		    $result = $statement->fetch(PDO::FETCH_ASSOC);
    		    $this->check_password($result['pass_hash'], $result['pass_salt'], $this->pass);
        }
        function create_account(){
    		    //Create new account
    		    $this->hash($this->pass);
    		    $sql = 'INSERT into users (username, pass_hash, pass_salt) VALUES (:username, :pass_hash, :pass_salt)';
    		    $statement = $this->db->prepare($sql);
    		    $statement->bindParam(':username', $this->user, PDO::PARAM_STR);
    		    $statement->bindParam(':pass_hash', $this->hashed_password, PDO::PARAM_STR);
    		    $statement->bindParam(':pass_salt', $this->salt, PDO::PARAM_STR);
    		    $statement->execute();
    		    $this->status = true;
    		    $_SESSION['logged_in']=true;
        }
        function update_keys(){
    		    //Update account password hash & salt
    		    $this->hash($this->pass);
    		    $sql = 'UPDATE users SET pass_hash=:pass_hash, pass_salt=:pass_salt WHERE username=:username';
    		    $statement = $this->db->prepare($sql);
    		    $statement->bindParam(':username', $this->user, PDO::PARAM_STR);
    		    $statement->bindParam(':pass_hash', $this->hashed_password, PDO::PARAM_STR);
    		    $statement->bindParam(':pass_salt', $this->salt, PDO::PARAM_STR);
    		    $statement->execute();
    		    $this->status = true;
    		    $_SESSION['logged_in']=true;
        }
    }//END Login class
    //Logout handler
    if(isset($_GET['logout'])){ Login::logout(); }
    $login = new Login($db);
    //Login handler
    $login->process_login();
    //Debug
    echo '<pre>';
    print_r($login);
    echo '</pre>';
    
    //Check login status
    if(isset($_SESSION['logged_in']) && $_SESSION['logged_in']==true){
        //Logged in
        echo '<a href="?logout">Logout</a>';
    }else{
        //Not Logged In
        //Show login form & create uniqie parrams for user/pass/create post keys
        $_SESSION['userParam']   = sha1(uniqid().microtime(true));
        $_SESSION['passParam']   = sha1(uniqid().microtime(true));
        $_SESSION['createParam'] = sha1(uniqid().microtime(true));
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Secure Login</title>
    </head>
    <body>
    <h1>Secure Login Example</h1>
    <h3>Please login:</h3>
    <?php $login->error('global'); ?>
    <form method="POST" action="">
     <label for="user">Username :  </label>
     <input type="text" name="<?=$_SESSION['userParam'];?>" size="29"> <?php $login->error('user'); ?>
     <br />
     <label for="pass">Password :  </label>
     <input type="text" name="<?=$_SESSION['passParam'];?>" size="29"> <?php $login->error('pass'); ?>
     <br />
     <input type="submit" value="Login">  and create my account:<input type="checkbox" name="<?=$_SESSION['createParam'];?>" value="1">
    </form>
    </body>
    </html>
    <?php } ?>
    

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