Category Archives: PHP

Articles about php development

Easiest PHP file upload

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:

  2. < ?php
  3. //Uploader class, by Alex
  4. // This class is meant to handle all kinds of file uploads for DJs Music
  5. // Images, music... all here
  7. class Uploader{
  8. var $maxSize;
  9. var $allowedExt;
  10. var $fileInfo = array();
  12. function config($maxSize,$allowedExt){
  13. $this->maxSize = $maxSize;
  14. $this->allowedExt = $allowedExt;
  15. }
  17. function generateRandStr($length){
  18. $randstr = "";
  19. for($i=0; $i< $length; $i++){
  20. $randnum = mt_rand(0,61);
  21. if($randnum < 10){
  22. $randstr .= chr($randnum+48);
  23. }else if($randnum < 36){
  24. $randstr .= chr($randnum+55);
  25. }else{
  26. $randstr .= chr($randnum+61);
  27. }
  28. }
  29. return $randstr;
  30. }
  32. function check($uploadName){
  33. if(isset($_FILES[$uploadName])){
  34. $this->fileInfo['ext'] = substr(strrchr($_FILES[$uploadName]["name"], '.'), 1);
  35. $this->fileInfo['name'] = basename($_FILES[$uploadName]["name"]);
  36. $this->fileInfo['size'] = $_FILES[$uploadName]["size"];
  37. $this->fileInfo['temp'] = $_FILES[$uploadName]["tmp_name"];
  38. if($this->fileInfo['size']< $this->maxSize){
  39. if(strlen($this->allowedExt)>0){
  40. $exts = explode(',',$this->allowedExt);
  41. if(in_array($this->fileInfo['ext'],$exts)){
  42. return true;
  43. }
  44. echo 'Invalid file extension. Allowed extensions are '.$this->allowedExt;
  45. return false; //failed ext
  46. }
  47. echo 'Sorry but there is an error in our server. Please try again later.';
  48. return false; //All ext allowed
  49. }else{
  50. if($this->maxSize < 1000000){
  51. $rsi = round($this->maxSize/1000,2).' Kb';
  52. }else if($this->maxSize < 1000000000){
  53. $rsi = round($this->maxSize/1000000,2).' Mb';
  54. }else{
  55. $rsi = round($this->maxSize/1000000000,2).' Gb';
  56. }
  57. echo 'File is too big. Maximum allowed size is '.$rsi;
  58. return false; //failed size
  59. }
  60. }
  61. echo 'Oops! An unexpected error occurred, please try again later.';
  62. return false; //Either form not submitted or file/s not found
  63. }
  65. function upload($name,$dir,$fname=false){
  66. if(!is_dir($dir)){
  67. echo 'Sorry but there is an error in our server. Please try again later.';
  68. return false; //Directory doesn't exist!
  69. }
  70. if($this->check($name)){
  71. //Process upload. All info stored in array fileinfo:
  72. //Dir OK, keep going:
  73. //Get a new filename:
  74. if(!$fname){
  75. $this->fileInfo['fname'] = $this->generateRandStr(15).'.'.$this->fileInfo['ext'];
  76. }else{
  77. $this->fileInfo['fname'] = $fname;
  78. }
  79. while(file_exists($dir.$this->fileInfo['fname'])){
  80. $this->fileInfo['fname'] = $this->generateRandStr(15).'.'.$this->fileInfo['ext'];
  81. }
  82. //Unique name gotten
  83. // Move file:
  84. if(@move_uploaded_file($this->fileInfo['temp'], $dir.$this->fileInfo['fname'])){
  85. //Done
  86. return true;
  87. }else{
  88. echo 'The file could not be uploaded, although everything went ok :S ... Please try again later.';
  89. return false; //File not moved
  90. }
  91. }else{
  92. return false;
  93. }
  94. }
  96. };
  97. //Initialize the object:
  98. $up = new Uploader;
  99. ?>

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


