Thursday, June 25, 2009

XML - Parse Indeed RSS Job Feed - PHP 5 required

It is easy to parse an XML feed with PHP 5 and simplexml_load_file(). Here is a form I created that will paste into any PHP 5 .php page. It grabs job results from Indeed.com and displays them on your site.

<?php
if (isset($_POST['query']))
{
$query = $_POST['query'];
$location = $_POST['location'];
$radius = $_POST['radius'];
$limit = $_POST['limit'];

$feedAddress = "http://api.indeed.com/ads/apisearch?publisher=2212206290584495&sort=date&highlight=1&q=".$query."&l=".$location."&limit=".$limit."&radius=".$radius."";

$indeedjobs = simplexml_load_file($feedAddress);

foreach ($indeedjobs->results->result as $jobs)
{
printf("JobName: %s\n", $jobs->jobtitle);
echo "<br>";
printf("URL: %s\n", $jobs->company);
echo "<br>";
printf("City: %s\n", $jobs->city);
echo "<br>";
printf("State: %s\n", $jobs->state);
echo "<br>";
printf("Country: %s\n", $jobs->country);
echo "<br>";
printf("Source: %s\n", $jobs->source);
echo "<br>";
printf("Date: %s\n", $jobs->date);
echo "<br>";
printf("Description: %s\n", $jobs->snippet);
echo "<br>";
printf("URL: %s\n", $jobs->url);
echo "<br>";
printf("OnMouseDown: %s\n", $jobs->onmousedown);
echo "<br>";
printf("JobKey: %s\n", $jobs->jobkey);
echo "<br>";
echo "<br>";
}
} else {
$query = '';
$location = '';
$radius = '10';
$limit = '50';
}
?>
<form action="index.php" method="POST">
Search Jobs:
<input type="text" name="query" value="<?php echo $query; ?>" size="20">
<input type="text" name="location" value="<?php echo $location; ?>" size="20">
<label>Distance:
<select name="radius" id="radius">
<option value="1">1 Mile</option>
<option value="3">3 Miles</option>
<option value="5">5 Miles</option>
<option value="10">10 Miles</option>
<option value="15" selected="selected">15 Miles</option>
<option value="20">20 Miles</option>
<option value="25">25 Miles</option>
<option value="35">35 Miles</option>
<option value="50">50 Miles</option>
<option value="100">100 Miles</option>
<option value="4000">USA</option>
<option value="15000">World</option>
</select>
# Results:
<select name="limit" id="limit">
<option value="10">10</option>
<option value="25">25</option>
<option value="50" selected="selected">50</option>
<option value="100">100</option>
</select>
</label>
<input type='submit' value='submit' />
</form>

Saturday, June 13, 2009

PHP - XML Multi-Page Hit Counter Development

I am developing a hit counter with PHP that tracks hits on a page by page basis with an XML file. This version is for PHP 5. So far, it only edits existing entries in the XML. If it is going to work on a database driven site, I need to write in some validation and more complex XML editing script. If you improve on it, please send me your updates :

hitcounter2.php :


<?php
#GET THE XML FILE
$xml = simplexml_load_file(SITEROOT.'hitcounter2.xml');

#LOOP TO FIND THE ID
foreach($xml->hitcounter->page as $page)
{
if ($page['id'] == $page_id)
{
echo $page['num_hits'];
//$num_hits = $page['num_hits'] + 1;
$page['num_hits'] = $num_hits;
break;
}
}

#UPDATE THE XML FILE
file_put_contents(SITEROOT.'hitcounter2.xml', $xml->asXml());
?>

hitcounter2.xml :

<?xml version="1.0" encoding="utf-8"?>
<hitcounter>
<page>
<id>1</id>
<num_hits>21</num_hits>
</page>
<page>
<id>2</id>
<num_hits>22</num_hits>
</page>
<page>
<id>3</id>
<num_hits>23</num_hits>
</page>
</hitcounter>

Place this on any PHP page in your site:

<?php
include (SITEROOT.'hitcounter2.php?page_id=3'); // change the page_id for each page
?>

My best method of submitting files from a html form with PHP

Uploading an image on a web server is a lot more complicated than it needs to be. If you have the means to edit your web server's config.ini file and change the upload_max_filesize variable from its default of 2MB, then you don't need me that much. However, if you are like most people and use a third party server for all of your uploads, I do have a work around for you.

First:
include the following in your html form:

<p>
<label for='cimage'><div style="width: 300px;">Image ( Must be a .jpg and < <?php echo ini_get('upload_max_filesize'); ?>b ): </div></label>
<input type='file' name='IMGlink' accept='jpg|jpeg' value='browse'>
</p>

Second:
on the page that receives your form submittal include the following:

<?php
if ((isset($_SERVER['CONTENT_LENGTH'])) && (isset($_FILES['IMGlink']["size"])))
{
if ((($_SERVER['CONTENT_LENGTH']) < 2000000) && (($_FILES['IMGlink']["size"]) < 2000000))
{
if ((($_SERVER['CONTENT_LENGTH']) > 2000) && (($_SERVER['CONTENT_LENGTH']) > 2000))
{

include 'imageupload.php';

} else { echo "You did not upload an image. Or the image you uploaded is too small. <input type='button' value='back' onclick='history.back()'>"; }
} else { echo "The .jpg file you selected is too large. It must be less than 2Mb. <input type='button' value='back' onclick='history.back()'>"; }
}
?>

Third:
create a file called 'imageupload.php'
this file will upload the submitted image to the web server
and create and upload a thumbnail of the images to the web server
and returns a string value of the filename in a variable called $url
include the following:

<?php
$idir = "uploads/images/large/"; // Path To Images Directory
$tdir = "uploads/images/small/"; // Path To Thumbnails Directory
$twidth = "200"; // Maximum Width For Thumbnail Images
$theight = "200"; // Maximum Height For Thumbnail Images

if (isset($_POST['subpage']) && $_POST['subpage'] == 'upload')
{ // Uploading/Resizing Script

$url = $_FILES['IMGlink']['name']; // Set $url To Equal The Filename For Later Use

if ($_FILES['IMGlink']['type'] == "image/jpg" || $_FILES['IMGlink']['type'] == "image/jpeg" || $_FILES['IMGlink']['type'] == "image/pjpeg") {
$file_ext = strrchr($_FILES['IMGlink']['name'], '.'); // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php
$copy = copy($_FILES['IMGlink']['tmp_name'], "$idir" . $_FILES['IMGlink']['name']); // Move Image From Temporary Location To Permanent Location

if ($copy) { // If The Script Was Able To Copy The Image To It's Permanent Location
print 'Image uploaded successfully.<br />'; // Was Able To Successfully Upload Image
$simg = imagecreatefromjpeg("$idir" . $url); // Make A New Temporary Image To Create The Thumbnail From
$currwidth = imagesx($simg); // Current Image Width
$currheight = imagesy($simg); // Current Image Height

if ($currheight > $currwidth) { // If Height Is Greater Than Width
$zoom = $twidth / $currheight; // Length Ratio For Width
$newheight = $theight; // Height Is Equal To Max Height
$newwidth = $currwidth * $zoom; // Creates The New Width
} else { // Otherwise, Assume Width Is Greater Than Height (Will Produce Same Result If Width Is Equal To Height)
$zoom = $twidth / $currwidth; // Length Ratio For Height
$newwidth = $twidth; // Width Is Equal To Max Width
$newheight = $currheight * $zoom; // Creates The New Height
}

$dimg = imagecreate($newwidth, $newheight); // Make New Image For Thumbnail
imagetruecolortopalette($simg, false, 256); // Create New Color Pallete
$palsize = ImageColorsTotal($simg);

for ($i = 0; $i < $palsize; $i++) { // Counting Colors In The Image
$colors = ImageColorsForIndex($simg, $i); // Number Of Colors Used
ImageColorAllocate($dimg, $colors['red'], $colors['green'], $colors['blue']); // Tell The Server What Colors This Image Will Use
}

imagecopyresized($dimg, $simg, 0, 0, 0, 0, $newwidth, $newheight, $currwidth, $currheight); // Copy Resized Image To The New Image (So We Can Save It)
imagejpeg($dimg, "$tdir" . $url); // Saving The Image
imagedestroy($simg); // Destroying The Temporary Image
imagedestroy($dimg); // Destroying The Other Temporary Image
print 'Image thumbnail created successfully.'; // Resize successful

} else {
print '<font color="#FF0000">ERROR: Unable to upload image.</font>'; // Error Message If Upload Failed
}

} else {
print '<font color="#FF0000">ERROR: Wrong filetype (has to be a .jpg or .jpeg. Yours is '; // Error Message If Filetype Is Wrong
print $file_ext; // Show The Invalid File's Extention
print '.</font>';

}
}


