Tag Archive: PHP

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.

More About CA272 (Pro Website Development) Final Project

CA272 Final Project LogoSince I mentioned the CA272 final project a little in the last post, I think it’s best to talk more about this topic.

I took CA272 class in the Spring of 2009. It is known as Professional Website Development. Actually to me, this is not a professional class. Instead, it is a very basic class: it doesn’t include sever-side script languages nor JavaScript, just basic HTML4. At that time however, I didn’t know jQuery and PHP until the very end of the semester.

As you can see through the source code of the Final Project page, all of the AJAX and JavaScript functions were created by myself. Because I discovered jQuery during the last week of final project submission, I hurriedly added some animated transitions to the pages using jQuery without the deep understanding of jQuery. Therefore, the animation looks a little incomplete.

The presentation below explains the most of features on the site:

Note that because I don’t have my own website at the time, I copied all the final project files to a free hosting. Therefore, the URL at the end of the video is not valid anymore, use http://robbychen.com/ca272/final/ instead.

Remove Part of File Names using PHP

Since David’s Batch Processor was pre-installed in GIMP on Ubuntu Studio, I used it extensively in the ICAF Gallery project.

My goal for these images is to resize their thumbnail version to 10KB or smaller and retain the original size for the enlarged version.

  1. Because most of these images are in different resolution, I randomly selected the scale value in the Batch Processor to resize the images.
  2. Then I had to manually view the file size of each image to see whether or not an image has to be resized again.
  3. After the differentiation, I moved the images that need to be resized once more to a new sub-directory and started the above process one more time.
  4. I would repeat these steps again and again until all the thumbnail version of the images are under or equal to 10KB.

During the early use of the Batch Processor, I missed a very important feature – that is to save the newly processed images to a different folder. This resulted my decision to write this Batch File Name Remover script.

The source code for this script is very easy to understand. It’s just some PHP functions plus two Linux commands: ls and mv.

I always place a postfix after the file name of processed thumbnails: “-thumb”. Because of that, I need to remove this postfix whenever I repeated the above resize steps.

The ls command is used to list the file name that contains the specified characters into an array. The mv command is used to remove the specified characters from the file name using PHP explode function. I used PHP instead of native Linux Bash script because PHP is easier than Bash for me :).

The source code for this script is available here.

Below is its source code:

<!doctype html>
<html>
    <head>
        <title>Batch File Name Remover</title>
        <style>
            table {
                width: 80%;
                margin: 0 auto;
            }
            table tr td {
                width: 50%;
                text-align: left;
            }
            table tr td[colspan="2"] {
                text-align: center;
            }
            .original, .changed {
                font-style: italic;
            }
            .original {
                color:red;
            }
            .changed {
                color:green;
            }
            #error {
                color:red;
                font-weight: bold;
            }
        </style>
    </head>
    <body>
        <h1>Batch File Name Remover</h1>
        <?php
            if (!isset($_POST['submitted'])) {
        ?>
        <table border="0" cellpadding="0" cellspacing="0">
        <form action="" method="post">
            <input type="hidden" name="submitted" />
            <tr>
                <td><label for="location">Folder Location: </label></td>
                <td><input type="text" id="location" name="location" size="100" value="/home/" /></td>
            </tr>
            <tr>
                <td><label for="remove">Characters to remove: </label></td>
                <td><input type="text" name="remove" id="remove" size="100" value="-" /></td>
            </tr>
            <tr><td>&emsp;</td></tr>
            <tr>
                <td colspan="2">
                    <input type="submit" value="Remove" />
                    <input type="reset" value="Restore default value" />
                </td>
            </tr>
        </form>
        </table>
        <?php
            }
            else {
                $location = $_POST['location'];
                $remove = $_POST['remove'];
                $fileList = exec("ls '{$location}'", $files);
                $notContain = 0;    // Initialize the number of file names that doesn't contain the specified characters

                for ($i = 0; $i < sizeof($files); $i++):
                    if (strstr($files[$i], $remove)):
                        $charsRemain = explode($remove, $files[$i]);
                        exec("mv '{$location}/{$files[$i]}' '{$location}/{$charsRemain[0]}{$charsRemain[1]}'");
                        echo "<span class='original'>{$files[$i]}</span> renamed to <span class='changed'>{$charsRemain[0]}{$charsRemain[1]}</span><br /><br />";
                    else:
                        $notContain++;
                    endif;
                endfor;
                echo "<br />{$notContain} file name(s) do(es)n't contain the character(s) \"{$remove}\".";
            }
        ?>
    </body>
</html>

And here is the code in action:

Video coming soon …

Changing Back to the Original Schedule and First Video Post (Updated)

Update (12/08/2010): For some of you having trouble to run the PHP script, I posted a tutorial on how to install web server with PHP to help you who are non web developers to run the PHP scripts I wrote. Take a look here and leave a comment if you have any questions.

