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.

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

Update (04/17/2015): I know that I need to use VPS in addition to optimize MySQL tables for increasing WordPress speed. I will try Digital Ocean later this year. But for now, I will stick to my share hosting account until it expires at the end of this year.

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.

What do you think about this tip? Please leave your response 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.

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.