Sep
13
2008
0

PHP: Autolink Text - Twitter @replies

Update: To prevent any confusion the code highlighter might cause in the post, I added a plain text version of this post here.
I noticed a lot of sites allow user submitted content but prevent autolinking of urls. Some of the most common instances of this are on Twitter sites (much like my own creation: SecretTweet.com). So I threw together a function to autolink urls:

 
<?
$text= 'Hey go to google.com moo http://google.com moo www.google.com moo http://wwww.google.com/404.php moo';
function linkify(&$text)
{
//CONVERT *://.* TO LINK (EG HTTP://KEVINSMITHDESIGNS.COM)
$text = ereg_replace("[a-zA-Z]+://([.]?[a-zA-Z0-9_/-])*", "\\0", $text);
//CONVERT *://*.* TO LINK (EG HTTP://WWW.KEVINSMITHDESIGNS.COM)
$text = ereg_replace("(^| )(www([.]?[a-zA-Z0-9_/-])*)", "\\1\\2", $text);
return $text;
}
echo linkify($text);
?>
 

Would return "Hey go to google.com moo http://google.com moo www.google.com moo http://wwww.google.com/404.php moo".

And since I made this primarily for Twitter, the following will linke @ replies automatically, too:

 
<?
$tweet = "Hey @mozunk! Go check out http://digsby.com -- I think you will like it.";
function twitterify(&$tweet) {
//CONVERT *://.* TO LINK (EG HTTP://KEVINSMITHDESIGNS.COM)
$tweet = ereg_replace("[a-zA-Z]+://([.]?[a-zA-Z0-9_/-])*", "\\0", $tweet);
//CONVERT *://*.* TO LINK (EG HTTP://WWW.KEVINSMITHDESIGNS.COM)
$tweet = ereg_replace("(^| )(www([.]?[a-zA-Z0-9_/-])*)", "\\1\\2", $tweet);
//LINK @USERNAME
$tweet = preg_replace('/([\.|\,|\:|¡|¿|\>|\{|\(]?)@{1}(\w*)([\.|\,|\:|\!|\?|\>|\}|\)]?)\s/i', "$1@$2$3 ", $tweet);return $tweet;
}
echo twitterify(&$tweet);
?>
 

Would return "Hey @mozunk! Go check out http://digsby.com -- I think you will like it."

I'll be implementing this into SecretTweet pretty soon. I haven't decided if I want to autolink URLs or not...maybe just @replies.
---
automatically link urls php
autolink @ replies Twitter automatically link php

Written by Kevin in: PHP
Jul
22
2008
1

Masking PHP via .htaccess

What we're doing: turning the .php extension into .whatever
Why we're doing this: security, seo, or because you want to (then you'll have to answer why for yourself)
How to do this:

In your .htaccess file, we're going to tell apache to parse your choice of a single or multiple .whatevers as php.
So if we wanted to parse .html files as php, we would do something like this:

AddType application/x-httpd-php .html

And if we wanted to parse .bunnyboyfoofoo files as .php:

AddType application/x-httpd-php .bunnyboyfoofoo

And if we wanted to parse .bunnyboyfoofoo, .html, .htm, .py, .kevinsmith, .google files through php:

AddType application/x-httpd-php .bunnyboyfoofoo .html .htm .py .kevinsmith .google

Simple and fun to play with if you're that type of person.

PS:  Sorry it has been so long since my last update...it's summer, I've been enjoying it.

Written by Kevin in: PHP, WebDev
Jun
03
2008
0

301 Permanent Redirect PHP and HTACCESS

Just to compare two of the different ways to effectively do a proper redirect...

PHP:
(old.php)

<?
header ('HTTP/1.1 301 Moved Permanently');
header('Location: http://kevinsmithdesigns.com/new.php');
exit;
?>

.HTACCESS

 
Redirect 301 /old.php http://www.kevinsmithdesigns.com/new.php
 

