Updating To PHP 5.4 On Ubuntu Server 12.04 LTS

If you use php web applications then your know a lot are now demanding to be updated to php 5.4 or higher. To do this in Ubuntu 12.04LTS simply do the following…

If you haven’t already used ppa then you will have to first install python software properties, make sure you’re the root user… ( sudo bash )

apt-get install python-software-properties

PHP 5.4.x run:

add-apt-repository ppa:ondrej/php5-oldstable

PHP 5.5.x run:

add-apt-repository ppa:ondrej/php5

Once you’ve added the repo simply update and upgrade current packages & distribution packages with one simple command :)

apt-get update && apt-get upgrade -y && apt-get dist-upgrade -y

Google Maps Error 610 Bad Key, Responsive HTML5 Google Map API V3

 

Getting a 610 error response from Google lately? Perhaps you have a bad API key? Not really it actually might be because Google deprecated support for their API V2…

 

Want to learn how to make a responsive google map for your site using PHP & HTML5 on API 3? here is how…

 

Note: In API V3 you do not require or use an api key.

 

Objectives:
Create a quick solution to produce responsive HTML5 Google Maps on the fly.

  1. write HTML
  2. write CSS
  3. write php/curl function
  4. example of use
  5. sample

First we will begin with a quick HTML wrapper and to place our iframe in…

1
<div class="wrapper"></div>

 

Use CSS to control the iframe and wrapper, this will also keep iframe in widescreen/16:9

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
.wrapper

{
height: 0;
padding-bottom: 56.25%; /* 16: 9 */
position: relative;
width: 100%;
margin: 0;
overflow: hidden;
}
iframe

{
height: 100%;
left: 0;
position: absolute;
top: 0;
width: 100%;
border: 0;
overflow: hidden;
}

 

Now lets create the function that will generate a iframe tag on the fly by simply passing 1 value… an address

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# google map iframe generation
function gMap($a)
{
// setting up vars
$lat = '';
$lon = '';
$addr = $a;
$addr = urlencode($addr);
$u="http://maps.googleapis.com/maps/api/geocode/json?address=".$addr."&amp;sensor=false"; // URL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $u);
curl_setopt($ch, CURLOPT_HEADER,0);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]);
// Comment out the line below if you receive an error on certain hosts that have security restrictions
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$d = curl_exec($ch);
curl_close($ch);
$g = json_decode($d, true);
// Debugging Purposes... or if you wanna use additional data...
//echo '
<pre>';
//print_r($g);
//echo '
</pre>
';
// If the Json request was successful...
if ($g)
{
$lat = $g['
results'][0]['geometry']['location']['lat'];
$lon = $g['
results'][0]['geometry']['location']['lng'];
$m = '
<iframe src="https://maps.google.com/?q='.$addr.'&amp;ie=UTF8&amp;ll='.$lon.','.$lat.';t=m&amp;z=15&amp;iwloc=&amp;output=embed" width="320" height="240"></iframe>';
echo $m;
} else {
echo "

No Map Available

";
}
}

 

Our php then goes inside the div

1
2
3
4
5
6
7
8
9
<div class="wrapper">

<?php
// you can insert a var instead of string if you wish ex: gMap($address)
gMap('48034 Rancho Way Temecula CA, 92592');

?>

</div>

 

An example of a running script

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<?php

# google map iframe generation
function gMap($a)
{
// setting up vars
$lat = '';
$lon = '';
$addr = $a;
$addr = urlencode($addr);
$u="http://maps.googleapis.com/maps/api/geocode/json?address=".$addr."&amp;sensor=false"; // URL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $u);
curl_setopt($ch, CURLOPT_HEADER,0);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]);
// Comment out the line below if you receive an error on certain hosts that have security restrictions
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$d = curl_exec($ch);
curl_close($ch);
$g = json_decode($d, true);

// Debugging Purposes... or if you wanna use additional data...
//echo '
<pre>';
//print_r($g);
//echo
;
// If the Json request was successful...

