Tag Archive: PHP

Write CSS3 with Understandable Variables with LessPHP – Part 3

LessPHP allows you to use variables in your CSS stylesheet for the repeatable blocks of code.

In part 2, I provided you with the content of var.less. This part I will give you an example on how to use this .less file to write your own stylesheet. The provided example is based on the final project of this post on the Nettuts+.

First off, here is the folder structure for this example:

Example folder structure

Folder structure for the example

From top to bottom, they are:

css - folder

less - folder

lessc.inc.php in less folder - LessPHP compiler

main.less in less folder - source file to compile to CSS stylesheet

@import 'var';

body, html {
	@dimension(100%;100%);
}

body {
	@center;
}

#box {
  @bg-color(#e3e3e3);
  @dimension(400px;200px);
  @transition(all;1s);
  border: 1px dashed #666;
  margin: auto;
  cursor: pointer;
  position: relative;
 	:after {
 		@dimension(70%;10px);
 		@box-shadow(0;9px;20px;rgba(0,0,0,.4));
	  content: '';
	  position: absolute;
	  bottom: 0;
	  left: 15%;
	  z-index: -1;
	}
	> div {
  	@bg-color(#e3e3e3);
    @dimension(100%;100%);
    @transition(all;1s;ease-in-out);
    position: absolute;
    top: 0;
    left: 0;
    font: 45px/200px bold helvetica, arial, sans-serif;
    text-align: center;
  	:first-child {
	    position: relative;
  	  z-index: 2;
    }
 }
 :hover {
 	@rotate(;rotateY(180deg));
 	> div:first-child {
  	opacity: 0;
 	}
	div:last-child {
  	@rotate(rotateY(180deg));
 	}
 }
}



var.less in less folder - contains the LessPHP variables which I already provided it to you in part 2

index.php in css folder – contains the compile script which provided in part 1

main.css in css folder – contains the compiled CSS styles

index.php in root folder – contains the inclusion of main.css in css folder

Note that some of the code are directly copied from the above source. Also, in order to completely experience this example, you need to use Chrome or webkit compatible browsers.

Feel free to ask any question you have regarding the above code in the comment below.

Write CSS3 with Understandable Variables with LessPHP – Part 1

LessPHP

LessPHP is the PHP version of LessCSS, a CSS stylesheet language which is relied on Node.js web server. All LessPHP need is the PHP server.

In this part I walked you through the installation of LessPHP compiler and general folder structure for a one-page web app using LessPHP. In the next part, I will give you some CSS3 properties with parameters which have easy to understand variables.

The installation of LessPHP is easier than you think. After you download its source from GitHub, the only step is to copy lessc.inc.php into your web app folder and included in the page. Here is the basic structure for the folder:

Folder structure for the one-page web app

Folder structure for the one-page web app

Below is the explanation for each file and folder from top to bottom:

web app is the root of the web app.

styles contains lessPHP files and compiled CSS stylesheets.

less contains lessPHP compiler and less source.

main.less relates to main.css which I discussed below. It contains the styles information that will output to main.css.

var.less contains the lessPHP variable definitions which is imported to main.less using @import.

index.php in the styles folder is used to compile the less source to CSS stylesheet. It contains the following code:

<?php
// Convert LESS to CSS styles
include_once 'less/lessc.inc.php';
try { lessc::ccompile('styles/less/main.less', 'styles/main.css'); }
catch (exception $ex) { exit($ex->getMessage()); }
?>

main.css is the compiled stylesheet.

index.php contains the code of your web app but first you need to include the index.php from the styles folder:


<?php
include_once 'styles/index.php'; // Include the LessPHP compiler in the beginning of this file
?>

The above is general folder structure of mine for one-page web app. If you need to create a multi-page web app, you can create a include folder and include the lessPHP compiler to header.php or somewhere similar.

When you edit the stylesheet, you need to only edit the .less files and it will re-generate main.css file once the page is loaded.

In the next part, I will provide you the content of var.less which mentioned above that includes some CSS3 properties for your reference or you can use it as a template.

If you have any question about this part, post them in the comment below.

New Blog Title, New Logo

Note: As this post was written long time ago, I’m currently use Mac OS on the MacBook Air. Until I find a stable way to run Ubuntu on my MBA, I will stick to use OS X.

As you already saw, I changed the title for this blog from “Robby Chen Personal Blog” to “Ubuntu Web Coder “as well as the logo.

One reason for changing the blog title is because I’m going to stick to Ubuntu, specifically Lucid Lynx (10.04.1), since I depend on some PPAs to get the updates. Maverick Meerkat (10.10) just doesn’t work for me. I will wait until Natty Narwhal (11.04) is out and see. If this still won’t work for me, I will stay with 10.04.1 and wait for the next release… Anyway, you get the idea.

As most of you who read this blog in the past know, I used to write code in Netbeans until I discovered the hidden potential of gedit for being such a good IDE. That’s why I abandoned Netbeans and replaced with gedit in the new logo. And I renamed blog title specifically to “coder” because I would like to try writing the code in each post from now on.

Besides the gedit logo in the new logo, I have also included two groups of logos, GNU/Linux and PHP. The GNU/Linux logos include Linux penguin, Chrome OS, Android, and Open Source. The PHP logos include PHP, CakePHP, and WordPress. I also included just released HTML5 logo created by W3C. I regularly use these tools and talked and will continue to talk about them in this blog. That’s why I included them in the logo.

What do you think about the new logo, blog title, and background color?

Some CakePHP Productive Tips

CakePHP Logo

I’ve been playing around with CakePHP for the last several days. I’m beginning to enjoy using it through the CLI (Command Line Interface) tools that comes with the framework. Maybe because I spent too much time on the command line thanks to the CR-48 (Chrome OS) developer mode :) . Anyway, here are some tips I found while learning this easy to use PHP framework:

  1. During the development, it’s a good practice to change the default value for CAKE_CORE_INCLUDE_PATH both in the index.php and test.php of webroot directory in case you forgot when deploy to the server. For example, I changed the value of this constant to $_SERVER[‘DOCUMENT_ROOT’] . DS . ‘cakephp’ which is converted into localhost/cakephp. Once I deployed the application to the server, the included path will change to robbychen.com/cakephp without any modification.
  2. According to its documentation, each database has its own form control and data type relationship. For example, the tinyint data type for MySQL generates the checkbox control, whereas the boolean data type for SQLite also generates the checkbox control. It also applies to the latest stable version of CakePHP 1.3.
  3. If you want additional database options, you can download datasources plugin. This plugin also contains sqlite3 which, for some reasons, haven’t included with the CakePHP core yet. If you’re going to use SQLite in the framework without this plugin or just specify sqlite in the database config file, it will use version 2 instead.
  4. This is probably a bug in CakePHP: The CakePHP console cannot find the sqlite database file unless it’s in the root of the application folder, whereas the CakePHP web application looks for the file in the webroot directory of the application folder. The database configuration cannot be simply changed to webroot/database.sqlite. If it changes to that value, the console could find it (webroot/database.sqlite) but the web application could not (webroot/webroot/database.sqlite). The solution I decided is to make a link at the root folder to link to the sqlite file in the webroot directory. This way could both benefit the console and web application. It however does not suitable for some of you who are working on both the localhost and the production server, or often change folder, since the link target cannot be edited. The link will break once the whole directory is moved to a different machine or the target file was renamed or moved.
  5. Type cake api [type] [method] in the command line to browse through the CakePHP documentation. It is a very helpful command for use as a reference. However, you may learn some new tricks through this command, or you could use this as the primary learning resource for CakePHP assume that you already knew this command before you learn something else. For example, I found something useful for my project in the Ajax API: cake api helper ajax

