Web Development

PHP MySQL Table Update Function

May 1, 2011 in Blog, Web Development by admin  |  No Comments

Typing out the full PHP/MySQL for each UPDATE query within a very dynamic PHP application quickly becomes a tedious task. Since starting out with PHP ten years ago I’ve written my own functions to make such tedious tasks easier, I keep them all in a functions.php file which I include in all my projects. It takes a while to create and remember the syntax for such functions, but once you do you will save a lot of time. The same concept as using a framework, but without the bulk.

Below is a function I wrote for running UPDATE queries which:

  • automatically escapes data
  • allows MySQL functions to pass through with the use of *function* e.g. *NOW()*
  • allows you to update columns with empty string/null values
  • allows a single or an unlimited number of columns to be updated
  • saves you from typing out long UPDATE queries
  • assumes that you have a column called id, presumably a primary key

Parameters are split with ::: and the first parameter is the table name, then the id of the row to update, then the column, and then the value. Add on as many columns and values as desired.

[code language="php"]ut("jobs:::1:::status:::walking the dog:::server:::fileserver2");[/code]

replaces

[code language="php"]$query="UPDATE jobs SET status=" . mysql_real_escape_string('walking the dog') .", server=" . mysql_real_escape_string('fileserver2') . " WHERE id=" . mysql_real_escape_string('1');
$result=mysql_query($query);[/code]

Below is the function and here is a more readable screenshot of the code.

[code language="php"]
function ut($data)//update table function
{
/*  Update mysql table, save time. MySQL real escape data. Pass unlimited number of columns/values. Allow MySQL function passthrough with *function*, e.g. *NOW()*
to update a column with a blank value simply skip the data. e.g. jobs:::123:::status:::  would set status to empty string for row 123
table:::row id:::column:::value:::column:::value:::column:::value

examples, don't forget that values have been through mysql_real_escaped_string(), so the equivalent query typed/sanitized manually would be much longer than shown below.
jobs:::1:::status:::walking the dog:::server:::fileserver2
UPDATE jobs SET status='walking the dog', server='fileserver2' WHERE id='1'

jobs:::1:::status::::::server:::fileserver3422
UPDATE jobs SET status='', server='fileserver342' WHERE id='1'

jobs:::1:::status:::starting the job:::addedtime:::*NOW()*
UPDATE jobs SET status='starting the job', addedtime=NOW() WHERE id='1'

Questions/improvements welcome at http://www.incero.com/?p=1301
*/
$data=explode(":::",$data);
$table=addslashes(strip_tags($data[0]));//we know the column ID will always be an int, wont need to escape this data
$id=intval($data[1]);//we know the column ID will always be an int, wont need to escape this data
connect();//our own mysql connect function, omit this if you always keep mysql open (for the whole page load)
$x=2;
while($x<sizeof($data))//Loop through the data array for all the update queries.
{
$column=strip_tags($data[$x]);
$value=$data[$x+1];
if($x==2){
$queryString= mysql_real_escape_string($column);
}
else//this isn't the first data/column set so we need a comma
{
$queryString.= ", " . mysql_real_escape_string($column);
}
if(substr($value,0,1)=="*" && substr($value,strlen($value)-1,1)=="*")
{
$queryString.= "=" . substr($value,1,strlen($value)-2);//if the value is surrouned by * then omit single quotes, allowing mysql functions to pass through, e.g. *NOW()*
}
else
{
$queryString.= "='" .mysql_real_escape_string($value) . "'";
}
$x=$x+2;
}
$sQuery = "UPDATE $table SET $queryString WHERE id='$id'";
//echo "<br>the query was $sQuery<br";
$sQueryresult = mysql_query($sQuery);
@mysql_close();//omit this if you always keep mysql open (for the whole page load)
return $sQueryresult;
}
[/code]

Click to view larger screenshot

Number Of Available CPU Cores In PHP

July 1, 2010 in Blog, Web Development by admin  |  3 Comments

It is simple enough to check and then load the number of available processing cores on the current machine into a PHP variable. You can do so with the code below, which uses shell commands to grab data from /proc/cpuinfo and then removes unneeded data with PHP.