if ($g)
{
$lat = $g['
results'][0]['geometry']['location']['lat'];
$lon = $g['
results'][0]['geometry']['location']['lng'];
$m = '
<iframe src="https://maps.google.com/?q='.$addr.'&amp;ie=UTF8&amp;ll='.$lon.','.$lat.';t=m&amp;z=15&amp;iwloc=&amp;output=embed" width="320" height="240"></iframe>';
echo $m;
} else {
echo "

No Map Available

";
}
}

?>


<div class="page">
<div class="wrapper">
<?php
// you can insert a var instead of string if you wish ex: gMap($address)
gMap('48034 Rancho Way Temecula CA, 92592');
?>
</div>
</div>

Let me know if you have any questions. :)

PHP Startup: Unable to load dynamic library ‘/usr/lib/php5/20090626/mcrypt.so’ – libmcrypt.so.4: cannot open shared object file: No such file or directory in Unknown on line 0

Ok so I decided to quickly make this post because it was such a bitch to figure this out, all the information regarding missing dynamic libraries are in many cases unclear and could not find anything specific on the mcrypt library.

if you get the:
PHP Startup: Unable to load dynamic library ‘/usr/lib/php5/20090626/mcrypt.so’ – libmcrypt.so.4: cannot open shared object file: No such file or directory in Unknown on line 0

Here is whats going on…
you are missing files that are part of Apaches/PHP’s resources or you php.ini has the “entension_dir” value duplicated/actively pointing to the wrong location or php-cli is using the wrong php.ini config file. In my case it was due to a glitch with Ubuntu servers live OS update to 12.04.1 LTS which removed the old libraries and never re-installed them as part of the update.
Here is the checklist that will save you a long-ass headache, one that I unfortunately went through…

1) check your php.ini and make sure your “extension_dir” value (typically between line 805-809) is nulled out so its not processed (usually has a ; in front of it) in some cases the php.ini can be in multiple locations for apache/php-cli etc…
2) your mcrypt.so library is missing or corrupt.

first lets remove any possible installations of mcrypt libraries by running this in a shell, if you don’t have it installed skip this step (or you can still do it and if its not installed it will do nothing)…

1
2
sudo apt-get remove php5-mcrypt
sudo apt-get purge php5-mcrypt

then run this in a shell…

1
2
apt-get install php5-mcrypt
/etc/init.d/apache2 restart

(or you can sudo reboot too ;))

once this is done you should no longer get this error. If you have any issues please leave me a comment below :)

Using PHP To Pull Your Last Tweet Via Twitters Atom Timeline

Ok here is a simple script that will help you pull your latest feed from your twitter atom rss timeline without the use of cURL :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# Enter your twitter username
$username = "websymantecs";

#page title (if you want one &gt;:P)
$prefix = "&lt;h2&gt;Tweet Tweet&lt;/h2&gt;";

# Suffix - some text you want display after your latest tweet. (Same rules as the page title.)
$suffix = "";

# Our prepared URL
$feed = "http://search.twitter.com/search.atom?q=from:" . $username . "&amp;rpp=1";

# time to process our request
function parse_feed($feed) {
// time for our data parsing
$phase1 = explode("&lt;content type=\"html\"&gt;", $feed);
$phase2 = explode("&lt;/content&gt;", $phase1[1]);
$tweet = $phase2[0];
$tweet = str_replace("&amp;lt;", "&lt;", $tweet);
$tweet = str_replace("&amp;gt;", "&gt;", $tweet);
$tweet = str_replace("&amp;quot;", "", $tweet);
return $tweet;
}
# Parsed and echo to the screen.
$twitterFeed = file_get_contents($feed);
echo parse_feed($twitterFeed) . stripslashes($suffix);

Its that simple, enjoy! xD!

After a successful feed, you can use CSS to style the returned data.

Removing Login Fields From Justin Kliens WP-Facebook-Autoconnect

First of all I would like to say thanks to Justin for the plugin, it saved me some time :)
You can find his easy to use plugin at his personal blog site: http://www.justin-klein.com/projects/wp-fb-autoconnect/

This modification will work with Version 1.3.10

After about half an hour I was able to find the code that was causing a second duplicate login and password field. I am sure Justin was thinking ahead with the login fields but in some cases it actually interferes with the blog design/UI. The other problem was the welcome and edit profile links once logged in.

