by Niklas Waller on August 13, 2009
in PHP
I found a solution made by someone called P’tit Marcel on on how to display a text mass in two columns in php.
Here’s the function that returns the middle position. It takes into account a text mass that can also contain HTML so that it doesn’t break between two tags.
function split_pos($text) { /* find middle space in text */ $mid = (int) strlen($text)/2 – 1; $cut = strpos($text , ‘ ‘ , $mid); $part1= substr($text , 0 , $cut + 1);
$pos1 = strrpos($part1 , ‘<’); $pos2 = strrpos($part1 , ‘>’);
if (($pos1 < $pos2) or ($pos1 === False)) { return $cut; /* no html tag around */ }
$pos3 = strpos($text , ‘>’ , $cut1 + 1);
if ($pos3 !== False) { return $pos3; /* end of middle html tag */ } else { return $cut; /* unbalancing < > */ } } |
Call it like this to display the text with columns:
$middle_pos = split_pos($text); Print “<table><tr>”;
// First column Print “<td>” . substr($text, 0, $middle_pos) . “</td>;
Print “<td style=’width:30px’></td>”;
// Second column Print “<td>” . substr($text, $middle_pos + 1) . “</td>”;
Print “</tr></table>”; |
Tagged as:
columns,
html,
php,
split
by Niklas Waller on July 23, 2009
in PHP
Prerequisites:
-
-
-
Make sure you have ‘Console’ and ‘Net’ enabled in Firebug.
Download and install the . In my case it is just a matter of dowloading a directory with 4 files, uploading them to the server in some directory and then referring to the directory like below.
At the top of your page add the following:
/* PHP debugging */ require_once(‘FirePHPCore/FirePHP.class.php’); ob_start(); $firephp = FirePHP::getInstance(true); |
Where you need to log something use this:
| $firephp->log(‘Log message’); |
There are also much more advanced functionality for error, exception and assertion handling, grouping, logging, tracing etc. Read more .
Tagged as:
debug,
log,
php
by Niklas Waller on June 11, 2009
in PHP
Solutions for our customers give them the possibility to administrate their website completely on their own without any help (except for rare special cases of course). One thing I have been missing here is a backup capability.
If the MySQL data for some reason gets hacked or is lost for some other reason we can only rely on the web hotel’s backup routines and even if they have some it might not be that easy or fast to get the backup data.
So the thing that I want to do here is to allow the customers themselves to backup their data, either manually by clicking a button or by scheduling the backup.
I found the perfect class for this purpose – written by . It allows you to easily create and instantiate the object and then set a couple of parameters dependent on what you want to do.
- You can take a full backup or define specific tables.
- You can backup just the structure or the data.
- Define during backup if the file should be save to the server or downloaded to the client.
- Choose to zip the backup files (good when storing them on the server)
- Specifying the name
- And more…
I will myself add a log functionality så that a row is created in a logging table when a backup has been made. In the administration interface the user can then create a new backup or see previous backups and choose to download previous backups taken.
I will also list tables from the MySQL database so that a user can choose which ones to backup by clicking a couple of check boxes.
Tagged as:
backup,
mysql,
php
by Niklas Waller on May 28, 2009
in PHP
I stumbled upon this cool online tool a few days ago called . It lets you create connections to your FTP-servers where you keep your website and PHP files. You can make several of these connections.
When this is done the data directories and files from the FTP-server are displayed for browsing. Double-click on a file to open it and edit it. When you save it saves it back to the FTP-server.
You can also create files and folders and set file permissions. It is a bit slow but a very good backup option to have in case you would need to make an update but you left your computer at home on your sudden trip to Kuala Lumpur and only have an Internet connection on the nearest Internet café.
It seems to be a quite young application as well so maybe we can expect some more functionality in the future like actually being able to store your files and folders there as well (for free of course).
Tagged as:
developing,
editor,
online,
php
by Niklas Waller on March 31, 2009
in PHP
I have a MySQL database which has charset latin1_swedish_c1. When characters are saved to the database via SQL the swedish characters are translated into very odd ones.
You can get around the problem by encoding the page with charset UTF-8, however if you want your meta tags or other comments to have swedish characters or some other special characters, the page will not validate. If you use charset ISO-8859-1 for the page, the meta tags will look nice, but the data from the database will not. So I am stuck here between not being able to read the data from the database and not being able to validate the page.
The solution is simple however. Before putting the string in your update or insert SQL clause, use the utf8_decode function. This will make the characters being saved as what they are, i.e. å,ä or ö in my case. This is a predefined function in PHP that you can use:
| $str = utf8_decode($string); |
Tagged as:
characters,
charset,
encode,
mysql,
sql,
swedish,
utf-8
by Niklas Waller on February 17, 2009
in PHP
If you would like to have a list of the say 10 or 20 latest referrers to your blog or site, it is quite easy to accomplish a simple solution pretty quickly. Here’s an easy and fast way of how to do it with PHP and MySQL.
1. Create a new table in your MySQL database called ‘referrers’ with these fields and properties. This is the place where all data about referrers and requested content will be stored.
| id : |
int (10) primary key auto-increment |
| referrer: |
varchar (500) |
| request |
varchar (100) |
|
2. Paste this script to the page where the visitors arrive. Each time someone is referred to this blog a new entry is created in the MySQL table.
<?php /* Get the address of a possible referrer */ $referer = $_SERVER['HTTP_REFERER'];
/* If the visitor has been referred to this blog from some other site if ($referer != “”) {
/* Get the requested page */ $request = $_SERVER['REQUEST_URI'];
/*Create a sql-query and execute it */ $query_referer = sprintf(“INSERT INTO referrers (referrer, request) VALUES ( ‘ ” . $referer . ” ‘, ‘ ” . $request . ” ‘ )”; $referer_result = mysql_query($query_referer); } ?> |
3. Paste this piece of code where you want the referrer list to be on your site.
<?php /* Get the 10 most recent referrers */ $query = “SELECT * FROM referrers ORDER BY id DESC LIMIT 0,10″ $rs = mysql_query($query);
/* Loop through the list of referrers. Each row displays the first 25 characters of the referrer address and a link to it. If you hover it, the whole address and the requested page is displayed. */ while ($row = mysql_fetch_assoc($rs)) { Print sprintf(“<a href=\”%s\” title=\”%s\” style=\”cursor:hand;cursor:pointer\” target=\”_blank\”>%s</a><br>”, $row['referrer'], “REFERRER ‘” . $row['referrer'] . “‘ REQUESTED ‘” . “YOUR_DOMAIN” . $row['request'] . “‘”, substr($row['referrer'], 0, 25)); } ?> |
Take a look at the bottom right of Wohill to see this in action!
Tagged as:
mysql,
php,
referer,
referrer
by Niklas Waller on November 25, 2008
in PHP
I have been searching for a good solution for uploading files and images from a html form to a server for some time and finally found the superior way – written by .
| “This PHP script uploads files and manipulates images very easily. The perfect script to generate thumbnails or create a photo gallery! It can convert, resize and work on uploaded images in many ways, add labels, watermarks and reflections and other image editing features. You can use it for files uploaded through an HTML form, a Flash uploader, or on local files. It uses the GD library. This script is released under the GPL Version 2. If your project is not GPL, commercial licenses are available.” |
So using the default settings, that you get from downloading the , you can choose which type of file upload that you want to do. Look at the file “index.html” for the options. You can either choose to upload a file, an image or multiple files/images.
For a specific solution I had to upload an image and at the same time a thumbnail for that image. This class makes it happen the best possible way by letting you create the thumbnail from the original one during the upload. You can decide the size of the file and even crop it. Read more about the many possibilities .
The solution that I implemented have an upload page that look like this.