[code language="PHP"]<?php
/*How to check how many processors are available on the current machine.
by gordon@incero.com http://www.Incero.com. Feel free to use this code,
but keep this header. June 30th, 2010.*/
$numberOfProcessors=`cat /proc/cpuinfo | grep processor | tail -1`;
$numberOfProcessors=preg_replace('/s+/', '',$numberOfProcessors);
$numberOfProcessors=str_replace(":","", $numberOfProcessors);
$numberOfProcessors=str_replace("processor","", $numberOfProcessors);
$numberOfProcessors++;
echo "Number of processors on this machine is $numberOfProcessors!";
?>[/code]

We use this code to help our programs assign the most efficient parameters to others processes, such as FFMpeg video conversions, that we spawn from PHP across various machines.

Tested on CentOS 5.4, should work on most Linux distributions.

Zend

June 14, 2010 in Blog, Web Development by admin  |  No Comments

If you see an error on your website like the one below, it means that you need to install Zend Encoder to load the file.

[code]Zend� 2003120701�1�2570�9363�xù Ÿ2 Í[ÍoÜÆŸÚêH9(§^R€ÑEdY$g8œ‰½N¶ÒZÚÖ’ìõ:Ž$‹µ´–ÖÖ~˜Ëu¬¢h.íÑ@/Fs)KÓc½ô”? 7|)£ƒÂ·…›ú†‡ä– ®ï®ùÞ<¾ù½ï!-’ÿ'½ážÕŠBXÑŸxk “YîqÌŠEmÀÞt08:ßÝÛ €ÙëÃî ÷öŠC!œs?nÆAo¿3膻sŽía‡Ù¶hW)šLoOÂ`ÎaÜõ=ß&Å6êÍ:sî9Ì‹|op4¹؉:dîrÆ=øp£Ó†ÓA'}1™s<×§ÇBÜ Æ#¸È‰O˜í2uñ’¸ØÎ2l3îøÖî´{8šDÛ Ì¥>¡4 „fìÄ�çÑ™80“¯·ærص›�梻gô  ¡NçróJ£Ó™´''JÀ±‘Ï9P)åTÄÔ5 $BõÕÝÑðNÿüø`ßýçÒ5ÓQ‹¦ªý»¨½c$aÁè›—Ñ£g/Ö£¿µwÝDûdýán²Œ~W¾ˆþl:ð$ÄÖGVrÛhû2[½syºÕ¸Üh5Z1ëµ|Cç¦b~H„ñÐ;2ƒÏçrôíÑèÞ Ü;Í}ß&€G›Â_|úèZÂâ^ú±²æh{aèŠn>Û»D´w•8‰Ø‰6Y<É:� ??ûÁûa8~uu郳Ÿ~¾úÙòÒ‡}ݸò›ù ‚’øüL¥3bþSÄg3YÓSG‚Œiì¹RyŸrꉓ'™`~-·›ØCͨqRz&Eèå8VD§ª¹WÛ… ?ÉÒ‰¾A¿›µd’êÒM¦ßÏHÔ¶ÈM¼Ça®mÑ�ƒ9c) N5 N% N’…®gƒ/¿Í¸*/´³^(ˆ?”ƃpéV™òñôv¿2Fÿ8•Y;¯Í =ÎãJ<ý=7Ür}jc­míÝþкÜÚÙ²ÚA†Ú››±äõÚâ|¦[½­Î t}ã£Aÿ&§¨Žt7*ِ&Ôã5Èôš ëW S/)t O5¡ša=•/¤€Œžž£L.Ïw5º=„Mg¬iÿm…í<ô¸¤J G¡0Æ$b£èëVUÑC÷Íe•Ä¥èòNëf½µÞX—Ü¿7•(Q:sÚs3js®‘¿Ìi–èóO¥›Ù¤ÎGͺdû±J‘¹jE¾>‘"}£"â®ÿf!™ Råjkçã[0§noCh6w¶ß,@J­Íj½1´ˆŽVýF{s§Õü¤þÿ�˜-KƒMüz xýY%5ªåxîê:ýñíªq½eîW½Xó°¤Sßhl·%û¸¼!êO²£ý®žÖå»BO ZB¦Ç¹»Ì8¶ÎßT–¤…¾¦¿´Ò;¶›«ô0ö«ÕPÿßvù§1U­OaÎk5¶vڍN}}½%YÓŠïçªÿS,Ö®MIï壝l±&,)ÖÑ¡sTª›ã­îX–êþøN0¬5·íN½½³}vQÞZÊsMU[„Ñâ’Uß^áè’¾®ËUû¬Pc+ º`z¥¹Õl[Žä¬h €ZÑ�õ¤M°–7@456ďj 0«j €úMp››u«|S0ã`OÓä¯J[?maà—’Ëêþ±PË읳ÆÁèáQ-ú–ÜOóÎA5QFG`ÏYáýŽä)xט½‹ Zº~£jý#ã^A‰Ãî$jk7Z-èÖ:íæVãz»¾u57¿›qÑà 4•%™:v2¹?Óœ®èþLf/çÅîÏÐ{¦2ái5špôÛÂ3ré4ëÝ£Èe‚þp^½Ä"V<*³pJ–8úz38~d„©ñ´JÄÓ2ÒõÇUëKì³,éy/ÒC¢ �?‰ˆWÇ€¢š.á H·p‰¼4D$–@ G‡Uš…c¥’í’ýò»ïf,;¦0åUÕªÜ ’ÅUUŠWV).«Ô ”›j½kSê«n³ µž æ6LUm«¹ÝÞ‰ ½ˆÕÒ2J ƒÚ¼fïz“š“ät¹¤Ü‡ŠÄt9—±pn”Ú�ˆæ`­ÎÉþSò‰iBÌáÄ„ƒÑ4¨™!ЫèÙ¬mkýÆÕ+Í5‘Õ¸eÉ ƒ}.;RÊ÷å.Ôçå.Ôg't`ý™ÚBî!ž¨úùÃí7s€t7ŸræðTλ›Ë3îÖêÝé½ .½;bFP ,6# :,jŽ–ñ§E¢Ù¼¸ègX“ñè5˜«˜7™«²n2/F7Oj^œ{¸0ãbŠ.Nvƒþ8´Äûrµ…°÷0½Û}Ѝ¯.@÷2ÜŸv÷ôK¸z=¾ziöA7°zÇý ×R¬š5ì}¥=ì]º0«QÎOzatY¿¶/¯-YË–C`ÁÞhw:è Ãó»£Ñ½¾·°vØß½7©Ùä}&µàÖ¥„£­öõºƒýHÒÂkÜ j« FÍõšf}ÀÎ|.â3ôÚn¹Ù?]”wû®Ô©[2ýb´øYMrV-7VFñªß«íäâjlýKRüżsª¨§ž6í°4ê=ìSÅch…œÝi€M7!̹¶oÁq‰xkavönÏ9̧˜ۍޚ‰ý9Sêx¾ Ñ%Eå‹}ΩxÔEýñ¬xÕÆaœÄOswÓC’9‡º>và/Úʳ”9fHŒ™|?'žª` 6å®Ëà )ø¶ž[/code]