The block of code is found in 2 sections within Widget.php

The First NULLED section will remove the Welcome and Edit profile links once a user is logged in.
The Second NULLED section of code will remove the login fields.

Widget.php
Note: you can copy and past this entire code onto your Widget.php file to update it or download the file directly from the link at the bottom of this post.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
<?php

/**

  * Sidebar LoginLogout widget with Facebook Connect button

  **/


class Widget_LoginLogout extends WP_Widget

{

    //////////////////////////////////////////////////////

    //Init the Widget

    function Widget_LoginLogout()

    {

        $this->WP_Widget( false, "WP-FB AutoConnect", array( 'description' => 'A sidebar Login/Logout form with Facebook Connect button' ) );

    }

     

    //////////////////////////////////////////////////////

    //Output the widget's content.

    function widget( $args, $instance )

    {

        //Get args and output the title

        extract( $args );

        echo $before_widget;

        $title = apply_filters('widget_title', $instance['title']);

        if( $title ) echo $before_title . $title . $after_title;

       

        //If logged in, show "Welcome, User!"

        $userdata = wp_get_current_user();

        if( $userdata->ID ):

        ?>

<?php /*?>            
########################################################################
########################################################################
########################################################################
           
NULLED  TO PREVENT THE WELCOME MESSAGE ONCE THE USE IS LOGGED IN-->
           
            <div style='text-align:center'>

              <?php echo __('Welcome') . ', ' . $userdata->display_name?>!<br />

              <small>

                <a href="<?php echo get_settings('siteurl')?>/wp-admin/profile.php"><?php _e("Edit Profile")?></a> | <a href=" <?php echo wp_logout_url( $_SERVER['REQUEST_URI'] )?>"><?php _e("Logout")?></a>

              </small>

            </div>
           
## END OF NULL <--
 */
?>

        <?php

        //Otherwise, show the login form (with Facebook Connect button)

        else:

        ?>

<?php /*      

########################################################################
########################################################################
########################################################################
           
NULLED TO PREVENT THE WIDGETS LOGIN FIELDS-->
   
                <form name='loginform' id='loginform' action='<?php echo get_settings('siteurl')?>/wp-login.php' method='post'>

                <label>User:</label><br />

                <input type='text' name='log' id='user_login' class='input' tabindex='20' /><input type='submit' name='wp-submit' id='wp-submit' value='Login' tabindex='23' /><br />

                <label>Pass:</label><br />

                <input type='password' name='pwd' id='user_pass' class='input' tabindex='21' />

                <span id="forgotText"><a href="<?php echo get_settings('siteurl')?>/wp-login.php?action=lostpassword"><?php _e('Forgot')?>?</a></span><br />

                <?php //echo "<input name='rememberme' type='hidden' id='rememberme' value='forever' />";?>

                <?php echo wp_register('',''); ?>

                <input type='hidden' name='redirect_to' value='<?php echo htmlspecialchars($_SERVER['REQUEST_URI'])?>' />

            </form>
           
##END OF NULL <--
*/
?>
            <?php

            global $opt_jfb_hide_button;

            if( !get_option($opt_jfb_hide_button) )

            {

                jfb_output_facebook_btn();

                jfb_output_facebook_init();

                jfb_output_facebook_callback();

            }

        endif;

        echo $after_widget;

    }

   

   

    //////////////////////////////////////////////////////

    //Update the widget settings

    function update( $new_instance, $old_instance )

    {

        $instance = $old_instance;

        $instance['title'] = $new_instance['title'];

        return $instance;

    }



    ////////////////////////////////////////////////////

    //Display the widget settings on the widgets admin panel

    function form( $instance )

    {

        ?>

        <p>

            <label for="<?php echo $this->get_field_id('title'); ?>"><?php echo 'Title:'; ?></label>

            <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $instance['title']; ?>" />

        </p>

        <?php

    }

}





//Register the widget

add_action( 'widgets_init', 'register_jfbLogin' );

function register_jfbLogin() { register_widget( 'Widget_LoginLogout' ); }



