Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Thursday 1 August 2013

Heredoc in PHP to reduce a lot of echo calls

Heredoc is a way of building strings for output. Funnily enough I found there was a mistake in some of the coding on the Wikipedia page, but I won't hold that against them. Also, in some of the examples I've come across on the web, they don't seem to recognise an important feature of heredoc. That is, it also provides HTML output.

Below is some example PHP code with the correct syntax, use of variables and HTML. That should speed things up a bit.

<?php
$recipient = 'Mick';
$sender = 'Johnnie';
$x = <<<EOF
Dear $recipient,
I wish you to leave Sunnydale and never return.<br />
Not Quite Love,
$sender
EOF;
echo $x;
?>

Wednesday 3 July 2013

Onload alerts with foundation.js

I was recently asked to help on a website which had been designed using the foundation framework. Naturally, I had to sift through lots of code to find how the site actually worked, but it's not a bad framework. One of the requirements was to create a message alert only when a text string had been passed to the page.

Below is an example of how I did it using PHP. There are 2 elements highlighted in red. Crucial code which was not highlighted in the online documentation. Code which I have added to do the job.

<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" ><![endif]-->
<!--[if gt IE 8]><!--><html class="no-js" lang="en" ><!--<![endif]-->
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Foundation test</title>
<link rel="stylesheet" href="css/foundation.css" />
<script src="js/vendor/jquery.js"></script>
<script src="js/vendor/custom.modernizr.js"></script>
</head>
<body>
<div id="myModal" class="reveal-modal">
<h2>Alert!</h2>
<?php
echo '<p>'.urldecode($_GET['message']).'</p>';
?>
<a class="close-reveal-modal">&#215;</a>
</div>
<script src="js/foundation/foundation.js"></script>
<script src="js/foundation/foundation.reveal.js"></script>
<script>
$(document).foundation();
<?php
if(isset($_GET['message']))
{
?>
$('#myModal').foundation('reveal', 'open');
<?php
}
?>
</script>
</body>
</html>

Wednesday 22 May 2013

Two lines of PHP code which will save your sessions

So you develop PHP applications and use sessions to move data from page to page. You may then also have the problem that session data is not retained, especially if you use a line of code like this:
header('Location:nextpage.php');
Or indeed if the session is not saved on a page refresh.
Enter these 2 lines:

session_regenerate_id(true);
session_write_close();
Put these at the end of your page to save the session data. Also if you use the header function above do something like this.

session_regenerate_id(true);
header('Location:nextpage.php');
session_write_close();

Friday 26 April 2013

How to configure your Ubuntu localhost for PHP MVC URL routing

Step 1. Open a terminal and type
sudo gedit /etc/apache2/sites-available/default
or whatever text editor you like using to open up your apache configuration file for editing.
Step 2. Under the sections headed  <Directory /> and <Directory /var/www/>:
Change the line 'AllowOverride none' to 'AllowOverride All'.

Step 3.  Open up a terminal and type
hostname
This will display your hostname.

Step 4. Open up a terminal and type
sudo gedit /etc/hosts
or whatever text editor you like using to open up your hosts file for editing.
Step 5. Modify the first line so it reads
127.0.0.1    localhost localhost.localdomain yourhostname
Step 6. Open up a terminal and type
sudo a2enmod rewrite

Restart your computer.
It will now work.

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>

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!

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>

Tuesday 7 August 2012

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()
{

}
}
?>

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;
}
}
?>

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.


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;
?>

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!

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 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();>
?>

Tuesday 28 June 2011

PHP, JSON basic example using Topsy Otter

Topsy Otter

Otter API is a RESTful HTTP web service to Topsy. Topsy is a search engine that ranks links, photos and tweets by the number and quality of retweets they receive. The quality of retweets is determined by the influence of the Twitter users.

Below I have used PHP to display results of an Otter call which returns JSON. The results are for the most popular stories on wired.com today.

<?php
$data = json_decode(file_get_contents("http://otter.topsy.com/search.json?q=site:wired.com&window=d"));

foreach ($data as $name => $value)
{
 echo $value->total.'<br />';
 getAllItems($value->list);
}

function getAllItems($iarr)
{
foreach((array)$iarr as $itemName => $itemValue)
{
echo $itemValue->content.'<br />';
}
}
?>

PHP, JSON basic example using delicious

Here is an example of extracting and displaying JSON results through PHP. In this instance, I am using my delicious feed.
Having received the data and decoded it into an array, I like to see the structure of the data. This is where the <pre> tags come in handy. Once you have seen the structure, you know how to traverse and pick out the values you need. Given that the code below is so small, I have commented it.



<?php
/* Get the data and put it into an array */
$data = json_decode(file_get_contents("http://feeds.delicious.com/v2/json/guitarbeerchocolate"));

/* Display the structure of the data so that we know what to extract */
/* Comment out once understood */
echo '<pre>';
print_r($data);
echo '</pre>';

