Posts Tagged sourcecode

Generate a random password in PHP

Here’s a code snippet that will quickly generate a random password, using PHP. You can specify the characters set and the number of characters.

function generatePassword($length = 6, $chars = '23456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKMNPQRSTUVWXYZ')
{
  $password = '';
  $char_length = strlen($chars);
  for ($i = 0; $i < $length; $i++)
  {
    $num = rand() % $char_length;
    $password .= $chars[$num];
  }
  return $password;
}

Comments are welcome, as always. Have a faster way or a leaner function? Feel free to share!

,

Leave a comment

How to get your Facebook follower count in PHP

If you’re looking for a way to fetch and display your Facebook follower count in PHP, here is your code. In the below, substitute __ID__ for your numeric ID for your app or page, and __TOKEN__ for your access token.

Please consult the Facebook Graph API documentation for more information.

This method uses file_get_contents() rather than the preferrable cURL() call. Also, don’t forget to cache your queries, or you may experience API throttling. See the Rest & Graph API Best Practices for reference on this.

Here is the code:

function GetFacebookFollowerCount(){
  $json = file_get_contents('https://graph.facebook.com/__ID__/insights/page_fans/lifetime?access_token=__TOKEN__');
  $obj = json_decode($json);
  $new_facebook_followers= $obj->data[0]->values[0]->value;
  return $new_facebook_followers;
}

Comments and feedback are welcome.

, ,

Leave a comment

WordPress, suPHP, and Ubuntu Server 10.04

If you have WordPress running under an unprivileged user account, you may have noticed that when trying to install or delete a plugin that it prompts you for FTP information. This is due to a rather unintuitive way that WordPress checks for file access:

The following code is from the get_filesystem_method() method in the wp-admin/includes/file.php file:

if( function_exists('getmyuid') && function_exists('fileowner') ){
    $temp_file = wp_tempnam();
    if ( getmyuid() == fileowner($temp_file) )
        $method = 'direct';
    unlink($temp_file);
}

This code creates a temporary file and confirms that the file just created is owned by the same user that owns the script currently being run. In the case of installing plugins, the script being run is wp-admin/plugin-install.php.

This may seem a little counter-intuitive, since the only thing WordPress really needs to be able to do is write to the wp-content/plugins directory.

If you’re on your own server (i.e. your own box or a VPS) and not worried about security implications, you can simply make the files owned by your web server process (usually www-data or nobody). This will have WordPress’ check succeed and no longer ask for your information.

If you’re on your own server and running a shared hosting environment, or just care about the security implications, you should install suPHP.

What are the security implications? If all web files are owned by the web server process, it’s extremely easy for someone to introduce malicious php code which can affect other sites on the server. Since the web server process has access to all of the web server files across the server, malicious code would have no problem gaining access to other files and directories on the server.

suPHP, configured correctly, causes all php scripts under a defined directory (usually /home) to run as the user account they are owned by. It also enforces other security measures, such as requiring that directories and files do not have write permissions for anyone other than the user.

I could go on and on about what it does, but my biggest struggle has been getting it to work. Installation is easy, but it’s painfully clear it does not work out of the box. After dozens of searches I found varying different ways of making it work, but sometimes drastic and not clean nor easy, few didn’t require recompiling something (which I wasn’t going to do), and none of them seemed to work.

After more than a day of searching and testing, I finally came up with a simple, elegant, working solution. Note that this was written and based on Ubuntu Server 10.04 64-bit, and libapache2-mod-suphp 0.7.1-1 and may or may not work for other platforms.

Install suPHP:

apt-get install suphp-common libapache2-mod-suphp

Edit the sites-enabled/xxxx.conf file for your VirtualHost

Inside your directive, add:

php_admin_flag engine off
AddHandler application/x-httpd-php .php .php3 .php4 .php5 .phtml
suPHP_AddHandler application/x-httpd-php
suPHP_Engine on

Lastly, edit /etc/suphp/suphp.conf and under ;Handler for php-scripts (at the bottom) change:

application/x-httpd-suphp="php:/usr/bin/php-cgi"

to

application/x-httpd-php="php:/usr/bin/php-cgi"

Restart apache and all should be well.

/etc/init.d/apache2 restart

Note: You might get an error message like the following:

Syntax error on line 7 of /etc/apache2/sites-enabled/example.com.conf:
Invalid command 'php_admin_flag', perhaps misspelled or defined by a module not included in the server configuration