?>

Once you have made the 2 listed changes your facebook button may be out of alignment from your theme, to simply fix this add some padding using css in the following file:

Main.php (lines 105-109)

1
2
3
<script type="text/javascript">// <![CDATA[
    document.write('<span id="fbLoginButton" style=""><fb:login-button v="2" size="large" onlogin="();">Login with Facebook</fb:login-button></span>');
// ]]></script>

If this too much code for you and you just want the login fields gone download the following files and replace the ones in your x:/wp-content/plugins/wp-fb-autoconnect folder.

Download Files

Automatic Image Randomization/Rotation Using PHP

Ok here you go, This script simply takes your images inside a chosen folder and then loads a random picture inside that folder.
If you have any questions just Holla at me!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
<?php

/* This Script is OPEN SOURCE Use it as you like nuggahs!

// ------------FUCK LAMERS WHO PRIVATIZE SOURCE CODE!----------------

#####################################################################
#####################################################################
########IMAGE RANDOMIZATION USING A FOLDER OF RANDOM IMAGES##########
#####################################################################
#####################################################################


INSTRUCTIONS
    1. Modify the $folder setting in the configuration section below.
    2. Add image types if needed (most users can ignore that part).
    3. Upload this file (rotate.php) to your webserver.  I recommend
       uploading it to the same folder as your images.
    4. Link to the file as you would any normal image file, like this:

            <img src="http://example.com/rotate.php">

    5. You can also specify the image to display like this:

            <img src="http://example.com/rotate.php?img=gorilla.jpg">
       
        This would specify that an image named "gorilla.jpg" located
        in the image-rotation folder should be displayed.
   
    That's it, you're done.

*/





/* ------------------------- CONFIGURATION -----------------------


    Set $folder to the full path to the location of your images.
    For example: $folder = '/user/me/example.com/images/';
    If the rotate.php file will be in the same folder as your
    images then you should leave it set to $folder = '.';

*/



    $folder = '.';


/* 

    Most users can safely ignore this part.  If you're a programmer,
    keep reading, if not, you're done.  Go get some coffee, smoke a cig or
    do your thang.

    If you'd like to enable additional image types other than
    gif, jpg, and png, add a duplicate line to the section below
    for the new image type.
   
    Add the new file-type, single-quoted, inside brackets.
   
    Add the mime-type to be sent to the browser, also single-quoted,
    after the equal sign.
   
    For example:
   
    PDF Files:

        $extList['pdf'] = 'application/pdf';
   
    CSS Files:

        $extList['css'] = 'text/css';

    You can even serve up random HTML files:

        $extList['html'] = 'text/html';
        $extList['htm'] = 'text/html';

    Just be sure your mime-type definition is correct!

*/


    $extList = array();
    $extList['gif'] = 'image/gif';
    $extList['jpg'] = 'image/jpeg';
    $extList['jpeg'] = 'image/jpeg';
    $extList['png'] = 'image/png';
   

// You don't need to edit anything after this point.


// --------------------- END CONFIGURATION -----------------------

$img = null;

if (substr($folder,-1) != '/') {
    $folder = $folder.'/';
}

if (isset($_GET['img'])) {
    $imageInfo = pathinfo($_GET['img']);
    if (
        isset( $extList[ strtolower( $imageInfo['extension'] ) ] ) &&
        file_exists( $folder.$imageInfo['basename'] )
    ) {
        $img = $folder.$imageInfo['basename'];
    }
} else {
    $fileList = array();
    $handle = opendir($folder);
    while ( false !== ( $file = readdir($handle) ) ) {
        $file_info = pathinfo($file);
        if (
            isset( $extList[ strtolower( $file_info['extension'] ) ] )
        ) {
            $fileList[] = $file;
        }
    }
    closedir($handle);

    if (count($fileList) > 0) {
        $imageNumber = time() % count($fileList);
        $img = $folder.$fileList[$imageNumber];
    }
}