I have added functionality for being able to specify in which category an image belongs to. This will be more clear on another blog entry in the near future where I use the categories to display images in different photo galleries,
The other part you need to take a look at is the php-page to which the files are posted to. This page uses functionality from the class.upload.php class to process the files. In the package the example file’s name is ‘upload,php’. Posting an image and at the same time creating a thumbnail would look like this on the controller page where the form is posted.

So if you’d like to jumpstart and try this out I recommend to download the package and play with the index and upload files and you should be running this in a minute. Read the docs to find the ways to manipulate the images – there are many good methods.
Tagged as:
file,
image,
resize,
thumbnail,
upload
by Niklas Waller on September 4, 2008
in PHP
If you for some reason would like to display files in a directory on the web server there is an easy way to do this. You might for example like to display all images in a directory in a select box on a web page.
<?php // Set folder $folder = “images/”;
// And get a handle to it $handle = opendir($folder);
// Create an array containing the files in the current directory: while ($file = readdir($handle)) { $files[] = $file; } closedir($handle); sort($files);
// Print the file names print “<select name=’imageNames’>”; Print “<option value=’Choose image’>Choose image</option>”;
// Loop through array foreach ($files as $file) { // Don’t display “.” or “..” if (($file != “.”) And ($file != “..”)) { print sprintf(“<option value=’images/%s’>%s</option>”, $file, $file); } } print “</select>”; ?> |
If you would like to be more specific on which files not to display (the if-statement in the for-loop) you can for example use function ‘substr’. In the following example files that begin with “_x” will not be displayed.
| (substr($file, 0, 3) != “_x”) |
Tagged as:
file
by Niklas Waller on July 31, 2008
in PHP
There are some basic and useful lines of code that you often end up using when programming in PHP. I’ll put 10 common ones I often use here, partly for myself but foremost for you readers. Please feel free to complement if you have any suggestions or improvements.
Redirect user to another page:
| header(“Location: http://www.thedomain.com/aPage.htm”); |
Include the contents of another page:
include(‘include/aPage.php’); /* Warning message on failure */ // OR require(‘include/aPage.php’); /* Fatal error message on error and halt processing. */ |
Create a connection and set current active database:
| /* Set values of $mysql_host, $mysql_database, $mysql_username, $mysql_password */
$link = mysql_connect($mysql_host, $mysql_username, $mysql_password) or die(“Could not connect to database: ” . mysql_error());
mysql_select_db($mysql_database, $link) or die(“Could not set database”); |
Create and execute simple select-query to SQL-database:
| $select_query = “SELECT * FROM someTable”;
/* Perform Query */ $select_result = mysql_query($select_query);
/* Check result */ if (!$select_result) { $message = ‘Invalid query: ‘ . mysql_error() . “\n”; $message .= ‘Whole query: ‘ . $select_query; die($message); } |
Create random string:
function createRandomString($len) { $source_arr = array(“0″,”1″,”2″,”3″,”4″,”5″,”6″,”7″,”8″,”9″);
for ($i=0; $i<$len; $i++) { $random_key = array_rand($source_arr); $random_str .= $source_arr[$random_key]; }
return $random_str; } |
Create time and date variables on different :
$dt = date(“Y-m-d”); // 2008-07-18 $dt = date(“m/d/Y”); // 07/18/2007 $dt = date(“F j, Y, g:i a”); // July 18, 2008, 1:22 am |
Set pointer to the first position of a mysql resultset:
| mysql_data_seek($result, 0); |
Mail function:
/* Send mail */ function sendMail($to, $subject, $message) { $headers = “From: \”From address\” <fromAddress@mail.com>” . “\r\n” . “Reply-To: \”Reply address\” <replyAddress@mail.com>” . “\r\n” . “X-Mailer: PHP/” . phpversion(); mail($to, $subject, $message, $headers); } |
Replace all occurrences of a search string with a replacement string:
/* $string_before => ‘abcdef abcdef’ */ $resultString = str_replace(“a”, “”, $string_before); /* $resultString => bcdef bcdef */ |
Url-encode a string (for use in a query part of an url for example):
| $url = “http://www.domain.com/test.php?q=” + urlencode($query_part_of_url); |
Tagged as:
example,
php,
reference
by Niklas Waller on July 29, 2008
in PHP
Let’s say you have an id and you want to lookup the corresponding name or other field from an sql table that relates to this unique id. Here’s an example function in PHP that does it for you, but it might need to be tweaked a bit to fit the design of your sql-tables.
/* Get category name from a category id */ function getCategoryName($categoryId) { $select_category_query = sprintf(“SELECT * FROM table_name WHERE id=’%s’”, mysql_real_escape_string($categoryId)); $select_category_result = mysql_query($select_category_query);
if (!$select_category_result) { $message = ‘Invalid query: ‘ . mysql_error() . “\n”; $message .= ‘Whole query: ‘ . $select_category_query; die($message); }
$row = mysql_fetch_row($select_category_result); return $row[1]; } |
The function above assumes that the sql-table has the following structure:
| Field names: |
id |
categoryName |
Field2 |
Field3 |
| Example row: |
34 |
‘Some category’ |
‘donk’ |
‘blabla’ |
The result row that comes from the php-command ‘mysql_fetch_row’ returns an array with the field values that corresponds to a row in the sql-table. The result row is also indexed as an array. This means that the first value is on index 0. So the value of field name ‘id’ is on position 0 in the resultset, i.e. $row[0], the value of field name ‘categoryName’ is on position 1 and so on. Hence, to get the category name in the example above with the specified sql table structure, field ‘categoryName’ is represented by $row[1] in the resultset.
When you have several tables in an application that relates to each other it is common to use values as id’s instead of names. The reason for this is partly to save space but mainly to actually be able to change values only a one place without having to be forced to update large tables to replace strings.
So if you have a table where each row is a blog entry and one of the fields specifies the category of the blog entry you could choose to store this as the actual category string or an id which corresponds to a string in another table – a category table. If you ever need to change the name of a category you would need to update the entire blog entry table if you choose the string approach. If you would store it as an id you would only have to make the change in the category table.
The possible backside of this is possibly the extra database queries that has to be performed each time a blog entry is read to get the category name. Anyway, this is the place where you would need this function.
Tagged as:
mysql,
php,
sql