In this case, check that you actually have the Apache PHP mod installed and enabled. In can get uninstalled or disabled on occasion when upgrading Apache. Here’s how to reinstall/reenable:

sudo apt-get install libapache2-mod-php5
sudo a2enmod php5

Checking that it’s working

Create a phpinfo.php file with the follow contents:

<?php phpinfo(); ?>

Call it via your browser and check the Server API line near the top: CGI / FastCGI means suphp is working. Anything else means it’s not.

Suphp is slow!

Yes, unfortunately suphp is slow. Suphp runs PHP scripts in CGI mode, which reportedly causes them to run slower. I would argue that the security advantages outweigh the need for fast scripts, but each situation is unique. You have to decide for yourself.

500 Internal Server Error

If you’re getting the 500 Internal Server Error, it means that suphp is probably working, but for some reason it won’t allow the script to run.

Check that you don’t have any PHP opcode caching (APC, etc) running. If you are running any type of PHP opcode cache suphp will never work. You must disable your opcode caching. If you’re using APC, you can disable it system-wide by simply editing /etc/php5/conf.d/apc.ini and commenting the line out with a semicolon as follows:

;extension=apc.so

Another element of importance is file permissions. SuPHP will fail (with a 500 Internal Server Error) any file that has permissions which are not allowed, as defined in /etc/suphp/suphp.conf. For example:

; Security options
allow_file_group_writeable=false
allow_file_others_writeable=false
allow_directory_group_writeable=false
allow_directory_others_writeable=false

Any file or directory with the attributes defined as allow=false will fail. Based on the configuration above, any file that is group- or world-writable will automatically fail. Same with directories. It’s best to leave these options alone (instead of changing them), and change the permissions on your scripts instead.

However, it is supposedly possible to disable it on a per-VirtualHost basis. I haven’t tested this.

Also check that your /var/log/suphp/suphp.log file isn’t over 2GB. If it is, rotate it or delete it.

If all else fails, check /var/log/suphp/suphp.log and /var/log/apache2/error.log for hints.

Many thanks to all of the blogs and articles that each held a piece of this puzzle. :)

, , , , , , , , ,

Leave a comment

How to migrate website files using SCP

If you’re a web developer looking for a quick way to move files from one *nix server to another, SCP is your answer.

SCP quickly moves files from one server to another using an SSH tunnel.

Simply log on to your existing host and use the following command as example syntax:

scp -r * [email protected]:/target/folder/to/webroot/html/

login: your SSH login at the new host
domain: the hostname of your new host
/target/folder/to/webroot/html: the path to where you want your files stored

You’ll be prompted for your password after you hit enter.
This should transfer all of the files directly to your new host, but will NOT transfer hidden (dot) files.

If you use a dot ( . ) instead of the star ( * ), it will transfer the current directory WITH hidden files:

scp -r . [email protected]:/target/folder/to/webroot/html/

Comments are welcome, as always.

, ,

Leave a comment

Restoring the Network-Manager applet in Ubuntu

So you’ve noticed the Network-Manager applet is missing from your notification area in Ubuntu and you can’t connect to your wifi or cellular network. Now what?

Here’s a few tips to get it back, based on Ubuntu 10.10:

1) Make sure Network-Manager applet is installed

Open Applications > Ubuntu Software Center
Type ‘network’ in the search box and hit enter.
Locate ‘Network Manager’ in the application list and make sure it has a green check mark next to it.

2) Make sure Network-Manager-Applet is set to run on start-up

Open System > Preferences > Startup Applications and make sure the box next to Network Manager is checked.

The next two tips are slightly modified tips provided from UbuntuGeek:

3) Make sure Network-Manager is managing your connections

Open the terminal and type:

gksu gedit /etc/NetworkManager/nm-system-settings.conf

change the “managed=false” to “managed=true” and then save it.

then in the terminal type:

killall nm-system-settings

and then reboot.

4) Re-add the notification area to your bar:

right click panel>add to panel>Notification Area

5) Two bugs reported to LaunchPad involve this. Bug #577678, and #589362. Regarding #577678, a user suggested this fix:

Open a terminal and type:

gksu gedit /etc/network/interfaces

then check that the file has only this 2 lines:

auto lo
iface lo inet loopback

Delete all the others then reboot.

6) You may also want to try restoring the panels to default.

,

Leave a comment

Twitter Follower Count in PHP using Twitter REST API

