Web Development

Web Development Tips & Tricks, the things that you don’t want to figure out.





Archive for the ‘PHP

PHP.JS – Your Javascript PHP Library

Tuesday, August 4th, 2009

PHP.JSThe tile may have been a wee bit confusing, partially intended. PHP.JS is one of the most useful tools I’ve seen around, and boy did they do a good job. So, what is it, specifically?

PHP.JS is a Javascript library that has converted pretty much the entire PHP library into Javascript. This is their description:

“PHP.JS is an open source project in which we try to port PHP functions to JavaScript. By including the PHP.JS library in your own projects, you can use your favorite PHP functions client-side.”

It’s completely free (thank you, open source) and can help enormously.

The main question that was on my mind was, “Do I have to download the whole thing?” After all, something that comprehensive is probably pretty hefty.

The answer, thankfully, is no! They have every function broken out into pieces and the ability to download a wide variety of packages, and each package can be modified to add or subtract individual functions.

Well, that’s it for today! If you can’t think of many uses, let me know, because I can think of a plethora of uses.

Have a great day!

-Kerry

osTicket – Open Source Support Ticket Script (A Winner!)

Wednesday, October 1st, 2008

osTicket

I posted two rants yesterday, all about bad software and websites.

I was working on SendArticles.com, a new service that Studio98 just launched, and I decided I wanted a support system better than the ghetto contact form we had installed. So, I searched for “open source ticket system”.

The second listing appealed more than the first, and it was osTicket. I had no idea what to expect. I have never worked with the back end of a ticket system before, and never anything to do with installation.

So, I was almost immediately sold with their presentation of the product. I downloaded, installed, and voila, it was up and working!

I did have to go to their Wiki for a couple questions, but that was easy enough. I setup an email pipe system (never done that before), and it worked immediately.

The next step was integrating it. I have integrated many open source systems before. Never has it been this easy. I copied and pasted my header and footer includes to replace the ones they had, and voila, it all fit in like magic!

It still worked, and after messing with the system I had a fully functional support system that just took a few hours to install, customize and implement. All from scratch, with no prior experience.

5 stars to osTicket!

Shrinking Javascript the Better Way

Thursday, February 28th, 2008

Hello everyone!

There are many ways to shrink or obfuscate Javascript, simply search Google and you should find plenty of results. I found that many are programs that shrink it, then you upload the new code, which I was going to use until I found a better solution.

I found two that were recommended, jspacker and JSMin. After searching for jspacker and finding their site down, I went to JSMin. I found links at the bottom for PHP code that would do it on the spot, which made me happy because I figured I could figure out a way to do something tricky with it, which I did.

Through the use of .htaccess, JSMin and another file I created, I made the site I was working on automatically shrink all my Javascript files when called, but look completely normal in Dreamweaver.

Here’s the code:

.htaccess

Options +FollowSymLinks
RewriteEngine on

RewriteRule ^js/(.*).js$ /js/minimize.php?jsPage=$1 [L]

Quick note, I keep all my Javascript files in a folder called “js” which is also where “minimize.php” is located. You can adjust this according to your setup.

includes/minimize.php

<?php
require(‘../includes/jsmin.php‘);

// Output a minified version of the Javascript file.
echo JSMin::minify(file_get_contents($_GET['jsPage'] . ‘.js’));
?>

Again, should adjust the include of the “jsmin.php” which can be downloaded here. Also, with the way I set it up, “minimize.php” must be in the same folder. You can adjust all of this however you like, but this was the best for my use.That’s it! Basically what’s happening is when the site calls your “example.js” file, it instead reads the file “minimize.php?JSPage=example”, which then minimizes and outputs the “example.js”.

-Kerry

PHP, Cookies, MySQL & Headers

Monday, January 21st, 2008

I was recently implementing a persistent login feature and stumbled across a website that did it in a more unique way, seemingly more secure: Persistent Login Cookies Best Practice. I thought it was a smart way to use cookies and decided to use it.

Now, the way IÂ set my system up was that someone would enter a username and password, which it validates and then sends a request to my MySQL database to make sure that it matches. Upon matching, it sets a cookie using the method mentioned above.

One things I do is I like to use includes to store variables procedures, etc. I always, always, store database connection data in an include. I don’t like to have any data on a page where someone in a passing glance at my screen could get that information, or something of that nature. So, just like any other page, I included the database connection, sent the queries out, then tried to set cookies.