I hope these tips help you to become more productive with CakePHP. If you have any questions regarding the above tips, feel free to post them in the comment below.

Download WordPress and Other files Directly to your Server with PHP copy

PHP

Intro

When I tried to get the development environment working with Chrome OS (CR-48), I thought since Chrome OS is primary working for the cloud, why am I downloading, editing, and testing the website files locally? I found out that my hosting provider, iPage, offers a file manager and a basic text editor to manage and edit my PHP files, and since I use gEdit as my main code editor, I’m pretty comfortable with the text editor.

Basic code editor

The basic code editor available in the control panel

I shortly found some useful file operation functions on the official PHP document, one of them is copy. According to its documentation, the source and destination can both be URLs since 4.3.0. This means that I can download the code from another website directly to my server using the server resources. I wrote a test page to test this function and it worked without problem.

The Code

<section id='fileDownloader'>
 <article id='urlForm'>
  <form id='url' name='url' method='post' action=''>
   <label for='urlInput'>The file to be downloaded (URL): </label>
   <input type='text' name='urlInput' id='urlInput' placeholder='URL' size='60' autofocus value="<?=($_POST['submit'])?$_POST['urlInput']:""?>" />
   <br />
   <input type='submit' value='Download' name='submit' />
  </form>
 </article>
 <?php if ($_POST['submit']): ?>
 <article id='downloadStatus'>
  <?php
  if (empty($_POST['urlInput'])): die("Please enter a valid download URL"); endif;
  $path = explode("/", $_POST['urlInput']);
  $fileName = $path[sizeof($path) - 1];
  ?>
  <?php if (file_exists($fileName)): ?>
  This file already <a href="<?=$fileName?>" title="Download file from this server">downloaded</a>.
  <?php elseif (!copy($_POST['urlInput'], $fileName)): ?>
  Download failed. Make sure that the URL is correct.
  <?php else: ?>
  Download completed. You have the option to <a href="<?=$fileName?>" title="Download from this server">download this downloaded file</a> or <a href="<?=$_POST['urlInput']?>" title="Download from the original server">download the original file here</a>.
  <?php endif; ?>
 </article>
 <?php endif; ?>