Here’s an easy way to display the number of Twitter followers you (or another user) have in PHP using the Twitter REST API.

This was based off NealGrosskopf.com but was revised to use the Twitter API and not require a logged-in session.

First, declare the necessary functions:

&lt;?php
function curl($url) {
  $ch = curl_init($url);
  curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch,CURLOPT_HEADER, 0);
  curl_setopt($ch,CURLOPT_USERAGENT,"__YOUR_DOMAIN__");
  curl_setopt($ch,CURLOPT_TIMEOUT,10);
  $data = curl_exec($ch);
  curl_close($ch);
  return $data;
}

function GetTwitterFollowerCount($username) {
  $twitter_followers = curl("http://api.twitter.com/1/statuses/user_timeline.xml?count=2&amp;amp;screen_name=".$username);
  $xml = new SimpleXmlElement($twitter_followers, LIBXML_NOCDATA);
  return $xml-&gt;status-&gt;user-&gt;followers_count;
}
?&gt;

Now, a simple function displays the count:

&lt;?php
echo GetTwitterFollowerCount("__USER_NAME__");
?&gt;

Replace __YOUR_DOMAIN__ with the domain of the page making the API call, and __USER_NAME__ with the name of the user you want the information on.

Works for me.

UPDATE: For some reason, count=1 broke, but it works with count=2. Either change to count=2 (to reduce the download size) or omit the count= parameter completely (but it can inflate the download size if you have a lot of followers.)

UPDATE 2: If you are using this to fire on every page load, make sure you don’t exceed the Twitter API Rate Limit. If you think you may, you might want to cache the results, else risk being blocked by the Twitter API.

, ,

Leave a comment

Restoring Ubuntu Gnome Panels

If you’ve mangled, deleted, or otherwise borked your Ubuntu Gnome panels, here’s a way to revert them back to the default appearance and positioning.

You’ll want to open the ‘run’ dialog via ALT-F2 and enter each of the commands one at a time, followed by enter.

gconftool --recursive-unset /apps/panel
rm -rf ~/.gconf/apps/panel
pkill gnome-panel
gksu reboot

That should do it. When the system comes back up, all should be back the way it was.

, ,

Leave a comment

Installing iTunes on Ubuntu Linux

If you have an iPod, and have installed Ubuntu Linux, you may have gotten used to manging your audio library with iTunes. When you go to reach for iTunes on Ubuntu, you may have a moment of panic when you realize there’s no Linux client. Don’t worry, there’s alternatives.

Linux-native applications

First, try a Linux-native application, such as Rhythmbox, banshee, or Amarok for music and tripod for photos. These apps all have some support for iPod devices, and can help you manage your already-existing music library. If you’re using iTunes for music downloads, you may find the music store section of Rhythmbox helpful.

iTunes in Wine via PlayOnLinux

Second, you can try installing iTunes 7 using PlayOnLinux. PlayOnLinux is an application that helps you install programs using wine and gives each program it’s own configuration environment. Programs are installed using configurations that usually give the best results, so there’s little if any manual configuration required after the fact.

Remember, wine is an interpretive layer between the Windows-native application and the Linux environment, and therefore there’s a good chance that iTunes will run slowly and some features may simply not work.

You can find PlayOnLinux in Software Center, Synaptic, or install it using the command line:

sudo apt-get install playonlinux

iTunes in Wine via manual install

Lastly, if none of the above options pan out for you, or you want to try the latest version, you can try installing iTunes manually using wine.

Start by making sure you have wine and ubuntu-restricted-extras installed. You can install these using Synaptic or the following command at the command line:

sudo apt-get install wine ubuntu-restricted-extras

With those installed, it’s time to get iTunes installed. WineHQ gives very mixed ratings for iTunes under wine, so your mileage may vary. In addition, you may find the WineHQ Forum on iTunes and wine helpful.

You can find older versions of iTunes at OldApps.com iTunes page.

Virtualization

Lastly, if you find you simply can’t live without iTunes in a Windows environment, you may try running a Windows virtual machine in a hypervisor like VMware (my personal favorite) or VirtualBox. I prefer VMware because it seems to have better hardware pass-through support than even the closed-source versions of VirtualBox

Have you been able to get iTunes running on Ubuntu? Have any experience or tips to share? Please do so in the comments below.

, , , , , ,

Leave a comment

Drupal and Yourls