/* Traverse the array, picking out the values you need */
foreach ($data as $name => $value)
{
echo $value->u.'<br />';
echo $value->d.'<br />';
getAllItems($value->t);
echo $value->dt.'<br />';
echo $value->n.'<br />';
echo $value->a.'<br />';
}

/* Some values in this case, tags are themselves arrays so traverse those too */
function getAllItems($iarr)
{
foreach($iarr as $item)
{
echo $item.', ';
}
echo '<br />';
}
?>

Friday 17 June 2011

External web content in your page through the PHP Simple HTML DOM Parser

The excellent PHP Simple HTML DOM Parser, provides the opportunity to bring external content into your web pages.

Here is an example of taking the top news story from the BBC website.

See demo.


<?php
include'simple_html_dom.php';
$html = file_get_html('http://www.bbc.co.uk/news/uk/');
foreach($html->find('#top-story') as $e)
{
echo $e->innertext . '<br />';
}
?>

Monday 28 March 2011

Lorem Ipsum API using PHP

Below are some examples of using the Lorem Ipsum API. A useful tool for someone like me. I always need dummy text. I got the documentation from http://loripsum.net/

See demo.

Uncomment at will.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Lorem Ipsum API</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-family:Sans-serif;
line-height:1.5em;
}
</style>
</head>
<body>
<?php
/* Standard set of items. By default they are paragraphs.  */
/* echo file_get_contents('http://loripsum.net/api'); */
/* Set number of items */
/* echo file_get_contents('http://loripsum.net/api/2'); */
/*
Set length of items
Options can be short, medium, long, verylong.
*/
/* echo file_get_contents('http://loripsum.net/api/long'); */
/*
Set decoration of items
Options can be bold, italic and marked.
*/
/* echo file_get_contents('http://loripsum.net/api/bold'); */
/* Add links to some of the text */
/* echo file_get_contents('http://loripsum.net/api/link'); */
/* Add unordered lists. */
/* echo file_get_contents('http://loripsum.net/api/ul'); */
/* Add unordered lists. */
/* echo file_get_contents('http://loripsum.net/api/ul'); */
/* Add ordered lists. */
/* echo file_get_contents('http://loripsum.net/api/ol'); */
/* Add description lists. */
/* echo file_get_contents('http://loripsum.net/api/dl'); */
/* Add blockquotes. */
/* echo file_get_contents('http://loripsum.net/api/bq'); */
/* Add code samples. */
/* echo file_get_contents('http://loripsum.net/api/code'); */
/* Add headers. */
/* echo file_get_contents('http://loripsum.net/api/headers'); */
/* Use ALL CAPS. */
/* echo file_get_contents('http://loripsum.net/api/allcaps'); */
/* Prude version. Takes out latin words like 'sex' or 'homo'. Cheer up! */
echo file_get_contents('http://loripsum.net/api/prude');
?>
</body>
</html>

Monday 14 March 2011

Google Directions API - not bad

Here, I have provided an example of implementing Google Directions. This should give you the confidence to try more out. I recommend that you visit http://code.google.com/apis/maps/documentation/directions/ for more options.


See demo.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Google Directions API</title>
</head>
<body>
<?php
$params = 'origin=Toddington,Bedfordshire';
$params .= '&destination=Cranfield,Bedfordshire';
$params .= '&region=uk&sensor=false';
$data = json_decode(file_get_contents('http://maps.googleapis.com/maps/api/directions/json?'.$params));
if ($data->status === 'OK')
{
$route = $data->routes[0];
foreach ($route->legs as $leg)
{
foreach ($leg->steps as $step)
{
echo $step->html_instructions .'<br />';
}
}
}
?>
</body>
</html>

Thursday 18 November 2010

PHP to get current file name without the extension

This little function will return the file name which calls it minus the .php extension.

<?php

function getCurrentFile()
{
    $currentFile = $_SERVER["SCRIPT_NAME"];
    $parts = Explode('/', $currentFile);
    $currentFile = substr($parts[count($parts) - 1],0,-4);
    return $currentFile;
}
?>

How to get all the content from a directory using PHP

I've been developing a small CMS. It solves a small problem. Some of our customers would like to edit small amounts of text on a page. I don't want to create a CMS database for this. I just want to use text files. There is a tiny CMS which does this, but your website has to be in root, there is an install and it's a bit of a pig to configure.
My CMS is much simpler than that.
Anyway, to cut a long story short I created a PHP function for it which I wanted to share. It takes a directory name as a parameter then looks at that directory  and reads all the files within it. Obviously missing out those ugly  . and .. at the beginning. Manipulate at will.


<?php
function getDirContents($dirLoc)
{  
    foreach(array_slice(scandir($dirLoc),2) as $fileEntry)
    {
        echo file_get_contents($dirLoc.'/'.$fileEntry);
    }
}
?>