Update (08/25/2010): The video quality has been improved thanks to OpenShot. Note that to watch the original HD quality, you must switch to 720p or 1080p. I also fixed the PHP script to exclude the XML file inside the background.xml file so that the slideshow can run smoothly without an empty image.

After weeks of consideration, I finally decided to change back to my original post schedule of one post per day. Two posts each day simply doesn’t work for me.

I also plan to make a video version of the post along with each post. Here is my first video showing how to create a wallpaper slideshow in Ubuntu, one of the popular posts I wrote back to March of this year:

The steps in the video are different from the post. I recorded this video this afternoon. Just before that, I wrote a PHP script that can generate background.xml file for me.  You can download the PHP script here:
http://blog.robbychen.com/Ubuntu/slideshow.tar.gz

To use this script, you must first change the permission of the folder where the images are to 777. You may change it back to original permission after that for security reason.

If you have any problem running this script, please leave a comment below.

My Latest Project

I have been volunteering at ICAF (International Child Art Foundation) since April of this year. When I first started off, I was assigned to be a video editor to edit pre-recorded videos for some international festivals. The reason why I selected this position is probably because I put the video editing skill on my resume :) I used Kdenlive and Openshot interchangeably to edit these videos. Sometimes I also used Audacity to sync between left and right channel of the videos.

After three months of video editing, I was just beginning to love to edit videos. However, I assigned to redesign the gallery page on the ICAF website two weeks ago. This is my second web development challenge. My first challenge was to build the first website for another non-profit organization. Although that project was abandoned long time ago because the interruption of school work, I learned the existence of server-side scripting at that time and wrote the first PHP application, the contact form on my website. This time I need to place thousands of children’s artworks and some other pictures to the gallery page in an organized layout.

I know that I have to use pagination for this project. It’s my first time to create pagination pages using PHP. The original design shown below was using JqPageFlow jQuery plugin to implement the pagination as the user scroll down the page.

ICAF Gallery Original Desgin

ICAF Gallery page original design

After some more research, I thought that the infinite scrolling is not good for bookmarking since the manager specifically pointed out that he wants to have a back button for each page. Therefore I revised the design to use the traditional pagination method similar to Google:

ICAF revised gallery layout

Revised ICAF Gallery page layout

Note: The next three linked pages are no longer available as I’ve lost them. Sorry for the disappointment.

Based on the above design, I wrote a test page to test my pagination code. This page is still under development. I will integrate the code into the original page once I completed the testing stage. You can download the source code for this page here (I didn’t include the image files since these images are over 1.5 GB). Note that I used exec PHP function to execute ‘ls’ Linux command to output the image file names to an array rather than use a loop or a database table to process file names. This page also contains a script to split different parts of the file name since these names followed a specific pattern: “country-firstNam_lastName-age-thumb.png” as well as some knowledge I got from the C for loop tutorial. Also note that this is the test code, meaning that I haven’t added extensive comments to the code yet.

http://php.net/manual/en/function.exec.phphttp://php.net/manual/en/function.exec.php

Pass a Value to Multiple PHP Variables

I had been taking UMUC 411 this week, an one-week online test drive class for University Maryland University College. I was too active in the class that I didn’t have anything to write about on the blog. Now the class was over, I’m back to schedule to finish my website redesign project.

I decided that today I’ll be focused on “Follow me” section:

Click the image to enlarge

This section was made up by four images. The first one is RSS feed and the last three are social networks. I noticed that the title, alt, and part of the image location for social networks have the same content. Therefore I came up with the following PHP line to pass the value in the title variable into both alt and image location variables:

$image = $alt = $title;

In the above statement, because of the pass variables rule for PHP, I placed title variable to the farthest right of the equal signs and placed variables need to be distributed before the title variable which contains the original value. For instance, I assigned “Twitter” string to $title. $image and $alt would also assign “Twitter” string.

Four PHP Command-Line Functions

Typically I never read the technical articles on ibm.com. They are long and complicated. However, I was very interested on an IBM article today when I googled “php linux command”. It is titled Use Command-line tools in PHP. I experienced shell_exec(), exec(), passthru(), and system() functions by following the article. It explains the different usages between these four functions. To summarize them:

  • shell_exec() is similar to backtick(`) operator which I used most often.
  • exec() assigns its output result to an array variable. Apart from that, it is the same as shell_exec().
  • passthru() directly outputs the result without using the echo statement, but you can assign the last argument to it to output the error code for debugging purpose.
  • system() acts like a hybrid between passthru() and exec().

One function I was having trouble is the system() function. The output of the function is similar to the passthru() function. However, I later aware that if a variable assigned to the system() function, the function outputs an array so that I can process them line by line.