For this example I will suppose you have a basic HTML form as follows:

  2. <form action="process.php" method="post" enctype="multipart/form-data">
  3. <input name="uploadPic" type="file" />
  4. <input name="upload" type="submit" value="Upload" />
  5. </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)


  2. < ?php
  3. //include the class:
  4. include('handleUpload.php');
  5. $up->config('2000000','jpg,gif,png');
  6. if($up->upload('uploadPic','pictures/')){
  7. echo 'File uploaded. File information: <br />';
  8. echo $up->fileInfo['ext'].'<br />';
  9. echo $up->fileInfo['name'].'<br />';
  10. echo $up->fileInfo['size'];
  11. }
  12. // If the file was not uploaded, the error will have been echoed automatically
  13. ?>

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

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() )

  2. function timeBetween($start,$end,$after=' ago',$color=1){
  3. //both times must be in seconds
  4. $time = $end - $start;
  5. if($time < = 60){
  6. if($color==1){
  7. return '<span style="color:#009900;">Online';
  8. }else{
  9. return 'Online';
  10. }
  11. }
  12. if(60 < $time && $time <= 3600){
  13. return round($time/60,0).' minutes'.$after;
  14. }
  15. if(3600 < $time && $time <= 86400){
  16. return round($time/3600,0).' hours'.$after;
  17. }
  18. if(86400 < $time && $time <= 604800){
  19. return round($time/86400,0).' days'.$after;
  20. }
  21. if(604800 < $time && $time <= 2592000){
  22. return round($time/604800,0).' weeks'.$after;
  23. }
  24. if(2592000 < $time && $time <= 29030400){
  25. return round($time/2592000,0).' months'.$after;
  26. }
  27. if($time > 29030400){
  28. return 'More than a year'.$after;
  29. }
  30. }

And here an example of usage:

  2. 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

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:

  2. < ?php next_post_link(); ?>

Now this function has several (very useful) parameters, which are:

  2. < ?php next_post_link('format', 'link', in_same_cat,
  3. '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:

  2. < ?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:

  2. < ?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:

Of course to display previous posts substitute next by previous, with everything else being the same.


Easily assign an image to a post in WordPress

Have you ever wondered how to assign an image to a certain post using WordPress? Surely there are some plugins that try to do this, and maybe they accomplish it, but probably slowing down your blog.

Well, here is a way of doing it without slowing the blog or installing any sort of additional plugins. When you are done writing your post, upload an image to a directory that you will use for this, for example: "". And I recommned that you name the image something that has to do with the post, it will help you if you need to edit it.

Now in the writing are scroll down until you see the tab "Custom fields":

Assigning images to posts

And fill in the following information:

Key: post_image
Value: image_name.jpg

The key must be always the same, in this example it will be post_image. And the value will be the name of the image that we uploaded. In the example it is assigning_images.jpg

And that's it for now. The next step is including this images into our template.

Add the image to the template:

As you can see under the tab Custom Fields there is a link to the WordPress codex, where they explain the functions we'll use for this, so consult that if you have any doubts.

So here is the code to display the image (It must be inserted inside the Loop):

  2. if(get_post_meta($post->ID, 'post_image',true)){
  3. //There is an image assigned:
  4. echo '<img src="'.get_post_meta($post-/>ID, 'post_image',true).'" />';
  5. }

Note that if you copy and paste the code before you'll have to delete a / in $post->ID because WordPress is adding it automatically.
Of course this is the most basic approach, but hopefully you will understand the method and will be able to work on it.
At the moment I am using it to display thumbnails on the archive excerpts (They are not live yet, I'm still testing) and it is a very easy and fast way of doing it.

If you ever need to edit either the image or the meta-data simply re-upload the picture or edit the post.


Best unobtrusive anti-spam technique (Not CAPTCHA)

I know you are probably thinking that this will be some silly thing, but this idea that Thomas Landauer came up with is by far the best I've seen in a long time.

How does it work?

Well the idea is relatively simple: Add CSS-hidden fields that a user won't see, but a spam-bot will fill. Then using php check if they were filled, and if they were: block the spammer!

The CSS would be something as simple as:

  2. .noshow { display:none; }

The HTML form should include something like this:

  2. <label for="leaveblank">Leave this blank</label>
  3. <input type="text" class="noshow" id="leaveblank" name="leaveblank" /><br />
  4. <label for="dontchange">Do not change this</label>
  5. <input type="text" value="http://" class="noshow" id="dontchange" name="dontchange" />

And finally the php would be simply:

  2. if ($_POST['leaveblank'] == '' && $_POST['dontchange'] == 'http://') {
  3. // accept form submission
  4. }

The only possible drawback would be that some users with CSS disabled would see the "hidden" form fields, and thus would be quite puzzled.
The good thing is that the percentage of users with CSS disabled is so low that I wouldn't even care about that issue...

I like this idea so much that I'm writing a WP plugin to do this for sure. Just wait for a week or so and I will have version one running :)

Hope to see you when that happens!

PS: If you want me to notify you, comment saying so below, and I'll send you an email when I'm done.