Actually, this should work with any CMS supporting PHP code blocks: Drupal, Joomla, WordPress (with a  plug-in), phpBB, etc. Has been tested working with Drupal 6, Joomla 1.5.

You’ll want to replace YOUR-YOURLS-DOMAIN-HERE below with the actual YOURLS domain, and API-SIGNATURE-HERE with the API key found at your YOURLSDOMAIN/admin/tools.php.

<?php
if ( isset($_REQUEST['url']) ) {
$url = $_REQUEST['url'];
$keyword = isset( $_REQUEST['keyword'] ) ? $_REQUEST['keyword'] : '' ;
if ($keyword) { $keyword = '&amp;keyword='.$keyword; }
$return = file_get_contents('YOUR-YOURLS-DOMAIN-HERE/yourls-api.php?signature=API-SIGNATURE-HERE&amp;action=shorturl&amp;format=simple&amp;url='.urlencode($url).$keyword);
echo <<<RESULT
<h2>URL has been shortened</h2>
<p>Original URL: <code><a href="$url">$url</a></code></p>
<p>Short URL: <code><a href="$return">$return</a></code></p>
RESULT;
} else {
echo <<<HTML
<h2>Enter a new URL to shorten</h2>
<form method="post" action="">
<p><label>URL: <input type="text" name="url" value="http://" size="50" /></label></p>
<p><label>Optional custom keyword: <input type="text" name="keyword" size="5" /></label></p>
<p><input type="submit" value="Shorten" /></p>
</form>
HTML;
}
?>

The idea was based off this post, which I could never get to work for me. It always had a PHP error, and it depended on having Drupal and Yourls installed on the same site. The above code will work even if the installation is remote (on a different server). It only requires that you’re able to get an API key.

Feedback is welcome.

, , , , , ,

Leave a comment

Optimizing WordPress

So after my little fiasco with plug-ins and CPU throttling, I’ve been looking for ways to make WordPress at least a little lighter and faster. I’m not going to cover disabling plug-ins, I’m going to go over a few other ways, starting with …

Disabling revisions:

Every time a post is edited and/or published, a new revision is created. These stick around in the database (never deleted) and can not only grow the database, but can also lengthen query times for information. So, per MyDigitalLife and the WordPress codex, here’s the quick-and-dirty:

…simply add the following line of code to wp-config.php file located in the root or home directory of WordPress blog.

define('WP_POST_REVISIONS', false);

If you would rather limit the number of revisions to something small, say 2 for example, just use the number instead of FALSE:

define('WP_POST_REVISIONS', 2);

It should be added somewhere before the require_once(ABSPATH . 'wp-settings.php'); line. That’s it. Revisions will no longer be created. If you want to delete previously created revisions, read on…

Deleting revisions:

So now that you’ve disabled revisions, how do you delete all the old cruft laying around? MyDigitalLife has the answer on this one too.

…and then issue the following [SQL] command (it’s also recommended to backup the database before performing the deletion SQL statements):

DELETE FROM wp_posts WHERE post_type = "revision";

All revisions should now be deleted from the database.

Caching:

Caching is a hot button for sites that could potentially see high amounts of traffic (and since we would all like to be in that category…) The caching plug-in that I use and recommend is WP Super Cache. The UI is easy enough to work around, though it does require editing of the .htaccess file.

Database queries:

Shared hosting providers get real upset when applications and scripts perform excessive and unoptimized database queries. Heavy themes, excessive numbers of widgets, and badly-written plug-ins all contribute to this. Fortunately, a post on CravingTech points to an easy method to check the number of queries happening on a single page load.

You can insert this snippet of code on your Footer.php file (or anywhere) to make it display the number of queries:

&lt;?php echo $wpdb-&gt;num_queries; ?&gt; &lt;?php _e(‘queries’); ?&gt;

After looking at the number of queries occurring on a page load, try changing themes, disabling plug-ins, and/or reducing the number of widgets on a page to reduce the number of queries. SQL Monitor looks like a useful plug-in for further examining SQL queries, but I haven’t used it, so I can’t comment on it’s usefulness (or lack thereof).

Also…

I’ve stumbled on some additional information while researching, and apparently the “WordPress should correct invalidly nested XHTML automatically” setting (under Settings > Writing) can not only increase the load when a post is saved, but can also break some plug-ins. If you’re familiar enough with (X)HTML to handle correctly closing tags, you might actually be better turning this off.

You can also find other settings for wp-config.php on the WordPress Codex page.

, , , , ,

Leave a comment