</section>

Note that I’m just staring to learn HTML5, so I can’t guarantee the above syntax is correct.

Questions

If you have any questions regarding this script, leave a comment below. And please don’t spam my server when testing on the test page, If you want to test it on your localhost, you can download the source code here.

A Very Nice PHP Array Technique

Introduction

You properly already knew the following code:

$strings = array();
$strings[] = "apple";
$strings[]="bamboo";
$strings[]="cat";

This will contain an array of strings:

array(1=>"apple", 2=>"bamboo", 3=>"cat");

However, this is not very useful for multi-dimensional arrays where each array in a parent array contains the same keys and different values like the database array. This is where associative arrays come into play. The code below uses the same technique as above without using the array_push function.

Source Code

foreach ($strings as $row) {
 foreach ($row as $col=>$val) {
  $data[$col] = $val;
 }
}

Explanation

As you can see from the code, each array in the $strings array is copied into a new $data array. I can then use this newly copied array just after the end of second foreach loop to do something. For example, insert it into another database to change the database driver (MySQL to SQLite, for example).

Please share it in the comments below if you have any other uses for this technique.

Get File Name without Extension using pathinfo() PHP function

Back Story

I recently have a need to import a list of images into the database for easier management. Because they are all PNGs and JPGs, I was trying to find a way to separate each image to file name and extension. I could use two explode() functions to take out PNG and JPG extensions. However, the file name could be thief.jpgTopng.png which use these functions will convert it to thiefTopng.This type of issue is very common at least to me. Thanks to one of the comments on this page, I discovered an useful PHP function for working with file names called pathinfo().

The Code

The usage of pathinfo() is very easy compare to explode():

exec("ls {$path}", $images);
foreach ($images as $image) {
 $file = pathinfo($image); // get the path info
 $fileName  = $file['filename']; // get the file name
}

As you can see, I use exec() function to execute ls command to list all of the files inside the specified directory.

My First Regular Expression Statement

regex

Sorry for not posting any updates for the past week. I have been very busy with the schoolwork lately. For this post, I will discuss about the first basic regular expression statement that I wrote.

During my quest searching for more AJAX tutorial using jQuery, I found the jQuery history plugin. It enables the back button and manipulate browser history for AJAX applications. What I loved about this plugin is that the page with a hash sign at the end of the URL will automatically go to the page specified after the hash sign. For example, the URL http://localhost/index.php#products normally would ignoring the hash sign and go to the home page instead of products page. With history, this URL will go to the products page directly once it is entered into the address bar.

On the demo page of history plugin, I noticed a regular expression embedded in the code. I didn’t care about the expression very much at first because I thought I didn’t need it. But after experimenting with it, I came up with this jQuery code:

$(document).ready(function() {

 function ajax404(page) {
   $("#content").load(page + ".php");
   $("#content").ajaxError(function(e, xhr) {
     if (xhr.status == 404) {
       page = page.replace(/^.*//, "");
       $("#content").html("Page " + page + " not found.");
     }
   });
 }

 $.history.init(function(url) {
   if (url == "") {
     $("#content").load("home.php");
   }
   else {
     ajax404(url);
   }
  });

 $("#products a").hover(function() {
   $("#products ul").css("visibility", "visible");
  }, function() {
   $("#products ul").css("visibility", "hidden");
  });

 $("#menu a").click(function() {
   var menuLink = $(this).context.href;
   menuLink = menuLink.replace(/^.*#/, "");
   ajax404(menuLink);
  });
});

The regular expression in the last click event is the same as the one in the history demo page. According to regular-expressions.info, it means to remove all the characters before the hash sign along with the hash sign. For example,

http://localhost/index.php#products/juice
(Note that the following examples are based on this URL)

After the regular expression used with replace function, the new value will be

products/juice

The ^ character in the expression means to start with. The .* characters means any character. In the above code, ^.*# means to start with any character until the hash sign.

In the function ajax404() of the above code, I used the regular expression ^.*/ to get rid of all the characters before the backslash (/) sign along with the backslash sign. This produced the following result:

juice

As the function name implies, I used this expression to display the page name when the file is not found. The above expression would produce the following error message:

Page juice not found

instead of

Page products/juice not found

if not used with the expression, which is not a good error message.

As with PHP and C, the forward slash (\) represents the escape character. In the code above, the normal usage of backslash (/) character is the same as the use of quotation marks in PHP. If used with escape character, it would output a normal backslash character. For example,

/

would produce

/

To learn more about regular expression, visit regular-expressions.info. And if you have any tips on how to work with regular expression, please share them in the comment below.

By the way, I will continue to post C programming tutorials later today.

C sizeof Operator

The sizeof operator is used to determine the memory size of a variable or a type in bytes. Here are some examples:

size = sizeof array; // determine the size of an array
size = sizeof array[i]; // determine the size of i th element of the array
size = sizeof(float); //determine the total size of the float variable type in a program

As you can see, when used with variable types, the sizeof operator must use parentheses around the type name.

Below is the sample code for this operator:

/*
 *
 * sizeof.c
 *
 * Program to demonstrate the sizeof operator
 *
 * by Mark Virtue, 2001.
 *
 */

#include <stdio.h>

main() {
 int x;
 short arr[20];
 double y;
 char string[51];

 printf("The size of x (an integer) is %lu bytesn", sizeof x);
 printf("The size of arr (an array of 20 shorts) is %lu bytesn", sizeof arr);
 printf("The size of one element of arr (one short) is %lu bytesn", sizeof arr[0]);
 printf("The size of y (a double) is %lu bytesn", sizeof y);
 printf("The size of string (an array of 51 char) is %lu bytesn", sizeof string);
 printf("The size o one element of string (one char) is %lu bytesn", sizeof string[0]);
 printf("The size of a long is %lu bytesn", sizeof(long));

 fflush(stdin);
 getchar();
}

Note that I made a little change to the above code. It originally has %d in the printf statements instead of %lu. Since the gcc compiler interprets the output of sizeof operator as a long unsigned int, I changed to %lu as long unsigned. Interestingly, %li (long integer) also works.

Here is the sample code that shows the usage of this operator:

/*
 *
 * sizeof2.c
 *
 * Program to demonstrate the use of the sizeof operator
 *
 * by Mark Virtue, 2001
 *
 */

#include <stdio.h>

main() {
 int array[] = {1, 34, 65, 778, 111, 23, 782, 75, 94, 3, 100, 22, 58, 145, 72, 99, 43, 67, 278, 98, 53};
 int total = 0;
 float average;
 int i;

 for (i = 0; i < sizeof array / sizeof array[0]; i++) {
 total += array[i];
 }

 average = total / (sizeof array / sizeof array[0]);

 printf("The total is %dn", total);
 printf("The average is %.3fn", average);

 fflush(stdin);
 getchar();
}

The usage of sizeof operator in the for loop at the above code reminded me the sizeof function in PHP. Both usages are similar except C needs to divide by the size of one element in the array since C has different sizes on each variable types.