Merry Christmas everyone! To celebrate, I have decided to give the second edition of my recipe book away for free. No catch. No asking for retweets. Links below:
Big Mick's Recipe Book epub
Big Mick's Recipe Book pdf
Thursday, 6 December 2012
Tuesday, 4 December 2012
Fullscreen presentations using twitter bootstrap and the HTML5 API
I can't take all the credit for this. I have to acknowledge the great work done by HTML5 Demos. What I did was, simplify some of the JavaScript and CSS. I then used Twitter Bootstrap as a template, so to make this work, you'll have to make that download. I also made use of the carousel library which came with Twitter Bootstrap. You'll also have to download jQuery and refer to it as I have.
Here's how it works. You load put the page in your browser. When loaded, you press the 'f' jey to make the page full screen. Press the 'enter' key to move forward through the slideshow. Press the backspace key to move back. Press the 'Esc' key when you've done.
I've tested it on Chrome and Firefox. I believe there's another popular browser, but it's not installed on my computer.
Anyway. Here's the code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Fullscreen demo</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- CSS -->
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/bootstrap-responsive.css" rel="stylesheet">
<!-- <link href="application/application.css" rel="stylesheet"> -->
<style>
::-webkit-scrollbar
{
width:15px;
background:white;
}
::-webkit-scrollbar-thumb
{
box-shadow:inset 0 0 99px rgba(0,0,0,.2);
border:solid transparent;
border-width:6px 4px;
}
html, body
{
height:100%;
background:white;
overflow-y:auto;
overflow-x:hidden;
}
:-webkit-full-screen-document
{
}
:-webkit-full-screen:not(:root)
{
width:100% !important;
float:none !important;
}
:-moz-full-screen:not(:root)
{
width:100% !important;
float:none !important;
}
#fs:-webkit-full-screen
{
width:98%;
height:98%;
background-color:white;
}
.carousel-inner .item
{
margin-left:80px;
}
</style>
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<div id="fs">
<div class="container">
<div class="page-header">
<h1>f for full screen, Esc for quit.</h1>
</div>
<div id="myCarousel" class="carousel slide">
<!-- Carousel items -->
<div class="carousel-inner">
<div class="active item">
<ul>
<li>First bullet</li>
<li>Second</li>
<li>Third</li>
</ul>
</div>
<div class="item">
<ul>
<li>Fourth bullet</li>
<li>Fifth</li>
<li>Sixth</li>
</ul>
</div>
<div class="item">
<ul>
<li>Seventh bullet</li>
<li>Eighth</li>
<li>Ninth</li>
</ul>
</div>
</div>
<!-- Carousel nav -->
<a class="carousel-control left" href="#myCarousel" data-slide="prev">‹</a>
<a class="carousel-control right" href="#myCarousel" data-slide="next">›</a>
</div>
</div>
</div>
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script>
$(document).keyup(function(event)
{
$('.carousel').carousel('pause');
if (event.keyCode === 13)
{
$('a.carousel-control.right').trigger('click');
}
if (event.keyCode === 8)
{
$('a.carousel-control.left').trigger('click');
}
});
var elem = document.querySelector(document.webkitExitFullscreen ? '#fs' : 'body');
document.addEventListener('keydown', function(e)
{
switch (e.keyCode)
{
case 70:
enterFullscreen();
break;
}
}, false);
function enterFullscreen()
{
if (elem.webkitRequestFullscreen)
{
elem.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
}
else
{
if (elem.mozRequestFullScreen)
{
elem.mozRequestFullScreen();
}
else
{
elem.requestFullscreen();
}
}
}
</script>
</body>
</html>
Here's how it works. You load put the page in your browser. When loaded, you press the 'f' jey to make the page full screen. Press the 'enter' key to move forward through the slideshow. Press the backspace key to move back. Press the 'Esc' key when you've done.
I've tested it on Chrome and Firefox. I believe there's another popular browser, but it's not installed on my computer.
Anyway. Here's the code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Fullscreen demo</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- CSS -->
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/bootstrap-responsive.css" rel="stylesheet">
<!-- <link href="application/application.css" rel="stylesheet"> -->
<style>
::-webkit-scrollbar
{
width:15px;
background:white;
}
::-webkit-scrollbar-thumb
{
box-shadow:inset 0 0 99px rgba(0,0,0,.2);
border:solid transparent;
border-width:6px 4px;
}
html, body
{
height:100%;
background:white;
overflow-y:auto;
overflow-x:hidden;
}
:-webkit-full-screen-document
{
}
:-webkit-full-screen:not(:root)
{
width:100% !important;
float:none !important;
}
:-moz-full-screen:not(:root)
{
width:100% !important;
float:none !important;
}
#fs:-webkit-full-screen
{
width:98%;
height:98%;
background-color:white;
}
.carousel-inner .item
{
margin-left:80px;
}
</style>
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<div id="fs">
<div class="container">
<div class="page-header">
<h1>f for full screen, Esc for quit.</h1>
</div>
<div id="myCarousel" class="carousel slide">
<!-- Carousel items -->
<div class="carousel-inner">
<div class="active item">
<ul>
<li>First bullet</li>
<li>Second</li>
<li>Third</li>
</ul>
</div>
<div class="item">
<ul>
<li>Fourth bullet</li>
<li>Fifth</li>
<li>Sixth</li>
</ul>
</div>
<div class="item">
<ul>
<li>Seventh bullet</li>
<li>Eighth</li>
<li>Ninth</li>
</ul>
</div>
</div>
<!-- Carousel nav -->
<a class="carousel-control left" href="#myCarousel" data-slide="prev">‹</a>
<a class="carousel-control right" href="#myCarousel" data-slide="next">›</a>
</div>
</div>
</div>
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script>
$(document).keyup(function(event)
{
$('.carousel').carousel('pause');
if (event.keyCode === 13)
{
$('a.carousel-control.right').trigger('click');
}
if (event.keyCode === 8)
{
$('a.carousel-control.left').trigger('click');
}
});
var elem = document.querySelector(document.webkitExitFullscreen ? '#fs' : 'body');
document.addEventListener('keydown', function(e)
{
switch (e.keyCode)
{
case 70:
enterFullscreen();
break;
}
}, false);
function enterFullscreen()
{
if (elem.webkitRequestFullscreen)
{
elem.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
}
else
{
if (elem.mozRequestFullScreen)
{
elem.mozRequestFullScreen();
}
else
{
elem.requestFullscreen();
}
}
}
</script>
</body>
</html>
Wednesday, 28 November 2012
Quick tip Replacing characters with a new line in Sublime Text 2
I use Sublime Text 2 all the time. I'm also give files all the time which need tweaking before they can be used. Yesterday someone sent me a bunch of e-mail addresses separated by semi-colons, but I needed the content instead to be separated by new line characters. Here's how I did it.
Open the file
Choose Find->Replace.
Then select the 'Regular Expression' button at the bottom left of the screen.
In the 'Find What:' field type your character. In my case it was the semi-colon.
In the 'Replace With:' field type \n
The click the 'Replace All' button.
Hey presto!
Open the file
Choose Find->Replace.
Then select the 'Regular Expression' button at the bottom left of the screen.
In the 'Find What:' field type your character. In my case it was the semi-colon.
In the 'Replace With:' field type \n
The click the 'Replace All' button.
Hey presto!
Labels:
find,
new line,
newline,
regular expression,
replace,
sublime text 2
Tuesday, 2 October 2012
Presenting MySQL table data through PHP, JSON and jQuery
This may seem like a long way round to do something, but believe me, it has its benefits if you are trying to deliver an open systems approach to your development framework.
Let's say I have a MySQL database with table called chat. The chat table has 3 fields; userid, entry and datesaved.
I create a PHP script called jsonout.php which returns all rows of the chat table, thus:
<?php
$con = mysql_connect('localhost','root','');
mysql_select_db('test', $con);
$result = mysql_query('SELECT * FROM `chat`');
while($rows[] = mysql_fetch_assoc($result));
array_pop($rows);
mysql_close($con);
echo json_encode($rows);
?>
Notice the final line (in red) where I return a JSON encoded version of the resulting array.
Now my HTML page (below) can collect the JSON through jQuery and present the results on the page.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple JSON retrieval through jQuery</title>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" href="http://meyerweb.com/eric/tools/css/reset/reset.css" />
<style>
body
{
font:10px/15px Sans-serif;
}
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
</script>
</head>
<body>
<script>
(function()
{
$.getJSON('jsonout.php', function(data)
{
$.each(data, function(i, items)
{
$('body').append('<p>'+items.userid+'</p>'+items.entry+'<p>'+items.datesaved+'</p>');
});
});
})();
</script>
</body>
</html>
Let's say I have a MySQL database with table called chat. The chat table has 3 fields; userid, entry and datesaved.
I create a PHP script called jsonout.php which returns all rows of the chat table, thus:
<?php
$con = mysql_connect('localhost','root','');
mysql_select_db('test', $con);
$result = mysql_query('SELECT * FROM `chat`');
while($rows[] = mysql_fetch_assoc($result));
array_pop($rows);
mysql_close($con);
echo json_encode($rows);
?>
Notice the final line (in red) where I return a JSON encoded version of the resulting array.
Now my HTML page (below) can collect the JSON through jQuery and present the results on the page.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple JSON retrieval through jQuery</title>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" href="http://meyerweb.com/eric/tools/css/reset/reset.css" />
<style>
body
{
font:10px/15px Sans-serif;
}
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
</script>
</head>
<body>
<script>
(function()
{
$.getJSON('jsonout.php', function(data)
{
$.each(data, function(i, items)
{
$('body').append('<p>'+items.userid+'</p>'+items.entry+'<p>'+items.datesaved+'</p>');
});
});
})();
</script>
</body>
</html>
Monday, 1 October 2012
Simple JSON retrieval through jQuery
This page explains how to retrieve some simple JSON data and append it to a page. First the JSON through a script called jsonout.php
{
"one": "Singular sensation",
"two": "Beady little eyes",
"three": "Little birds pitch by my doorstep"
}
Now the HTML with jQuery to retrieve and display it within the page.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple JSON retrieval through jQuery</title>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" href="http://meyerweb.com/eric/tools/css/reset/reset.css" />
<style>
body
{
font:10px/15px Sans-serif;
}
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
</script>
</head>
<body>
<script>
(function()
{
$.getJSON('jsonout.php', function(data)
{
$.each(data, function(key, val)
{
$('body').append('<p>'+key+':'+val+'</p>');
});
});
})();
</script>
</body>
</html>
{
"one": "Singular sensation",
"two": "Beady little eyes",
"three": "Little birds pitch by my doorstep"
}
Now the HTML with jQuery to retrieve and display it within the page.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple JSON retrieval through jQuery</title>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" href="http://meyerweb.com/eric/tools/css/reset/reset.css" />
<style>
body
{
font:10px/15px Sans-serif;
}
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
</script>
</head>
<body>
<script>
(function()
{
$.getJSON('jsonout.php', function(data)
{
$.each(data, function(key, val)
{
$('body').append('<p>'+key+':'+val+'</p>');
});
});
})();
</script>
</body>
</html>
Tuesday, 28 August 2012
Saving and retrieving images using MySQL through PHP
I really should have looked into this a long time ago, but still. The example below deliberately doesn't use jQuery. If you want to POST files through jQuery, you'll need to use an ajax form plugin.
Right. Now we've got that out of the way, to my example. I have created a database in MySQL with a table called pictures, and I have 2 fields:
id : int(8)
picture : longblob
I have used the database class which I developed earlier to handle the requests.
At this stage, I'm just handling JPEG images.
<?php
require_once 'database.class.php';
$db = new database;
if($_POST)
{
$image=$_FILES['uploadfile']['tmp_name'];
$fp = fopen($image, 'r');
$content = fread($fp, filesize($image));
$content = addslashes($content);
fclose($fp);
$sql="insert into pictures (picture) values ('$content')";
$results = $db->query($sql);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File upload</title>
</head>
<body>
<form enctype="multipart/form-data" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="MAX_FILE_SIZE" value="10000000" />
<input name="uploadfile" id="uploadfile" type="file" />
<input type="submit" value="Submit" />
</form>
<div id="results">
<?php
$arr = $db->query('SELECT * FROM pictures');
if($arr)
{
foreach($arr as $row)
{
echo $row['id'];
echo '<img src="data:image/jpeg;base64,'.base64_encode($row['picture']).'" /><br />';
}
}
?>
</div>
</body>
</html>
Enjoy!
Right. Now we've got that out of the way, to my example. I have created a database in MySQL with a table called pictures, and I have 2 fields:
id : int(8)
picture : longblob
I have used the database class which I developed earlier to handle the requests.
At this stage, I'm just handling JPEG images.
<?php
require_once 'database.class.php';
$db = new database;
if($_POST)
{
$image=$_FILES['uploadfile']['tmp_name'];
$fp = fopen($image, 'r');
$content = fread($fp, filesize($image));
$content = addslashes($content);
fclose($fp);
$sql="insert into pictures (picture) values ('$content')";
$results = $db->query($sql);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File upload</title>
</head>
<body>
<form enctype="multipart/form-data" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="MAX_FILE_SIZE" value="10000000" />
<input name="uploadfile" id="uploadfile" type="file" />
<input type="submit" value="Submit" />
</form>
<div id="results">
<?php
$arr = $db->query('SELECT * FROM pictures');
if($arr)
{
foreach($arr as $row)
{
echo $row['id'];
echo '<img src="data:image/jpeg;base64,'.base64_encode($row['picture']).'" /><br />';
}
}
?>
</div>
</body>
</html>
Enjoy!
Monday, 20 August 2012
Useful PHP quick test page
I developed this page a little while ago to do quick tests. Essentially, you just put items in the text box and press submit. The benefit of the page is that all the reloading is done for you. There is no need to keep using back or forward buttons. Just carry on making adjustments to your code and keep trying. The page will use the changes you make.
In the example below, I am outputing an md5 version of my input, but you can create your own functions and just replace the bit where md5 is called (highlighted in red).
<?php
$myname = $_GET ? html_entity_decode($_GET['myname']) : NULL;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" href="http://meyerweb.com/eric/tools/css/reset/reset.css" />
<style>
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
</script>
</head>
<body>
<form>
<label for="myname">Type your string</label>
<input type="text" name="myname" id="myname" value="<?php echo $myname; ?>" />
<button type="submit">Submit</button>
</form>
<p><?php echo $myname ? md5($myname) : NULL; ?></p>
<script>
(function()
{
$('form').submit(function()
{
locStr = '<?php echo basename(__FILE__); ?>?str='+$('#myname').val();
window.location.replace(locStr);
}
})();
</script>
</body>
</html>
In the example below, I am outputing an md5 version of my input, but you can create your own functions and just replace the bit where md5 is called (highlighted in red).
<?php
$myname = $_GET ? html_entity_decode($_GET['myname']) : NULL;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" href="http://meyerweb.com/eric/tools/css/reset/reset.css" />
<style>
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
</script>
</head>
<body>
<form>
<label for="myname">Type your string</label>
<input type="text" name="myname" id="myname" value="<?php echo $myname; ?>" />
<button type="submit">Submit</button>
</form>
<p><?php echo $myname ? md5($myname) : NULL; ?></p>
<script>
(function()
{
$('form').submit(function()
{
locStr = '<?php echo basename(__FILE__); ?>?str='+$('#myname').val();
window.location.replace(locStr);
}
})();
</script>
</body>
</html>
Thursday, 9 August 2012
Lessons learned from the coal face of git repositories
I've just been going through a bit of pain, setting up a git repo.
A git repo is a place to put your open source project. It allows users to get hold of your project, contribute to it and create their own version from it. A git repo also gives you useful things like change control for your project.
GitHub have tried to make the process simple with good help, but there are a few do's and don'ts which I discovered along the way so here, I compose my learning as a reminder to myself. Hopefully we'll all feel the benefit.
I'm going to assume that you have already gone through all the pain of creating a GitHub account. There are many places on the web you can learn how to do this. I'm also assuming that you have logged in to GitHub and that you have reached the homepage of your account. Finally, I'll have to assume you've set git up on your server so that all the local software is in place.
1. It's best to create a new repository from GitHub. Not, as they recommend from your server. Start by clicking the 'New repository' buutton.
2. I recommend you name the repository as the directory on your server. Do not take the option to create the README file. By avoiding it, you will be provided with some starting commands, which I recommend you save to a text file. They'll look something like this:
Create a new repository on the command line
touch README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin https://github.com/yourusername/yourdirectory.git
git push -u origin master
Push an existing repository from the command line
git remote add origin https://github.com/yourusername/yourdirectory.git
git push -u origin master
3. Follow the instructions provided by GitHub within the directory on your server.
4. You may already have a project ready to go up. Then you'll need to do:
git add *.*
git commit -m "your comments"
git push origin master
Followed by:
git add .
git commit -m "your comments"
git push origin master
5. Now you're ready to start pushing your updates. Make some changes. Test that you're happy with them on your server. Now commit using:
git add *.*
git commit -m "your comments"
git push origin master
6. Let's say you messed up (each and every minute of every day in my case (yes, even when I'm sleeping)) and you want to remove a file you've committed. First delete it from your server then:
git add . -A
git commit -m "removed some files"
git push origin master
Have fun with GitHub!
Tuesday, 7 August 2012
Hiding website directories from Johnnie Hacker using a .htaccess file
OK, here's the situation.
You're creating a website.
You want a directory called say 'classes'.
You need to access stuff contained in 'classes', but you don't want a user of your site to access the 'classes' directory through something like this http://www.yoursite.com/classes/
I'm assuming you've shown the good sense to use the apache web server here and that you haven't fallen foul of the Microsoft marketing machine or foolishly believed that you get what you pay for. That said, there are some good web servers other than apache.
I digress. Anyway, here is how to do it.
Go into the directory you wish to deny access to.
Create a file called .htaccess
Add a single line to the file namely:
deny from all
Save the file and restart apache.
If for some reason this doesn't work, it may be the way your apache server is set up.
Look for a file such as:
/etc/apache2/sites-available/default
That's if you're using a proper operating system. Goodness knows what it would be if you were using Windows.
In here you will see a few lines which look like this:
<Directory /var/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>
Change the line which says 'AllowOverride None' to 'AllowOverride All'.
Now restart apache again.
You can now add similar .htaccess files to any directories you want to control.
You're creating a website.
You want a directory called say 'classes'.
You need to access stuff contained in 'classes', but you don't want a user of your site to access the 'classes' directory through something like this http://www.yoursite.com/classes/
I'm assuming you've shown the good sense to use the apache web server here and that you haven't fallen foul of the Microsoft marketing machine or foolishly believed that you get what you pay for. That said, there are some good web servers other than apache.
I digress. Anyway, here is how to do it.
Go into the directory you wish to deny access to.
Create a file called .htaccess
Add a single line to the file namely:
deny from all
Save the file and restart apache.
If for some reason this doesn't work, it may be the way your apache server is set up.
Look for a file such as:
/etc/apache2/sites-available/default
That's if you're using a proper operating system. Goodness knows what it would be if you were using Windows.
In here you will see a few lines which look like this:
<Directory /var/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>
Change the line which says 'AllowOverride None' to 'AllowOverride All'.
Now restart apache again.
You can now add similar .htaccess files to any directories you want to control.
OOP PHP Authentication Class
This class relies upon the existence of a databases class, such as the one listed here, to go away and check of the username and password match. If they do, a session and cookie is created.
<?php
require_once 'database.class.php';
class authenticate
{
public $id;
private $username;
private $password;
private $db;
function __construct()
{
$this->db = new database;
}
function login($u, $p)
{
$this->username = mysql_real_escape_string($u);
$this->password = mysql_real_escape_string(md5($p));
$q = "SELECT * FROM users WHERE username='{$this->username}' AND password='{$this->password}'";
$result = $this->db->query($q);
if($result)
{
$this->id = $result->id;
$this->username = $result->username;
$this->createSessionAndCookies();
}
else
{
$this->destroySessionAndCookies();
}
}
function logout()
{
$this->destroySessionAndCookies();
}
private function createSessionAndCookies()
{
@session_start();
$_SESSION['AUTH_ID'] = $this->id;
$_SESSION['AUTH_USERNAME'] = $this->username;
$expire=time()+3600*24*30;
setcookie('AUTH_ID', $this->id, $expire);
setcookie('AUTH_USERNAME', $this->username, $expire);
echo 'session and cookie created';
}
private function destroySessionAndCookies()
{
unset($_SESSION['AUTH_ID']);
unset($_SESSION['AUTH_USERNAME']);
session_destroy();
setcookie('AUTH_ID', '', time()-3600);
setcookie('AUTH_USERNAME', '', time()-3600);
echo 'session and cookie destroyed';
}
function __destruct()
{
}
}
?>
<?php
require_once 'database.class.php';
class authenticate
{
public $id;
private $username;
private $password;
private $db;
function __construct()
{
$this->db = new database;
}
function login($u, $p)
{
$this->username = mysql_real_escape_string($u);
$this->password = mysql_real_escape_string(md5($p));
$q = "SELECT * FROM users WHERE username='{$this->username}' AND password='{$this->password}'";
$result = $this->db->query($q);
if($result)
{
$this->id = $result->id;
$this->username = $result->username;
$this->createSessionAndCookies();
}
else
{
$this->destroySessionAndCookies();
}
}
function logout()
{
$this->destroySessionAndCookies();
}
private function createSessionAndCookies()
{
@session_start();
$_SESSION['AUTH_ID'] = $this->id;
$_SESSION['AUTH_USERNAME'] = $this->username;
$expire=time()+3600*24*30;
setcookie('AUTH_ID', $this->id, $expire);
setcookie('AUTH_USERNAME', $this->username, $expire);
echo 'session and cookie created';
}
private function destroySessionAndCookies()
{
unset($_SESSION['AUTH_ID']);
unset($_SESSION['AUTH_USERNAME']);
session_destroy();
setcookie('AUTH_ID', '', time()-3600);
setcookie('AUTH_USERNAME', '', time()-3600);
echo 'session and cookie destroyed';
}
function __destruct()
{
}
}
?>
Labels:
authenticate,
oop,
PHP,
user
Monday, 6 August 2012
OOP PHP Vimeo Class
This is essentially the earlier mentioned RSS class with a couple of tweaks for vimeo and search.
First, a script to call the class:
<?php
require_once 'vimeo.class.php';
$addr1 = 'http://vimeo.com/api/v2/channel/videoschool/videos.xml';
$addr2 = 'http://vimeo.com/api/v2/channel/wineaftercoffee/videos.xml';
$vimeo = new vimeo;
$vimeo->addFeed($addr1);
$vimeo->addFeed($addr2);
$arr = $vimeo->getFeed();
/* Or
$arr = $vimeo->getFeed('water');
*/
/*
Or
$searchArray = Array('glass', 'trix');
$arr = $vimeo->getFeed($searchArray);
*/
foreach($arr as $row)
{
echo '<iframe src="http://player.vimeo.com/video/'.$row->id.'" width="WIDTH" height="HEIGHT" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe><br />';
}
?>
Now, the class itself:
<?php
class vimeo
{
public $addr = NULL;
private $outArr = Array();
function __construct($addr = NULL)
{
$this->addr = $addr != NULL ? $addr : $this->addr;
if($this->addr)
{
return $this->addFeed();
}
}
function addFeed($addr = NULL)
{
$this->addr = $addr != NULL ? $addr : $this->addr;
$rss = simplexml_load_file($this->addr);
$this->outArr = array_merge($this->outArr, $rss->xpath('/videos//video'));
}
function getFeed($input = NULL)
{
usort($this->outArr, function ($x, $y)
{
if (strtotime($x->pubDate) == strtotime($y->pubDate)) return 0;
return (strtotime($x->pubDate) > strtotime($y->pubDate)) ? -1 : 1;
});
if(is_array($input))
{
$this->outArr = $this->getArrayFilteredFeed($input);
}
elseif(is_string($input))
{
$this->outArr = $this->getStringFilteredFeed($input);
}
return $this->outArr;
}
private function getStringFilteredFeed($s)
{
$tempArr = Array();
foreach($this->outArr as $row)
{
if(stristr($row->title,$s) || stristr($row->description,$s))
{
array_push($tempArr, $row);
}
}
return $tempArr;
}
private function getArrayFilteredFeed($arr)
{
$tempArr = Array();
foreach($this->outArr as $row)
{
foreach ($arr as $key)
{
if(stristr($row->title,$key) || stristr($row->description,$key))
{
array_push($tempArr, $row);
}
}
}
return $tempArr;
}
}
?>
First, a script to call the class:
<?php
require_once 'vimeo.class.php';
$addr1 = 'http://vimeo.com/api/v2/channel/videoschool/videos.xml';
$addr2 = 'http://vimeo.com/api/v2/channel/wineaftercoffee/videos.xml';
$vimeo = new vimeo;
$vimeo->addFeed($addr1);
$vimeo->addFeed($addr2);
$arr = $vimeo->getFeed();
/* Or
$arr = $vimeo->getFeed('water');
*/
/*
Or
$searchArray = Array('glass', 'trix');
$arr = $vimeo->getFeed($searchArray);
*/
foreach($arr as $row)
{
echo '<iframe src="http://player.vimeo.com/video/'.$row->id.'" width="WIDTH" height="HEIGHT" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe><br />';
}
?>
Now, the class itself:
<?php
class vimeo
{
public $addr = NULL;
private $outArr = Array();
function __construct($addr = NULL)
{
$this->addr = $addr != NULL ? $addr : $this->addr;
if($this->addr)
{
return $this->addFeed();
}
}
function addFeed($addr = NULL)
{
$this->addr = $addr != NULL ? $addr : $this->addr;
$rss = simplexml_load_file($this->addr);
$this->outArr = array_merge($this->outArr, $rss->xpath('/videos//video'));
}
function getFeed($input = NULL)
{
usort($this->outArr, function ($x, $y)
{
if (strtotime($x->pubDate) == strtotime($y->pubDate)) return 0;
return (strtotime($x->pubDate) > strtotime($y->pubDate)) ? -1 : 1;
});
if(is_array($input))
{
$this->outArr = $this->getArrayFilteredFeed($input);
}
elseif(is_string($input))
{
$this->outArr = $this->getStringFilteredFeed($input);
}
return $this->outArr;
}
private function getStringFilteredFeed($s)
{
$tempArr = Array();
foreach($this->outArr as $row)
{
if(stristr($row->title,$s) || stristr($row->description,$s))
{
array_push($tempArr, $row);
}
}
return $tempArr;
}
private function getArrayFilteredFeed($arr)
{
$tempArr = Array();
foreach($this->outArr as $row)
{
foreach ($arr as $key)
{
if(stristr($row->title,$key) || stristr($row->description,$key))
{
array_push($tempArr, $row);
}
}
}
return $tempArr;
}
}
?>
Thursday, 19 July 2012
Simple PDO Class
For some reason, maybe it was my first (negative) introduction to OOP through C++, I've always hated those (::) double colons. So, when I started to look at PHP Data Objects (PDO), although it seemed like a good idea, I couldn't get over the fact that I was opening myself up to using static class and methods with all the syntax which goes with it.
So I started to create a simple database class which made use of PDO, which would be a little friendlier to call. Humble beginnings these. First I created an ini file for all the settings, which looks something like this:
DB_TYPE = mysql
DB_HOST = localhost
DB_USERNAME = jimmy
DB_PASSWORD = password
DB_NAME = testdb
Then, I created the database class which called the ini file thus:
<?php
class database
{
private $config;
private $connection;
private $pdoString;
function __construct()
{
$this->config = (object) parse_ini_file('config.ini', true);
$this->pdoString = $this->config->DB_TYPE;
$this->pdoString .= ':dbname='.$this->config->DB_NAME;
$this->pdoString .= ';host='.$this->config->DB_HOST;
$this->connection = new PDO($this->pdoString, $this->config->DB_USERNAME, $this->config->DB_PASSWORD);
}
public function query($q)
{
return $this->connection->query($q);
}
function __destruct()
{
$this->connection = NULL;
}
}
?>
Finally, I created a calling page to see how it ran:
<?php
require_once 'database.class.php';
$db = new database;
$arr = $db->query('SELECT * FROM users');
foreach($arr as $row)
{
echo $row['username'].'<br />';
}
?>
It's a start.
So I started to create a simple database class which made use of PDO, which would be a little friendlier to call. Humble beginnings these. First I created an ini file for all the settings, which looks something like this:
DB_TYPE = mysql
DB_HOST = localhost
DB_USERNAME = jimmy
DB_PASSWORD = password
DB_NAME = testdb
Then, I created the database class which called the ini file thus:
<?php
class database
{
private $config;
private $connection;
private $pdoString;
function __construct()
{
$this->config = (object) parse_ini_file('config.ini', true);
$this->pdoString = $this->config->DB_TYPE;
$this->pdoString .= ':dbname='.$this->config->DB_NAME;
$this->pdoString .= ';host='.$this->config->DB_HOST;
$this->connection = new PDO($this->pdoString, $this->config->DB_USERNAME, $this->config->DB_PASSWORD);
}
public function query($q)
{
return $this->connection->query($q);
}
function __destruct()
{
$this->connection = NULL;
}
}
?>
Finally, I created a calling page to see how it ran:
<?php
require_once 'database.class.php';
$db = new database;
$arr = $db->query('SELECT * FROM users');
foreach($arr as $row)
{
echo $row['username'].'<br />';
}
?>
It's a start.
Friday, 13 July 2012
OOP PHP RSS Reader
This is a simple RSS Reader which allows you to add multiple feeds. It also sorts the results before returning them to the calling page.
The calling page would look something like this:
<?php
require_once 'rss.class.php';
$addr1 = 'http://feeds.bbci.co.uk/sport/0/football/rss.xml';
$addr2 = 'http://feeds.howtogeek.com/HowToGeek';
$addr3 = 'http://feeds.feedburner.com/TheEdTechie';
$rss = new rss;
$rss->addFeed($addr1);
$rss->addFeed($addr2);
$rss->addFeed($addr3);
$arr = $rss->getFeed();
foreach($arr as $row)
{
echo $row->title.'-'.$row->pubDate.'<br />';
}
?>
So, here's the RSS Reader class:
<?php
class rss
{
public $addr = NULL;
private $outArr = Array();
function __construct($addr = NULL)
{
$this->addr = $addr != NULL ? $addr : $this->addr;
if($this->addr)
{
return $this->addFeed();
}
}
function addFeed($addr = NULL)
{
$this->addr = $addr != NULL ? $addr : $this->addr;
$rss = simplexml_load_file($this->addr);
$this->outArr = array_merge($this->outArr, $rss->xpath('/rss//item'));
}
function getFeed()
{
usort($this->outArr, function ($x, $y)
{
if (strtotime($x->pubDate) == strtotime($y->pubDate)) return 0;
return (strtotime($x->pubDate) > strtotime($y->pubDate)) ? -1 : 1;
});
return $this->outArr;
}
}
new rss;
?>
The calling page would look something like this:
<?php
require_once 'rss.class.php';
$addr1 = 'http://feeds.bbci.co.uk/sport/0/football/rss.xml';
$addr2 = 'http://feeds.howtogeek.com/HowToGeek';
$addr3 = 'http://feeds.feedburner.com/TheEdTechie';
$rss = new rss;
$rss->addFeed($addr1);
$rss->addFeed($addr2);
$rss->addFeed($addr3);
$arr = $rss->getFeed();
foreach($arr as $row)
{
echo $row->title.'-'.$row->pubDate.'<br />';
}
?>
So, here's the RSS Reader class:
<?php
class rss
{
public $addr = NULL;
private $outArr = Array();
function __construct($addr = NULL)
{
$this->addr = $addr != NULL ? $addr : $this->addr;
if($this->addr)
{
return $this->addFeed();
}
}
function addFeed($addr = NULL)
{
$this->addr = $addr != NULL ? $addr : $this->addr;
$rss = simplexml_load_file($this->addr);
$this->outArr = array_merge($this->outArr, $rss->xpath('/rss//item'));
}
function getFeed()
{
usort($this->outArr, function ($x, $y)
{
if (strtotime($x->pubDate) == strtotime($y->pubDate)) return 0;
return (strtotime($x->pubDate) > strtotime($y->pubDate)) ? -1 : 1;
});
return $this->outArr;
}
}
new rss;
?>
Wednesday, 11 July 2012
HTML5 Audio Slideshow
Here, I've created a slideshow which syncs with a piece of audio. You can add different types of image and you can set the position in the audio when the image/slide appears. All free for you to play with.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>HTML5 Audio Slideshow</title>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" href="http://meyerweb.com/eric/tools/css/reset/reset.css" />
<style>
audio img
{
display:none;
}
#display_meta
{
width:300px;
min-height:225px;
}
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
google.load("jqueryui", "1");
</script>
</head>
<body>
<br />
<img id="display_meta" src="1.png" /><br />
<audio id="greeting" controls="controls">
<source src="http://dl.dropbox.com/u/17154625/greeting.ogg" type="audio/ogg" />
<img src="jimmy.png" data-seconds="2" />
<img src="johnnie.png" data-seconds="4" />
<img src="julie.png" data-seconds="6" />
</audio>
<script>
var allImages = new Array(3);
var inc = 0, foundie = 0;
$('audio img').each(function()
{
allImages[inc] = new Array(3);
allImages[inc][0] = $(this).attr('src');
allImages[inc++][1] = $(this).data('seconds');
});
(function()
{
var displayTime = function()
{
var rVer = Math.round(greeting.currentTime);
foundie = giveBackImageName(rVer);
if(foundie != 0)
{
document.getElementById('display_meta').src = foundie;
}
}
var giveBackImageName = function(vr)
{
for (var i = 0; i < allImages.length; i++)
{
if(allImages[i][1] == vr)
{
return allImages[i][0];
}
}
return 0;
}
$('#greeting').bind('timeupdate', displayTime);
})();
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>HTML5 Audio Slideshow</title>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" href="http://meyerweb.com/eric/tools/css/reset/reset.css" />
<style>
audio img
{
display:none;
}
#display_meta
{
width:300px;
min-height:225px;
}
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
google.load("jqueryui", "1");
</script>
</head>
<body>
<br />
<img id="display_meta" src="1.png" /><br />
<audio id="greeting" controls="controls">
<source src="http://dl.dropbox.com/u/17154625/greeting.ogg" type="audio/ogg" />
<img src="jimmy.png" data-seconds="2" />
<img src="johnnie.png" data-seconds="4" />
<img src="julie.png" data-seconds="6" />
</audio>
<script>
var allImages = new Array(3);
var inc = 0, foundie = 0;
$('audio img').each(function()
{
allImages[inc] = new Array(3);
allImages[inc][0] = $(this).attr('src');
allImages[inc++][1] = $(this).data('seconds');
});
(function()
{
var displayTime = function()
{
var rVer = Math.round(greeting.currentTime);
foundie = giveBackImageName(rVer);
if(foundie != 0)
{
document.getElementById('display_meta').src = foundie;
}
}
var giveBackImageName = function(vr)
{
for (var i = 0; i < allImages.length; i++)
{
if(allImages[i][1] == vr)
{
return allImages[i][0];
}
}
return 0;
}
$('#greeting').bind('timeupdate', displayTime);
})();
</script>
</body>
</html>
Thursday, 28 June 2012
OOP PHP POST handler in 2 parts
Actually, I'm wrong before I've even started. The class I give you below will also handle GET requests too. I've described it in 2 parts. The first is some HTML and jQuery which can be used to test the class. Then there is the class itself.
The HTML delivers a form with an input field and submit button. It also contains a jQuery call to the POST handler. Here, I pass the method within the class which will be called to handle the data. Then I pass the data. In this case, the contents of the input field. Finally, An alert catches any data coming back from the class.
The POST handler accepts the POST request as and converts it into an object. It checks to see if a method has been called and that the method exists. If so, the method is invoked. If not, an error message is returned.
Enjoy!
<!DOCTYPE html>
<html lang="en">
<head>
<title>Post test</title>
<style>
body
{
font-family:Sans-serif;
line-height:1.5em;
}
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
google.load("jqueryui", "1");
</script>
</head>
<body>
<form>
<label for="myname">Type your name</label>
<input type="text" name="myname" id="myname" />
<button type="submit">Submit</button>
</form>
<script>
(function()
{
$('form').submit(function()
{
$.post('posthandler.php',
{
method:'getContent',
myname:$(this).find('#myname').val()
}, function(data)
{
alert(data)
});
return false;
});
})();
</script>
</body>
</html>
<?php
class posthandler
{
private $postObject;
function __construct($p)
{
$this->postObject = (object) $p;
if($this->postObject->method && (method_exists($this, $this->postObject->method)))
{
$evalStr = '$this->'.$this->postObject->method.'();';
eval($evalStr);
}
else
{
echo 'Invalid method supplied';
}
}
function getcontent()
{
echo $this->postObject->myname;
}
}
new posthandler($_POST);
?>
The HTML delivers a form with an input field and submit button. It also contains a jQuery call to the POST handler. Here, I pass the method within the class which will be called to handle the data. Then I pass the data. In this case, the contents of the input field. Finally, An alert catches any data coming back from the class.
The POST handler accepts the POST request as and converts it into an object. It checks to see if a method has been called and that the method exists. If so, the method is invoked. If not, an error message is returned.
Enjoy!
The HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>Post test</title>
<style>
body
{
font-family:Sans-serif;
line-height:1.5em;
}
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
google.load("jqueryui", "1");
</script>
</head>
<body>
<form>
<label for="myname">Type your name</label>
<input type="text" name="myname" id="myname" />
<button type="submit">Submit</button>
</form>
<script>
(function()
{
$('form').submit(function()
{
$.post('posthandler.php',
{
method:'getContent',
myname:$(this).find('#myname').val()
}, function(data)
{
alert(data)
});
return false;
});
})();
</script>
</body>
</html>
The Class
<?php
class posthandler
{
private $postObject;
function __construct($p)
{
$this->postObject = (object) $p;
if($this->postObject->method && (method_exists($this, $this->postObject->method)))
{
$evalStr = '$this->'.$this->postObject->method.'();';
eval($evalStr);
}
else
{
echo 'Invalid method supplied';
}
}
function getcontent()
{
echo $this->postObject->myname;
}
}
new posthandler($_POST);
?>
Monday, 28 May 2012
Tabs using Twitter Bootstrap
I had been trying to search out a real world example of how tabs worked in Twitter Bootstrap and found that, by far, most examples missed some crucial elements. Below, I have supplied some code to paste into your Twitter Bootstrap site which you can play with.
<div class="row">
<div class="span16">
<div class="tabbable" id="usernav">
<ul class="nav nav-tabs">
<li class="active"><a href="#home" data-toggle="tab">Home</a></li>
<li><a href="#jobs" data-toggle="tab">Jobs</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="home">
This is my home content.
</div>
<div class="tab-pane" id="jobs">
This is the jobs section.
</div>
</div>
</div>
</div>
</div>
Friday, 9 March 2012
A bit off the wall but who cares
This post won't appeal the the majority of people who follow my blogs, but here goes just the same.
If you type organic culture into the Google search bar, you get results which include fabrics from bamboo, pro-biotic foods, crops and gardening etc. Or to put it another way, semi-structures derived and evolved from existing natural materials.
I was having a conversation with a colleague this morning. We were talking about a system which requires someone to produce something (new) and then receive approval and feedback. The people who submit the products are also the people who will be approving/disapproving other people's products.
Let's just image for a moment that it's you who have been working long and hard on a product with all the best intentions. You are hoping to gain some credibility for your efforts. You send it out for approval. The feedback is negative, in places, missing the point that you have taken time and care to convey.
How likely are you to provide positive feedback to the next product you review?
How likely are you to provide positive feedback to the next product from the person who gave your work negative feedback?
Most organisations have a culture. An organisation I once worked for have a very positive, mutually supportive culture. As time went by, this culture was organically shifted to one which treated new ideas and efforts as an opportunity to pour scorn and score short term points.
Once this type of culture takes hold, it's a bit like fabrics from bamboo, pro-biotic foods, crops and gardening etc. Very difficult to untangle or remove, but for us who wish better for our working lives and for our organisations, we must. And we must replace it with a culture which gets behind something good, works with the originator and builds upon it to create excellence. Only then do we deserve and pat on the back.
If you type organic culture into the Google search bar, you get results which include fabrics from bamboo, pro-biotic foods, crops and gardening etc. Or to put it another way, semi-structures derived and evolved from existing natural materials.
I was having a conversation with a colleague this morning. We were talking about a system which requires someone to produce something (new) and then receive approval and feedback. The people who submit the products are also the people who will be approving/disapproving other people's products.
Let's just image for a moment that it's you who have been working long and hard on a product with all the best intentions. You are hoping to gain some credibility for your efforts. You send it out for approval. The feedback is negative, in places, missing the point that you have taken time and care to convey.
How likely are you to provide positive feedback to the next product you review?
How likely are you to provide positive feedback to the next product from the person who gave your work negative feedback?
Most organisations have a culture. An organisation I once worked for have a very positive, mutually supportive culture. As time went by, this culture was organically shifted to one which treated new ideas and efforts as an opportunity to pour scorn and score short term points.
Once this type of culture takes hold, it's a bit like fabrics from bamboo, pro-biotic foods, crops and gardening etc. Very difficult to untangle or remove, but for us who wish better for our working lives and for our organisations, we must. And we must replace it with a culture which gets behind something good, works with the originator and builds upon it to create excellence. Only then do we deserve and pat on the back.
Monday, 5 March 2012
Multiple inheritance through PHP using traits
I actually took this code from http://php.net. Multiple inheritance has always been a bit dodgy for me in PHP. This is an excellent example of how to use traits to achieve it.
<?php
trait Hello {
public function sayHello() {
echo 'Hello ';
}
}
trait World {
public function sayWorld() {
echo ' World';
}
}
class MyHelloWorld {
use Hello, World;
public function sayExclamationMark() {
echo '!';
}
}
$o = new MyHelloWorld();
$o->sayHello();
$o->sayWorld();
$o->sayExclamationMark();>
?>
<?php
trait Hello {
public function sayHello() {
echo 'Hello ';
}
}
trait World {
public function sayWorld() {
echo ' World';
}
}
class MyHelloWorld {
use Hello, World;
public function sayExclamationMark() {
echo '!';
}
}
$o = new MyHelloWorld();
$o->sayHello();
$o->sayWorld();
$o->sayExclamationMark();>
?>
Labels:
inheritance,
multiple,
oop,
PHP
Friday, 2 March 2012
Removing cache manifest in Chrome
In an earlier post, I explained how to use cache-manifest for localstorage. Once you've achieved this, you'll find that in order to continue editing the site that the cache manifest will need to be removed. Otherwise, you won't see your changes. To do this in Chrome, you need to put this command in the address bar:
chrome://appcache-internals/
This will list all the sites in your application cache with a 'remove' link.
A full list of such commands, enter chrome://chrome-urls/
chrome://appcache-internals/
This will list all the sites in your application cache with a 'remove' link.
A full list of such commands, enter chrome://chrome-urls/
Subscribe to:
Posts (Atom)