if ($img!=null) {
    $imageInfo = pathinfo($img);
    $contentType = 'Content-type: '.$extList[ $imageInfo['extension'] ];
    header ($contentType);
    readfile($img);
} else {
    if ( function_exists('imagecreate') ) {
        header ("Content-type: image/png");
        $im = @imagecreate (100, 100)
            or die ("Cannot initialize new GD image stream");
        $background_color = imagecolorallocate ($im, 255, 255, 255);
        $text_color = imagecolorallocate ($im, 0,0,0);
        imagestring ($im, 2, 5, 5,  "IMAGE ERROR", $text_color);
        imagepng ($im);
        imagedestroy($im);
    }
}

?>

Using PHP to add security with IP filtration/blacklisting.

I remember having issues with an old company I use to work for, always checking my blogs and social profiles trying to get information about what I was currently doing kinda pathetic but true. This of course was due to there paranoia of me retaliating to their unlawful termination, but thats is entirely a new blog post. I thought I would create a security system to protect my personal information and make it a lot more difficult to coordinate the gathering of information.

Traditional methods would say create a login system and set user roles and view access controls but this alone would not be enough. I needed further security that would detect a connections address and then log it. I then would need to create a algorithm that would predict redirects anonymizers and proxies, and then cross refrencing access the logs.

This of course is a very complex way of filtering traffic from your site but one that works.

The following PHP script will detect the IP of a guest and return its value, compares the value’s and then either loads the page if the IP is not on the black list or silently forwards to the site of your choice.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// By Miguel Angel Vallejo www.miguelvallejo.com
// This script is Open Source so please use it if you wish. Enjoy! ^_^
// Si nececitas ayuda porfovor dejame un mensaje a mi coreo electronica miguel@miguelvallejo.com

//Lets declare the emtpy variable now.
var public $ip_address = '';

//Lets create a function called ip_filter() to process our check.
function ip_filter()
{
//This part of the code checks to see if the IP is a Fake
if (getenv(HTTP_X_FORWARDED_FOR)) {
$ip_address = getenv(HTTP_X_FORWARDED_FOR);
} else {
// At this point it has detected that the Ip is masked and it requesting the real IP and storing in inside the variable $ip_address.
$ip_address = getenv(REMOTE_ADDR);
// This is the variable that will store the banned IP address
var private $blacklist = '127.0.0.1';
// Now lets compare the values
if ($ip_address == $blacklist)
{
// if the ip is the same as the blacklisted ip forward the user to:http://www.google.com
header('Location:http://www.google.com');
} else {
return;
}
}
}

Now Lets try something a little more realistic, instead of a single value to compare lets create an array that houses our banned ips, then compare the ip with all values within the array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
//IP Detection Script -- &gt;
// By Miguel Angel Vallejo www.miguelvallejo.com
// This script is Open Source so please use it if you wish. Enjoy! ^_^
// Si nececitas ayuda porfovor dejame un mensaje a mi coreo electronica miguel@miguelvallejo.com

//Lets declare the emtpy variable now.
var public $ip_address = '';

//Lets create a function called ip_filter() to process our check.
function ip_filter()
{
//This part of the code checks to see if the IP is a Fake
if (getenv(HTTP_X_FORWARDED_FOR)) {
$ip_address = getenv(HTTP_X_FORWARDED_FOR);
} else {
// At this point it has detected that the Ip is masked and it requesting the real IP and storing in inside the variable $ip_address.
$ip_address = getenv(REMOTE_ADDR);
// This is an array that will store the banned IP addresses
var private $blacklist = array('127.0.0.1','127.0.0.2');
// Now lets compare the values, for each value in $blacklist[]
foreach ($blacklist as $value)
{
if($ip_address == $value)
{
header('Location:http://www.bing.com');

}else{
return;
}
}
}
// Initialize the function.
ip_filter();
// load the page default as the security check has cleared as guest not on the banned list.
include('default.php');

Ideally you would place and call the function at the beginning of each page/template which would prevent guests from trying to avoid the check.

If you wanted to take this script further you could tie it to your database where it connects and retrieves the blacklist making things much easier to update with a GUI in the future.
In the next tutorial we will cover taking the IP, time, amount of times and then writing those values into a table in your MySQL database.

If you have any questions please leave them.