If you are running cPanel/WHM on your server you can easily install Zend Encoder from the "Easy Apache" menu. Below are some screenshots detailing the process in WHM, simply use your existing Apache/PHP settings and then check the Zend Encoder checkbox on the options list near the end of the process.

Click here to view full size

Click here to view full size

Click here to view full size

Click here to view full size

Click here to view full size

PHP Upload Progress Bar Script

June 7, 2010 in Blog, Web Development by admin  |  Comments Off

We have developed an amazing PHP upload progress bar script, which uses Javascript and PHP to report back the upload status data to the user. This script makes it extremely easy to add an upload progress bar to your website without using Flash, Perl, cgi, or other complex solutions.

Demo

You can see the upload progress bar in action here. You can also see a video of it in action at the bottom of this page.

Features

  • Uses simple HTML form, allowing you to post additional data such as a description of the file, user-name, etc
  • 100% PHP and Javascript
  • Customizable progress update interval, have it update as often as you like, specify the interval in milliseconds
  • CSS based upload progress bar, change colors and size easily

Customizable & Well Documented

All of the code is easily customizable by any novice web programmer. All of the PHP code is very well commented in clear and easy to understand English. If there are any features that you want to add you can easily edit the source code to meet your needs.

Help Available, If You Need It!

We answer emails to info@incero.com within 1 business day, but usually within a couple of hours. We can also be reached on (512) 394.8803.  We can install the script for you, integrate it into your website, or perform nearly any other programming task for you for a reasonable fee. We are a real web development company located in downtown Austin, TX and are always happy to assist our clients!