--------------
I much prefer .htaccess so you can delete old.php and keep track of all redirects via one file (.htaccess).
.htaccess is also probably the safest way to redirect (if you're the SEO conscious type)

Written by Kevin in: PHP, WebDev
May
28
2008
0

Only allow alpha/numeric characters

Strip all symbols and other non a-z, 1-0 characters from a string using the handy-dandy ereg_replace.

<?php
$before= "First !@#$%^&amp;*() Middle _+:?&gt;&lt;|}  Last";
$after= ereg_replace("[^A-Za-z0-9] ", "", $before);
echo $after
?>
 

And the output would be:
"First Middle Last"

---
This is very basic but I see a lot of people going about this the long way around with snippets that are 10-15 lines long (when they only need to be one)...

EDIT!:

Aken pointed out a mistake I made.

I had ereg_replace("[^A-Za-z0-9]", "", $before); when it should be ereg_replace("[^A-Za-z0-9] ", "", $before); (so that spaces are also not allowed). I have corrected the code above. I'm only human :/

Written by Kevin in: PHP
Apr
29
2008
0

Insert Ads Between MySQL Results

If you are pulling information from a mysql database and want to insert either ads (like adsense) or just repeat the headers after every X amount of results, here's my way of doing it:

<?
//connect to the mysql database\
//I always like to define the value of $i as 0 just to keep things straight in my mind.  You can set this to whatever number you want to start counting from
$i=0;
 
//The query -- this is an example from one of my sites.
$result55 = mysql_query("SELECT * FROM table WHERE safe='y' AND language='english' ORDER BY timedate DESC LIMIT 10");
 
//Do the basic while statement
while($row = mysql_fetch_array($result55))
{
//Set the count of $i to plus 1
$i++;
//echo your results
echo $row[id];
//create an if statement and print out an ad on whatever number you like.  Since I limited my query to ten results, I'm going to print an ad after the 5th result (in the middle, obviously).  Note that adsense will only allow you to print three ads on any given page.
if ($i == "5"){ ?>
INSERT ADSENSE CODE HERE
<?
}
?>
 

See a working demo of this at www.SecretTweet.com -- the ad script is repeated after every 3rd ad when the query limits the results to 10. This way I can achieve the maximum number of ads allowed by google while spreading out the ads evenly within the results.

Written by Kevin in: MySQL, PHP, WebDev
Apr
02
2008
0

My Latest Project: SecretTweet.com - Anonymous Twitter App

I started on this last night around 10pm and had the basic code finished around midnight. It's fairly simple (and yes, another Twitter application): a user goes to www.SecretTweet.com and types in a secret. Their secret "tweet" is then published to @secrettweet. It's kind of like postsectret but for Twitter. I might add some features to it in the future...it all depends on the popularity.

Written by Kevin in: PHP, Personal, Uncategorized
Mar
22
2008
0

Use Sticky Forms!

If a user inputs information that generates an error OR if he/she leaves a field blank, save them time (and increase your turnover) by using sticky forms. It's so simple and improves usability so much...

Let's say we're collecting first and last names (to keep it simple):

 
form.php
<?php
if (isset($_POST['submitted'])) {
 
		// Print the results.
		echo '
<h1>Your Name:</h1>
 
First: ' . $_POST['first'] . ' Last: ' . $_POST['last'] . '
 
';
 
	} else { // Invalid submitted values.
		echo '
<h1>Error!</h1>
 
Please enter a valid name.
 
';
	}
?>
<h2>Your Name</h2>
<form action="form.php" method="post">
 
First:
<input type="text" name="first" size="30" maxlength="40" value="<?php if (isset($_POST['first'])) echo $_POST['first']; ?>" />
 
Last:
<input type="text" name="last" size="30" maxlength="40" value="<?php if (isset($_POST['last'])) echo $_POST['last']; ?>" />
<input type="submit" name="submit" value="Submit!" />
<input type="hidden" name="submitted" value="TRUE" />
</form>
 

So, if a user inputs a first name but no last name (or last but no first), it will show whatever the user has already typed (and preventing them from having to type it again)...if the form is lengthy, this is very handy and such a time saver.

Written by Kevin in: PHP, WebDev
Mar
21
2008
0

Multidimensional Arrays

Multidimensional arrays are basically arrays within arrays. So, let's make one.

 
<?
//Our first array is going to be for dairy products:
$dairy = array(1 =&gt; 'Milk','Cheese','Yogurt');//Our second array is going to be for animals:
$animals = array(1 =&gt; 'Cow','Duck','Horse','Chicken');
 
//Now let's pretend we wanted to combine these arrays (I should've chosen something like Months and Years or States and Territories...but I'm sticking with dairy products and farm animals ;) ....)
$combined = array('Dairy' =&gt; $dairy, 'Animals' =&gt; $animals);
 
//Idea: This is the best way to categorize interests for personalized profiles etc....
//Echoing what we've just done...
echo "I want to echo Cow!  {$combined['animals']['Cow']}";
 
?>

Of course, if you're just wanting to echo Cow, just use echo "Cow";...but if you're building things from arrays like drop down menus or if you're collecting interests, this is helpful.

Written by Kevin in: PHP, WebDev
Mar
15
2008
0

Sharing the voolia.com core

I started a sideproject called Voolia a few weeks ago so I could send multiple urls through Twitter. After getting it to a stable state (meaning it functions perfectly for what I want to do lol), I just left it alone. I checked the stats on it today to find that it has been getting some attention from random websites...pretty neat.

You might be surprised at how simple the base of the site is. It's under 50 line (counting empty lines and comments!) ...check it out:

 
<?
//define vars
$links = $_POST["links"];
$email = $_POST["email"];
$dateadded = date('Y/n/j');
 
//build callsign
// Notice that I don't user lowercase l and the number 1....too easily mistaken for eachother.
function createsign() { $chars = "abcdefghijkmnopqrstuvwxyz023456789ABCDEFGHIJKMNOPQRSTUVWXYZ";
srand((double)microtime()*1000000); $i = 0; $pass = '' ;
while ($i <= 2) { $num = rand() % 33; $tmp = substr($chars, $num, 1);
$pass = $pass . $tmp; $i++; } return $pass;}
$callsign = createsign();
 
//Check if callsign already exists...
 $q2 = mysql_query("SELECT * FROM links WHERE callsign='$callsign'");
   $q3 = mysql_fetch_object($q2);
    if($q3->callsign == $callsign) {
$callsign = createsign(); //do it again
}
 
//insert vars
$insertlinksquery = "INSERT INTO links (links, dateadded, email, hits, ip, callsign) VALUES ('$links', '$dateadded', '$email', '0', '".$_SERVER['REMOTE_ADDR']."', '$callsign')";
$runinsertlinksquery = mysql_query($insertlinksquery) or die(mysql_error());
 
//now do a foreach and insert each url within the murl as $callsign+1;
//first, we pull up what we just insertted ...i need to make this more efficient!
$result = mysql_query("SELECT * FROM links WHERE callsign='$callsign1'");
$row = mysql_fetch_array($result);
$linksrow = $row['links'];
 
$i = 0;
$chunks = spliti ("
", $links, 100);
//print_r($chunks);
foreach ($chunks as $value) {
if($value == "") { $newstring = "http://voolia.com"; $cliprow = "http://voolia.com"; } //get rid of empty links from bookmarklet and replace with voolia.com for kicks and giggles
$i++;
$individualcallsign = "$callsign$i";
$insertindividual = "INSERT INTO links (links, dateadded, email, hits, ip, callsign) VALUES ('$value', '$dateadded', '$email', '0', '".$_SERVER['REMOTE_ADDR']."', '$individualcallsign')";
$runinsertindividual = mysql_query($insertindividual) or die(mysql_error());
}
?>
 

Isn't that amazingly simple?...I think so. With just a tiny bit of .htaccess manipulation, you can have your own url redirection service....I find these handy.

Written by Kevin in: MySQL, PHP, WebDev
Mar
09
2008
1

Handy PHP Shorts

I like simple things...things that require little effort on my behalf. Here are some php functions/"shorts" that will probably prove useful somewhere in your future.

Get META tag information from practically any website (works locally, too!)

$thetags = get_meta_tags ( 'PATH OR URL' );print_r ( $thetags);

Get a ton of information about a user's browser: (also check out phpsniff)

echo $_SERVER['HTTP_USER_AGENT'] . "\n\n";$browser = get_browser(null, true);
print_r($browser);

Show the source of a file:

show_source("http://voolia.com");show_source(__FILE__);  //shows source of current file

Highlight source and number lines (great when you're stuck without an editor...no other use, in my opinion):

 
<style type="text/css">.line { float: left; color: gray; text-align: right; margin-right: 6pt; padding-right: 6pt; border-right: 1px solid gray;} </style>
 
<?php
function highlight_num($file)
{  echo '&lt;code class="line"&gt;', implode(range(1, count(file($file))), '&lt;br /&gt;'), '&lt;/code&gt;'; highlight_file($file); }
highlight_num('highlightfile.php');
?>

Create a very hard to guess unique id (impossible?) - php5 only:

 
$better_token = md5(uniqid(rand(), true));

Delay script execution (great for download scripts or advertising):

 
sleep(60); //in seconds.  this script will sleep for 1 minute as is.

Also check out time_sleep_until.

Print files in a directory:

 
$direct = dir('sample_directory/'); // the directory here
if ($direct)
{
while (false !== ($list = $direct-&gt;read())) {
if (!in_array($list, array('.', '..')))
{ echo "<a href='http://sampledomain.com/sample_directory/$list%5C%22'>$list</a>"; }
}
}
Written by Kevin in: PHP, WebDev

Powered by WordPress | Aeros Theme | TheBuckmaker.com WordPress Themes