The Urbano A. Company’s Blog
PHP
Articles about php development
Parse links in user comments
Sep 13th
When you allow users to comment and post stuff to your website, it is interesting and useful allowing them to post links and other stuff. But how can we do so easily?
Surely there is BBCode, phpBB, allowing only some HTML tags... etc but how easy is this approach for the end user? Of course some users will be familiar with BB code, or with HTML; others will be curious enough to learn how to use it, but most won't. And we want our users to be able to do so.
The solution: URL Parsing
How about this: They simply post the URL of whatever they want to include (A link, a picture, a YouTube video... ) and we detect that, and take the corresponding action.
First of all we need something that detects links, I have written a simple regexp to do so:
function parse($text){ return preg_replace_callback('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.-]*(\?\S+)?)?)?)@', 'parseUrl', $text); }
This is valid for almost all URLs, as long as http is the beggining. This function calls a callback function whenever a URL is found, called parseURL, which will then take care of the URL.
parseURL
Now that the URL is found, we need to take care of it: The url is stored in a parameter returned from the function preg_replace_callback. It is contained in the first element of the returned array.
function parseURL($url){ $link = $url[0]; }
We will parse the full url with a built-in function called parse_url(), which will return the following data:
- scheme - e.g. http
- host
- port
- user
- pass
- path
- query - after the question mark ?
- fragment - after the hashmark #
To get the file format we will check the extension:
$ext = substr(strrchr($url['path']),'.'),1);
Image formats:
$imgs = array('jpg','jpeg','gif','png','tif'); // You can write more if you want, this is only an example
Now let's check if it is or not an image:
if(in_array($ext,$imgs)){ return '<img src="'.$link.'" alt="This is a picture" class="insertedPic" />'; }
This way if a user inserts a link to a picture, the picture is displayed. You can now add a link, or change in any way the result of this.
If it is a YouTube video it would also be good to embed it, so we will first check if it is:
if(eregi('^(www\.)*(youtube\.).{2,3}$',$url['host'])){ // Check for youtube video return youtubeEmbed($url['query']); }
As you can see, if the link comes from youtube, we will embed it using our custom function youtubeEmbed:
youtubeEmbed()
function youtubeEmbed($params){ parse_str($params); if(substr($v , strlen($v)-3 ,3) == '<br '){ $v = substr($v , 0 ,strlen($v)-3); } if($v){ return ' <div class="addedLink"/><object width="200px" height="150px" style="display:block; z-index:1"><param name="movie" value="http://www.youtube.com/v/'.$v.'"></param><param name="allowFullScreen" value="true"></param><param name="wmode" value="transparent"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/'.$v.'&rel=1&color1=0xFFFFFF&color2=0x666666&border=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="200" height="150" wmode="transparent"></embed></object><br '; }else{ return false; } } </pre/> I won't go into too much detail here, it is quite simple, we take the parameter $v, which is the video ID, and then we proceed to the video embed... You can do the same with Metacafe, Vimeo, College Humor, Google Video... etc and the process would be basically the same for all. <h2>Further uses</h2> I use this class to detect internal links in some of my websites. If the link points to a page with a picture for example, I show a small version of it, if it points to a user profile I show the user's name and some data... etc The options are endless, and once you have everything parsed it is very easy to add new stuff. It really makes it simple for users to share pictures and videos, and it is the safest way of doing so, as well as the best way if you ever want to change the behavior, since in the database all you store is the raw URL.
Calculate age in PHP from timestamp
Sep 8th
If you ever wanted to calculate someone's age in PHP from a birth timestamp, you must take into account that the age is more than the number of years, since days and months are also important, so I wrote a simple function that will return the exact age for a given timestamp:
function getAge($birth){ $t = time(); $age = ($birth < 0) ? ( $t + ($birth * -1) ) : $t - $birth; return floor($age/31536000); }
Basically we first get the current time and store it in a variable (To avoid having to call the function time more than once)
Then we get the age in milliseconds (Taking into account that before 1969 timestamps are negative, thus the ternary operator)
Now we have the date in milliseconds, we divide it by the number of milliseconds in a year (60*60*24*365)
And that is basically it
Easiest PHP file upload
Aug 7th
Hello people,
I want to share with all of you a file upload class I have developed, that makes it stupid simple to upload files haha
The PHP class:
First of all, here is the PHP class you will need:
< ?php //Uploader class, by Alex // This class is meant to handle all kinds of file uploads for DJs Music // Images, music... all here class Uploader{ var $maxSize; var $allowedExt; var $fileInfo = array(); function config($maxSize,$allowedExt){ $this->maxSize = $maxSize; $this->allowedExt = $allowedExt; } function generateRandStr($length){ $randstr = ""; for($i=0; $i< $length; $i++){ $randnum = mt_rand(0,61); if($randnum < 10){ $randstr .= chr($randnum+48); }else if($randnum < 36){ $randstr .= chr($randnum+55); }else{ $randstr .= chr($randnum+61); } } return $randstr; } function check($uploadName){ if(isset($_FILES[$uploadName])){ $this->fileInfo['ext'] = substr(strrchr($_FILES[$uploadName]["name"], '.'), 1); $this->fileInfo['name'] = basename($_FILES[$uploadName]["name"]); $this->fileInfo['size'] = $_FILES[$uploadName]["size"]; $this->fileInfo['temp'] = $_FILES[$uploadName]["tmp_name"]; if($this->fileInfo['size']< $this->maxSize){ if(strlen($this->allowedExt)>0){ $exts = explode(',',$this->allowedExt); if(in_array($this->fileInfo['ext'],$exts)){ return true; } echo 'Invalid file extension. Allowed extensions are '.$this->allowedExt; return false; //failed ext } echo 'Sorry but there is an error in our server. Please try again later.'; return false; //All ext allowed }else{ if($this->maxSize < 1000000){ $rsi = round($this->maxSize/1000,2).' Kb'; }else if($this->maxSize < 1000000000){ $rsi = round($this->maxSize/1000000,2).' Mb'; }else{ $rsi = round($this->maxSize/1000000000,2).' Gb'; } echo 'File is too big. Maximum allowed size is '.$rsi; return false; //failed size } } echo 'Oops! An unexpected error occurred, please try again later.'; return false; //Either form not submitted or file/s not found } function upload($name,$dir,$fname=false){ if(!is_dir($dir)){ echo 'Sorry but there is an error in our server. Please try again later.'; return false; //Directory doesn't exist! } if($this->check($name)){ //Process upload. All info stored in array fileinfo: //Dir OK, keep going: //Get a new filename: if(!$fname){ $this->fileInfo['fname'] = $this->generateRandStr(15).'.'.$this->fileInfo['ext']; }else{ $this->fileInfo['fname'] = $fname; } while(file_exists($dir.$this->fileInfo['fname'])){ $this->fileInfo['fname'] = $this->generateRandStr(15).'.'.$this->fileInfo['ext']; } //Unique name gotten // Move file: if(@move_uploaded_file($this->fileInfo['temp'], $dir.$this->fileInfo['fname'])){ //Done return true; }else{ echo 'The file could not be uploaded, although everything went ok... Please try again later.'; return false; //File not moved } }else{ return false; } } }; //Initialize the object: $up = new Uploader; ?>
Alright this is the code. You shouldn't have to modify it, simply include it where you process the upload and the class will initiate itself inside the variable $up
Usage:
For this example I will suppose you have a basic HTML form as follows:
<form action="process.php" method="post" enctype="multipart/form-data"> <input name="uploadPic" type="file" /> <input name="upload" type="submit" value="Upload" /> </form>
As you can see, the action is process.php, which is, in this example, where the picture upload will be processed.
In the file process.php we will first include the upload handler, then configure it, and finally try to upload the file into the directory pictures/. Please take into account that it must be writable (CHMOD 777)
process.php:
< ?php //include the class: include('handleUpload.php'); $up->config('2000000','jpg,gif,png'); if($up->upload('uploadPic','pictures/')){ echo 'File uploaded. File information: '; echo $up->fileInfo['ext'].''; echo $up->fileInfo['name'].''; echo $up->fileInfo['size']; } // If the file was not uploaded, the error will have been echoed automatically ?>
As you can see there is no }else{ because the handler echoes the errors by itself. You can change this behavior easily by setting up your own function as desired.
In this example we have configured it to allow a maximum of 2000000 bytes per upload, and only jpg, gif, and png pictures.
Now that the file is uploaded you have some information about it in the $up object. The format ($up->fileInfo['ext']), the name ($up->fileInfo['name']), and finally the size in bytes ($up->fileInfo['size']).
The handler also generates a random name, and ensures it is not already in the directory. The new name is stored in the fileInfo array as mentioned above.
I hope you found this useful
Display time since last visit in PHP
Jan 20th
Have you ever seen those social networking sites that display the time since your last visit? They do it in a very neat way actually, that is a lot more friendlier that simply "Last login date..."
Well, this little php snippet will allow you to display messages like "Last visit was 4 days ago" or "2 weeks ago" or whatever it was, up to a year.
To use simply include the function in your code and then you'll need two timestamps to compare. One is the one that should be in the database, and it should be the date of the last user activity on the site, or the last time user logged in. The other would be normally the current time ( time() )
function timeBetween($start,$end,$after=' ago',$color=1){ //both times must be in seconds $time = $end - $start; if($time < = 60){ if($color==1){ return '<span style="color:#009900;">Online'; }else{ return 'Online'; } } if(60 < $time && $time <= 3600){ return round($time/60,0).' minutes'.$after; } if(3600 < $time && $time <= 86400){ return round($time/3600,0).' hours'.$after; } if(86400 < $time && $time <= 604800){ return round($time/86400,0).' days'.$after; } if(604800 < $time && $time <= 2592000){ return round($time/604800,0).' weeks'.$after; } if(2592000 < $time && $time <= 29030400){ return round($time/2592000,0).' months'.$after; } if($time > 29030400){ return 'More than a year'.$after; } }
And here an example of usage:
echo timeBetween($timeFromDatabase,time());
And an example output for that could be: 4 minutes ago
There are two configuration variables, $after and $color. $color sets online to a nice green color, and $after is what is displayed after the time. Default is " ago". But you can set it to anything you want.
Well I hope you find this useful
Display previous/next posts in single, category… in WordPress
Sep 14th
This is a really good option in WordPress, yet very few know how to do it. Well the code is relatively simple, and it gives a good navigation point for users that, if they liked your article, might want to keep reading your stuff.
If you want to plainly display the next post after the one the user is reading, use the following function:
< ?php next_post_link(); ?>
Now this function has several (very useful) parameters, which are:
< ?php next_post_link('format', 'link', in_same_cat, 'excluded_categories'); ?>
Format: For example bold ('%link'), italics ('%link')... And so on, you can add here divs, p, span or anything you want to apply css classes or ids.
Link: To display a custom text instead of the post title, for example if you want "Next post" use:
< ?php next_post_link('%link', 'Next post in category', TRUE); ?>
in_same_cat: A very handy parameter if you want to display only the next post of the same category. Set to TRUE if you want it that way, or FALSE if you simply want the next post.
You can use one more parameter to exclude categories, for example:
< ?php next_post_link('%link', 'Next post in category', TRUE, '13'); ?>
And now the next post will be from the same category, unless that category is 13 (The id, check in the administration panel)
If you want to exclude multiple categories you'll have to use the "and" separator. It will work like this:
'1 and 5 and 15'
Note: If you are using WordPress 2.2, the concatenation method was a comma (','). So you would use:
'1,5,15'
Of course to display previous posts substitute next by previous, with everything else being the same.
Enjoy,
... Please try again later.'