Buy Now

We are a PayPal verified business, once you have completed the payment we will email you a copy of the script. Please feel free to contact us if you have any troubles, we are here to help!

Single Domain, $69 Personal Domains, $119 Developer, $249
Use the code on only one domain. Use the code on an unlimited number of domains that you personally own. May not be used by web developers or businesses. For developers and business users. Use the code on any number of your own and your client’s domains.

Sever Requirements

viagra

Securing Joomla Media Files With Login Sessions

May 11, 2010 in Blog, Web Development by admin  |  No Comments

We recently completed an excellent Joomla file protection script which allows Joomla CMS webmasters to secure their digital files based on the current user login session preventing leeching.

Using our Joomla file protection script you can simply drop our securefile.php in any folder that contains files that you want to protect and they will only be loadable by registered and logged in users.

Here’s how it works:

  1. All file requests for media files including videos and images are automatically passed to securefile.php
  2. securefile.php checks that the user is already logged by checking the Joomla session and cookie data
  3. displays the requested file, or shows an error message if permission is denied.

An example usage would be that you have a several .swf presentations that you want to show to your registered users only, they view your webpage source code and then steal the link to the .swf (such as http://www.mywebsite.com/files/presentation4.swf). The user then shares that direct link to your presentation with non registered users resulting in bandwidth usage and lost revenue. With the leech protection system those direct links will not work for non registered users.

This beauty of this system is that you can keep using your existing video players and presentations on your site as you always have without having to modify your code. We can set this up for you, contact us for more information.

How To Generate Thumbnails On The Fly With PHP

April 30, 2010 in Blog, Web Development by admin  |  1 Comments

There are two great ways to generate thumbnails for images on the fly with PHP:

  1. Use GD to resize the image on the fly and output it
  2. Extracts the thumbnail from the Exif data. (If this fails, you could revert to method 1 above.)

The latter assumes that the image file has exif data, which most photos do. To ensure the fastest loading thumbnails it would be best to generate thumbnails when images are uploaded to the server, but there are times when you don’t want to have to store thumbnails for every image uploaded.

Method 1: Using GD To Resize On The Fly

Using this 8.5MB image, and the code below, the following URL will load a thumbnail that is dynamically created: http://www.incero.com/codesamples/thumbnailonthefly/thumbnail.php?image=highres.jpg&width=160

[php]<?php
/*How to extract a thumbnail from Exif data using PHP
Created by Gordon Page, gordon@incero.com. April 30th, 2010.
Incero.com offers custom coding and hosting solutions.
*/
header(“Content-type: image/jpeg”);

// get image size
$file = $_GET[image];
if($size = GetImageSize($file)){
$w = $size[0];
$h = $size[1];
//set new size
$nw = $_GET['width'];
$nh = ($nw*$h)/$w;
}
else{
//set new size
$nw = “160″;
$nh = “120″;
}
//draw the image
$src_img = imagecreatefromjpeg($file);
$dst_img = imagecreatetruecolor($nw,$nh);
imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $nw, $nh, $w, $h);//resizing the image
imagejpeg($dst_img,”",100);
imagedestroy($src_img);
imagedestroy($dst_img);
?>[/php]

You’ll notice that with this method it takes about a second to generate the thumbnail so you may want to default to the method below which is faster, and if that method fails then fall back to this first method.

Method 2: Extracting The Thumbnail From The Exif Data

Using the same 8.5MB image, and the code below, the following URL will extract the thumbnail from the Exif data: http://www.incero.com/codesamples/thumbnailonthefly/exifthumb.php?image=highres.jpg

[php]

<?php
/*How to extract a thumbnail from Exif data using PHP
Created by Gordon Page, gordon@incero.com. April 30th, 2010.
Incero.com offers custom coding and hosting solutions.
*/
// file to read
$file =$_REQUEST['image'];
$image = exif_thumbnail($file, $width, $height, $type);
// width, height and type get filled with data
// after calling “exif_thumbnail”
if ($image) {
// send header and image data to the browser:
header(‘Content-type: ‘ .image_type_to_mime_type($type));
print $image;
}
else {
// there is no thumbnail available, handle the error.
//This would be a great place to revert to the GD resize method.
print ‘No thumbnail available’;
}
?>

[/php]

Feel free to use the code above in your own projects. If you are in need of paid programming services please contact us.

PHP file_exists() Performance

April 2, 2010 in Blog, Web Development by admin  |  2 Comments

For one of our projects we need a large amount of cheap storage, an NFS mounted NAS suits us. But we also want to load most recently used files from the server’s local disk, so that the notoriously slow NFS protocol doesn’t get the better of us during peak times. We’ll simply run a cron each hour to mirror our most recently used files to the local disk. Think of it as a very simplified reverse proxy cache.

Now, we could store the current location of the files in the database, e.g. file1 is on the nas, file2 is on the nas and the local disk but that would mean more work, and an extra query on the database.

Databases are generally more expensive to scale than other website components, so we are simply going to check if the file exists on the local disk and if it does then serve it from there, and if not then load it from the NAS directory.

This raised the question of whether checking if the file exists on the local disk take too long, especially when checking several million times per day. The answer is no. Using PHP to check whether 10 million different files exist on the local disk takes approximately 40 seconds, that’s about 4 millionths of a second per check which is acceptable for our needs of 100,000 image loads per day.

Here’s the code we used to check:

[php]
<?php
$x=0;
$start_time=time();
while($x<10000000)
{
$x++;
}
print "loop without checks took ";
echo time() – $start_time;
print " seconds <br /><br />";

$x=0;
$start_time=TIME();
while($x<10000000)
{
$name=$x . ".wmv";
if(file_exists($name))
{
//do nothing
}
$x++;
}
print "loop with checks took ";
echo time() – $start_time;
print " seconds <br /><br />";
?>
[/php]

And here was the output from the script:

loop without checks took 1 seconds

loop with checks took 41 seconds

Obviously the next step to increase performance would be to have the “local disk” which caches the files actually be a RAM disk, however we’re many millions of image loads per day away from needing to do that. For now we’ve solved our limited storage issues without taking a performance hit.

Paste Image Upload Java Applet

March 23, 2010 in Blog, Web Development by admin  |  No Comments

We’re the creators of the awesome Java applet that allows users to paste images or screenshots directly from their clipboard and upload them to the web. We use this functionality on our site UploadScreenShot.com.

You may now purchase a version of the applet which can be easily integrated with your own website. Simply embed the Java applet, specify where the image data should be posted to,  the URL to redirect to when the upload is done, and a session identifier string which will be included in the post data if you wish (so that you can track which user uploaded which image).

Applet Features:

  • pasting images directly from the user’s clipboard
  • supports pasting and dragging and dropping of png and jpg image files
  • browse for and upload png and jpg image files
  • functions in the same fashion as the applet demonstrated on UploadScreenshot.com
  • unobtrusive copyright notice in the bottom right hand corner which can be seen here
  • includes example PHP code for handling the image uploads

Each purchase provides you with a license to use the Java applet on one website only, if you need to use it on multiple websites please purchase multiple licenses. You will be emailed the Java applet and sample PHP integration after completing the payment via the PayPal button below, all purchases are final.

We offer installation services at reasonable rates, please contact us for more info.

UploadScreenShot Without Java

January 13, 2010 in Blog, Web Development by admin  |  No Comments

We’ve added a basic upload fall back option so that users without Java enabled in their browser can still use UploadScreenShot.com.

Below is a screen capture of what the site now looks like, with a file upload form, when you visit the site with Java disabled:

Click here to view full size

Uploading To FTP Using PHP and CURL

October 15, 2009 in Web Development by admin  |  No Comments

An interesting project that I was working on today required grabbing remote files to a server and then pushing them to a remote FTP server.

PHP has built in FTP functions, but there are many reasons that you might want to use CURL instead.

Here is the code that I used to upload to FTP, slightly modified for portability:

<?php
$ch = curl_init();
$localfile = “test.tar”;
$fp = fopen($localfile, ‘r’);

curl_setopt($ch, CURLOPT_URL, ‘ftp://username:password@ftp.domain.com/public_html/filesfromscript/’.$localfile);
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localfile));

curl_exec ($ch);
$error_no = curl_errno($ch);
curl_close ($ch);

if ($error_no == 0) {
$message = ‘File uploaded successfully.’;
} else {
$message = “File upload error: $error_no. Error codes explained here http://curl.haxx.se/libcurl/c/libcurl-errors.html”;
}
echo $message;
?>