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?

Optimize MySQL Database

For a long time since I created this blog, I had been struggled with the WordPress’ slowness. I sometimes wondered why are others’ WordPress so fast compared to mine. Then I blamed my hosting provider’s MySQL server not fast enough.

Until today, I googled for “improve mysql performance shared host” and found out about this article on optimizing MySQL performance. I logged into phpmyadmin on the server and look for the word “optimize”. At first, I was not able to find it. After carefully read the article, I found “optimize table” option under the “With selected:” drop down menu at the very bottom of Structure page.

Position of the "With selected:" menu

The arrow shows the location of the “With selected:” drop down menu which contains “Optimize table” option, click the image above to see the enlarge version.

After some experimentation, I was able to manipulate the same task in the command line (in my localhost of course, since ssh access is not available for my hosting account). The query for optimizing tables is easy:

OPTIMIZE TABLE table_name;

Note that you need back stick operator (`) if you need to use SQL keywords as table name. For example,

OPTIMIZE TABLE `table`;

Also note that SQL is case-insensitive in case you don’t know.

The video below shows you how to optimize MySQL table in action:

What do you think about this tip? Please leave your response below.

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.

Install Web Server with PHP on Ubuntu

Ubuntu Apache PHP

Introduction

I recently noticed that some of you are not web developers, just general GNU/Linux users, especially through the wallpaper slideshow PHP script comments. Therefore, I decided to write a tutorial post dedicated to those who want to use my script but can’t open it through the browser.

Steps

Before I begin, I want to be clear that this tutorial uses command line interface to do all the stuff. If you don’t feel comfortable using the command line, then I suggest you to start using it more often. One more thing I want to mention is that unlike others, I like to use aptitude rather than apt-get because it offers more features and has detailed output during the operations. With these in mind, let’s begin the installation and setup tutorial:

  1. Open the terminal through Applications -> Accessories -> Terminal.
  2. Type
    sudo aptitude install mysql-server phpmyadmin

    into the command line, enter the password for your Ubuntu username, and start the installation. Note that by installing phpmyadmin, it will automatically install apache2, mysql-client, php5, and other required dependencies. However, mysql-server is not one of its dependencies.

  3. After the installation, it will ask you to setup mysql-server‘s password and phpmyadmin‘s password. Note that the first setup screen of phpmyadmin is ask you to enter mysql-server‘s password that you entered earlier. After this initial screen, you can whether enter a different phpmyadmin password or the same password as mysql-server. This password is not very important to me since it is used for remotely access phpmyadmin interface which I don’t use.
  4. Now you can access the web server by typing
    http://localhost

    into the browser’s address bar to see the welcome page.

  5. Copy the scripts you want to run into the /var/www folder, delete the index.html inside this folder, and refresh the page:
    sudo cp /path/to/your/scripts/folder /var/www
    sudo rm /var/www/index.html
  6. Now you can see the list of all the files available in the /var/www directory. You can click any of the PHP files and begin using the scripts.

Note that if you want to access the phpmyadmin interface, just go to

http://localhost/phpmyadmin

in your browser and type mysql-server password you setup earlier. As for the use of the phpmyadmin, you need to refer to its documentation.

If you have any issues following above instructions to install the web server or the PHP files are still not working, please feel free to leave a comment below. I will help out ASAP.

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.