?>

Fourth:
now take the $url variable which contains the filename of the uploaded file
and put it in your form submittal to the database:
include the following:

<?php
if (isset($_post['TheNameOfSomeVariableFromYourForm']))
{
echo "<form action='TheNameOfThePageToReceiveTheSubmittal' action='post'>";
echo "<input type='hidden' name='Url' value='".$url."'>";
// include any other form fields you would like to submit
echo "<input type='submit' value='TheNameOfYourButton'>";
echo "</form>";
}
?>

Fifth:
on the page that will receive the form submittal, receive and upload the form fields from the form submittal to the database.
if you don't know how to do that, read some of my other blog posts.

Media Library Gallery - The best gallery for WordPress

Searching long and hard for a gallery that worked 100% of the time, with every WordPress install, required no additional maintenance, and just basically does not waste a bunch of your time, I found Media-Library-Gallery to be the best. It simply finds all your blog's posted images from all users and creates a simple, basic, gallery from them. You can easily include the gallery on any object (page or sidebar item) by placing "<div style='height: 900px;'>[media-library-gallery nb=12]</div>
" in the html for that object. The '12' represents the number of images per page of the gallery.

To install Media-Library-Gallery, go to your WordPress admin plugin page and search for Media Library Gallery.

Saturday, June 6, 2009

PHP - .NET Master Page simulator

ASP.NET has really got something with their Master pages. Oh they're just so great, and oh they're just so easy, and oh they're just so easy to use. Well, let me tell you something:
PHP has ways, lots of ways. One such way that totally kicks is kinda like a reverse 'include' file request. Instead of asking PHP to get the info from another page ( as you would do with 'include' ) , you are telling PHP to post all the markup from the current page to another PHP page. And, the best part is, it is really really simple.

Benefits:
1. cut down on the number of server page requests
2. have a single page that contains all your css and functions.
3. have 90%+ of your object position style on one page.
4. restoring your site's style from a backup is greatly simplified (one file backup )
5. adding additional content pages to the site is very easy.

mypage.php ( The content of your Master Page's Content Div area goes here )

<?php ob_start();?>
<em>Put all your content, markup, javascript, php, and etc here.</em>
<?php
$pagemaincontent = ob_get_contents();
ob_end_clean();
$pagetitle = "Page Specific Title Text";
include("masterpage.php");
?>

masterpage.php ( all your headers, footers, style, functions, etc. go here )


<html>
<head>
<title><?php echo $pagemaincontent; > </title>
</head> <body>
<div class='myclass' >
<?php echo $pagemaincontent; ?>

</div>
</body>

</html>



Friday, June 5, 2009

"error establishing a database connection" on Wordpress MU install

Every time I installed Wordpress MU on my server, I would receive an error: "error establishing a database connection".

SOLUTION: I could not find a solution online no matter how hard I tried. Eventually, I realized that I had an existing .htaccess file in my site's root directory. I deleted that file, deleted all the tables from my MySQL database, deleted the wp_config.php file from the WordPress directory, and then reinstalled WordPress.

Let me know if I saved you a world of frustration.