I received the error “headers already sent out”, pointing to my database connection include. This lead me to believe that the functions themselves sent out headers, and so I would have to some weird way of settings cookies like reading another page with it as a query string and a lot of unneeded complexity would be added.

I decided to mention my problem to an ASP.NET programmer, who didn’t use cookies much and we ended up arguing because he wasn’t understanding my problem. In a fit of frustration, I replaced the contents of the include with the call to the include – meaning the database connection data was now on page.

It worked.

Why did this work? I didn’t know. This led me to believe that including a file sent out headers. So, to prove my point, I included another file.

It still worked.

I then thought because the other include I was using only contained variables, and the database connection include called a function, that you couldn’t call a function within an include, because that would send headers out.

Wrong again!

I did more tests and finally gave up trying to exclude the database login information in an include. I still don’t understand exactly why, I even tried to store just the variables of the information and then do the calls in the program, which didn’t work.

I continued with my work, going on to other things, and had the magnificent thought, why don’t I put the setcookie (PHP function) in with the database calls in an include file? This will save me extra code and will keep the database information secure — if it works.

It worked!

In conclusion, if you need to set cookies after making a database call and would like to keep your database login information secure, use some sort of of function, either within a class or just a function that will make the call for you.

-Kerry

Curb a String – PHP Function

Tuesday, September 18th, 2007

I recently had several uses for this function, and there are probably many out. I am not proclaiming this unique nor the best available, but it works which is what counts. I actually took the majority of it from someone else, I think from php.net, but I tweaked it a little bit.

curb function

function curb($text, $maxlen = ”)
{
$MAXLENGTH = (empty($maxlen)) ? 100 : $maxlen; $split = explode(” “, $text);
$numwords = count($split);
$i= 0; //while counter
$a = 1; //counts the text chunks$amount = ceil(strlen($text)/($MAXLENGTH – 5)); //get total word chunks
while($i < $numwords) {
$len = (strlen($newtext[$a]) + strlen($split[$i])); //get length of the active chunk
if($len > ($MAXLENGTH – 5)) { //do we have to start a new one?
$a++;
$newtext[$a] = “[$a/$amount] “; //Adds [1/2]
} else {
$newtext[$a] = $newtext[$a] . ” ” . $split[$i];
$i++;
}
}
return $newtext[1] . “…”; // Don’t want the other variables
}

Pass in the string, and optionally, the length you want to curb it to. You can set a default in the highlighted section of the code (currently set at 100). Right now it returns it with a “…” at the end, which is what I wanted. Go ahead and remove the second highlighted section of the code if you don’t want this. (The highlights are very small – look hard! Squint if you must.)-Kerry

The Use Of Includes (PHP)

Monday, May 28th, 2007

It’s a very basic concept but often omitted, making life much more difficult than need be.

A basic principle that I follow is to never repeat identical code. If you have to repeat identical code somewhere, you should use an include, which will save you a lot of time and effort.

So, what is an include? It is a file that has a portion of text that you plan on using repeatedly throughout your site. For instance, the footer of your site that contains perhaps a few navigation links and your copyright is a great idea for an include. Lets say you have a very basic page, something like this:

index.php

<html>
<head>
<title>Include Example</title>
</head>
<body>
<img src=”example.jpg” />
My great website!
Copyright Joe Smith. All Rights Reservered
</body>
</html>

You can put that bottom copyright into a file, lets say footer.php (all my files are php, you can use any extension, .htm, .html, etc).

footer.php

Copyright Joe Smith. All Rights Reserved.

Now, to make this more interesting, lets say we added in some navigation at the bottom:

footer.php

HomeLinksAbout
Copyright Joe Smith. All Rights Reserved.

To include this file (remember that I’m using PHP, there are alternate methods in other scripting languages), your original page would now look like this:

index.php

<html>
<head>
<title>Include Example</title>
</head>
<body>
<img src=”example.jpg” />
My great website!
<?php include(“footer.php”); ?>
</body>
</html>

This puts all the code in footer.php right in that page. No visitor can see your php code – in this case it gets replaced by the code in the file, so it looks like a completely normal page. This enables you to put that little php include at the bottom of all your pages, and they all use the same page, so you never have to repeat that code. Now, if you change something in footer.php it will change that code on every page in your site. Most of my pages look something like this:

index.php

<?php include(“header.php”); ?>
<div id=”leftcolumn”>
<p class=”pagetitles”><b>Unsatisfied with your website?</b></p>
<p>Whether you finally decided to bring your business or career to the web, or you feel your website isn’t reaching
full potential, we can help.</p>
<p>We will build a website from ground up, walking you through every step on the way. If you want a site with
Flash Animation, E-Commerce, Support Forums, Wiki, User Login, etc., we will do it for you, completely customized
to your wish.</p>
<p>We will take care of any touch-ups or new features you need on your site – we constantly develop features for websites
or implement highly customizable ones to match your needs.</p>
<p>If you are a Web Designer but need the back-end taken care of, we will handle that. If you’re a developer and need the
design taken care of, or you need help with a specific section of your site, that will be arranged.</p><br /><br />
<br />
</div>
<? include(“footer.php”); ?>

header.php

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″ />
<title>Phoenix Development</title>
<meta name=”description” content=”Phoenix Development offers professional web design and development services for both personal and commercial websites.” />
<meta name=”keywords” content=”web design, web deveopment, phoenix development, php,” />
<link href=”/css/stylesheet.css” rel=”stylesheet” type=”text/css” media=”all” /><!–[imcss] *** Infinite Menus Core CSS: Keep this section in the document head for full validation. –>
</head><body><div id=”wrap”>
<div id=”page”>
<div id=”textarea”>

footer.php

</div><div id=”footer”>
| <a href=”/” title=”Phoenix Development Home”>Home</a> |
<a href=”/about.php” title=”About Us”>About Us </a> |
<a href=”/services.php” title=”Services”>Services</a> |
<a href=”/testimonials.php” title=”Testimonials”>Testimonials</a> |
<a href=”/referrals.php” title=”Referrals”>Referrals</a> |
<a href=”/faq.php” title=”Frequently Asked Questions”>F.A.Q.</a> |
<a href=”http://phoenixdev.wordpress.com/” target=”_blank” title=”Phoenix Development Blog”>Blog</a> |
<a href=”/contact.php” title=”Contact Us”>Contact Us</a> |
<br /><br />
<br />
© Copyright 2007 Phoenix Development. All Rights Reserved.
</div></div>
</div>
</body>
</html>

I removed a little bit of code from my website that has more advanced features. If you want to learn about those, let me know.-Kerry

PHP – cURL

Wednesday, May 9th, 2007

My post today is actually not a complaint nor instructive.

Yesterday I decided I was going to figure out how I could post through a proxy server. Right before I went to bed I found the functions cURL but didn’t have enough time to thoroughly explore it, which I did today.

cURL stands for Client URL and is a very powerful too. You can send all sorts of different requests to other servers and get all sorts of information.

In the tutorial I did today, he goes over how you can get definitions from dict.org (a dictionary site) or from amazon.com with requests based off input. Of course, you have to know what’s needed on the other end, but that information is out there. You can use it to FTP files back and forth. In my case I liked the posting ability. You can post data to another server.

I had been looking for this data for months, never really trying hard, just a couple searches here and there. This is it. Instead of giving you a bunch of code how you can do it, I’m just going to refer you to this tutorial: Using cURL with PHP. He briefly goes over all the things I was telling you about, but he does assume you have a little bit of prior PHP knowledge and experience.

Of course, like most great function sets (it’s not a specific function, its a set of different functions), it has its own home page.

I hope this discovery is exciting for you as it was for me.

-Kerry

PHP – Unsetting a Cookie Array

Sunday, April 29th, 2007

Hi everyone,

Most of what I’ve been doing recently I can’t blog about because it’s not complete, and who would want a half written blog?

What I am blogging today is a little loop that will unset a particular array in the Cookie array. If this sounds confusing, I’m not surprised. All the cookies are part of the Cookie Array. You can make subarrays within the Cookie arrays. For instance:

$nextWeek = time() + (7 * 24 * 60 * 60);
setcookie(“clothes[shirts]“, “blue”, $nextWeek, “/”);
setcookie(“clothes[shirts]“, “black”, $nextWeek, “/”);
setcookie(“clothes[shirts]“, “red”, $nextWeek, “/”);

And then, to make it a little more complicated, suppose we added another part to that array:

setcookie(“clothes[pants]“, “small”, $nextWeek, “/”);
setcookie(“clothes[pants]“, “medium”, $nextWeek, “/”);
setcookie(“clothes[pants]“, “large”, $nextWeek, “/”);

Now, lets say we wanted to just unset the “pants” subarray. Here’s a loop that could do it:

$subarray = “pants”;
if(isset($_COOKIE['clothes']) and is_array($_COOKIE['clothes']))
{
foreach($_COOKIE["items"][$subarray] as $key => $value)
{
$result[$key] = setcookie(“items[" . trim($subarray) . "][" . trim($key) . "]“, “”, time() – 3600, “/”);
}
}

I may add on to this post later and post an unset function.

-Kerry

PHP MCrypt (Encryption)

Tuesday, April 24th, 2007

Wow! Haven’t posted in a while. I should start more frequently, I’ve had some very busy days.

As I touched on in a previous post, I was working an encryption. I had found that GnuPG (a free version of PGP – Pretty Good Privacy) could be used in PHP and was trying to get that working. I looked into it and it seemed pretty complicated and I didn’t easily have access to install the necessary modules on on Linux Hosting. Therefore I decided to look for an alternate method.

I needed two-way encryption, meaning I could encrypt and decrypt it. The PHP function crypt() is one-way encryption, and wouldn’t work for my needs. MCrypt(), however, is a two way encryption function that supports many different methods. To see what methods are available on your server, put in the phpinfo() function in a page and you will find a section called “mcrypt”. Here it will tell you what methods are available for your use.

A page from hudzilla.org goes over the main different encryption methods and what should be used for your situation. I ended up choosing rijndael-256 (256 bit encryption, which is quite powerful). The example I give below will use this method.

I have made two functions, one to encrypt a string and one to decrypt a string. Here they are:

function encrypt($string, $extra = “”)
{
/* Open the cipher */
$td = mcrypt_module_open(‘rijndael-256′, ”, ‘ecb’, ”);

/* Create the IV and determine the keysize length, used MCRYPT_RAND
* on Windows instead */
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_DEV_RANDOM);
$ks = mcrypt_enc_get_key_size($td);

/* Create key */
$key = substr(md5(“CoMpLiCatED K3y” . $extra), 0, $ks);

/* Intialize encryption */
mcrypt_generic_init($td, $key, $iv);

/* Encrypt data */
$encrypted = mcrypt_generic($td, trim($string));

/* Terminate encryption handler */
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return $encrypted;
}

Where “CoMpLiCatED K3y” is your key for encryption and decryption. The optional $extra argument is what you can append to your key. This can make something more secure and different encryption keys for different purposes. Here’s the decrypt function:

function decrypt($encrypted, $extra = “”)
{
/* Open the cipher */
$td = mcrypt_module_open(‘rijndael-256′, ”, ‘ecb’, ”);

/* Create the IV and determine the keysize length, used MCRYPT_RAND
* on Windows instead */
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_DEV_RANDOM);
$ks = mcrypt_enc_get_key_size($td);

/* Create key */
$key = substr(md5(“CoMpLiCatED K3y” . $extra), 0, $ks);

/* Initialize encryption module for decryption */
mcrypt_generic_init($td, $key, $iv);

/* Decrypt encrypted string */
$decrypted = mdecrypt_generic($td, $encrypted);

/* Terminate decryption handle and close module */
mcrypt_generic_deinit($td);
mcrypt_module_close($td);

return trim($decrypted);
}

The same data applies to the above function, and it returns the decrypted string.

Enjoy!
-Kerry

PHP Ternary Operator – A Rare Find

Monday, April 16th, 2007

Today I discovered the ternary operator, which I’ve seen once before, while studying C++.

The ternary operator is a one-line way to do an if else statement, and I found it very good for cutting down unnecessary code. For example, if you had the statement:

if($color == “blue”) {
$correct = true;
} else {
$correct = false;
}

You could make it something much simpler:

$color = ($color == “blue”) ? true : false;

The way the ternary operator works is: “condition ? (expression if true) : (expression if false);”. You can assign variables to it like I did, or simple print it out. I haven’t tested this yet, but I’m pretty sure you can put functions there (I don’t see why you couldn’t).

Anyway, not a big post, but I thought it would be a useful operator to know about.

-Kerry