Tag Archives: php
Hi,
today i wanted to give some common and not so common ideas of how to improve the performance of your web app. as you know, when you have a busy website, the performance (and along with the stability) is a key factor to have your project up and running, in this cases, you need to try to improve every aspect of your app, that is the idea, to help you to identify what can be or not be done in your case.
Database Optimization
Build a efficient database schema is not something easy, it cost time, study and testing to do it. at the time to build a efficient DB schema you need to take in consideration the following:
*Use the minimum columns as possible, and choose wisely the type of data that the database will store (if you will store number of 3 digit max, set a int(3) and not a varchar, text or a int(20))
*use the relational model, for dynamic or multiple values, use a index pattern where you have the definition of the data in 1 table and the data itself inserted by the user in other. do not create tons of columns as value_1, value_2 etc..
*add indexes to your tables
*use the primary key and unique key for columns that should have unique values to avoid data corruption or misbehavior.
in cases of the query, try to group the query’s in the less quantity of calls, use JOIN’s, select only the columns that you will really going to use, don’t make generals select’s. in case you need to return the number of something, use functions as SUM() and not mysql_num_rows().
Clean and re-usable code
you need to be careful at coding too, even that php bring a big liberty whiteout having to worry about types and variable types, you need to be responsible for what you write. the php code get messy when you do messy stuff. organize variables, functions and classes as much as you can. i’ll recommend to use a MVC model if is possible (even that before i rejected it) and a framework will also make you life easier when you learn how to use it.
there is always a good practice separate the logic from the view (i mean the main php code from the design), for this you can grab any framework, most of them already support this or get a template engine. i have always used smarty, and is very flexible and you can extend it with custom functions and modifiers, also it support time cache and others types too. even that i’m happy with it, and i’ll recommend to you, i have realized with the time that is a waste if time. it will never be faster than the normal php code, so if you want to go really well, i’ll recommend you to get a or build a class that will just load the php script as templates and that’s it. you will save time from learning a template script and save process in the meantime
cache everything
this is one of the most important thing of all. the cache is the base of any optimization. let say true, most of the pages of any app doesn’t change and if they change dynamically, is usually for a user action. if this happen you can use a selective caching, where you cache at the event if a action. make this type of cache is not a easy task, takes time and testing, but really it make great results on the practice and worth the time invested on it. the cache of css and js files is also a good technique, as well the compress of them.
use the power of javascript
i learning caching a lot of stuff to use the power of javascript. i have cached pages that needed to be refreshed each 20 seconds. surely you are asking how i made it, so basically i just cached them once and filtered the results with javascript after the ajax load of the filter using JSON and the html code from other call. if you are wondering if this is really a performance advantage, well yes, you will see a 50% of difference from a normal php processing. anyway, be careful with this type of technique, remember that javascript run on the client side, so the information passed there can be manipulated in evil ways. is a powerful tool that need to be used very careful. also, i will recommend you to use a javascript framework, they are cross browser compatible for almost all their functions, with a big community and plugins available, and heavily optimized.
i hope this help you in some way at the moment to optimize your web app’s
Regards,
Shadow.
Related Post
Hi,
in any web app (or desktop app) the security and store of password is a critical subject. there is a lot of solution out there for desktop and if you are around in the web development you will know the usual solutions as well. the hashing of the password is *usually* the most popular option (is discarded any attempt to store the password in plain text of course) and even that mysql have in-built functions as AES_ENCRYPT and AES_DECRYPT, i still think is insecure have any option to get the encrypted password in some way.
for the hash of the password, there are lot of popular functions, as md5(), sha1() etc.. and the big problem with all this functions is the advance of the processing units of our computers have made easier for the cracker to figure out the real password behind the hash.
recently, with the attacks that pletyoffish.com and other important webs have suffered i started looking for the strongest hash encryption i could find (in the past i used a combination of sha2 with a unique salt and a second pass of sha2). in this search, i realized that bcrypt was the best option here. knowing that, i looked for a class that could wrap that process and make it easier. then is when i found phpass.
phpass is a wrapper, that will use the strongest hash function available (in this case bcrypt) and if not, will go down with a combination of functions. is really easy to use, as you will see in the following examples:
Encrypt password:
$hasher = new PasswordHash(8, FALSE); $hash = $hasher->HashPassword($pass);
Check password at login
if ($hasher->CheckPassword($pass, $hash))
in this example, you need to provide the plain password and the hashed password that is keep on the DB.
if you have already a hashed password system for login, the transition should be painless, if not, i recommend you do it as soon as possible. this is better to any system you could make, really will make you sleep better at night and don’t wake up at night with the notice that your site has been hacked.
you will find more info in their tutorials and in their home page
i hope it help you in some way
Regards,
Shadow.
Related Post
Hi,
on the web app i have been working this past months, we allow the users to upload avatar photos, and some other pictures that are shown at the site. so, i implemented the code i always use to resize the images. it have done the job well on the testing phase but we found that we have bad quality images when the users uploaded their photos. so i looked for a solution and i found phpThumb. this class/script generate resized images in a quickly and easy way. it comes in 2 flavors, in a ready to use script where you pass the parameters of where is the source image, destination, measures etc.. and will print you the image (can be used in img tags as source). and also you have the class where you can manually convert the files and save it on a file or print it etc..
the class use as input the location of the source image, the binary data or a GD resource. also, phpThumb will try to use imagemagick if is installed on the server (that will give you a better quality image) and if is not available, will use GD automatically. i have tried it and i need to say that the best configuration i made to get the best quality image possibly was:
$phpThumb->setParameter('output_interlace',true);
$phpThumb->setParameter('config_output_format', 'png');
$phpThumb->setParameter('fltr', 'q|95');
$phpThumb->setParameter('config_imagemagick_path', '/usr/bin/convert');
i have tried to use jpeg format, but sometimes i get some ugly and pixelated grey background at the thin lines of the image (like words etc..) so the best option was to use png.
you can download phpThumb from here
Regards,
Shadow.
Related Post
Hi,
GD is a php extension that let you create images using code.between the images format are jpg, gif, pnf, swf,tiff and jpeg200. GD let you create images from 0, you can grab a image (from a full path or from a url) and edit them, draw things in it or mix it with other images, also you can write strings in different colors and fonts (it support ttf fonts).
i will share some examples manipulating images using GD:
1 color image:
$im = imagecreate (150, 30); // create a blank image $bgc = imagecolorallocate ($im, 255, 255, 255); // create a background color imagefilledrectangle ($im, 0, 0, 150, 30, $bgc); // draw a rectangle of the size of the image with the background color
resize image:
// Load the images $thumb = imagecreate($newwidth, $newheight); $source = imagecreatefromjpeg($filename); // Resize the images imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); // Showing the resized image imagejpeg($thumb);
Mix 2 images:
// Create image instances
$dest = imagecreatefromgif('php.gif');
$src = imagecreatefromgif('php.gif');
// Copy and merge
imagecopymerge($dest, $src, 10, 10, 0, 0, 100, 47, 75);
// Output and free from memory
header('Content-Type: image/gif');
imagegif($dest);
i hope this help you in some way
Regards,
Shadow.
Related Post
Hi,
today i wanted to talk about a class that i have been using a lot lately and i have worked with it for the past months, called pChart. this class let you create charts from stream data. the class let you create line, curve, cake/basic pie, bar,stacked,radar, 3d pie,radar, and scatter charts, and in this list i’m sure i’m forgetting some of them. the process to create the chart is very simple
as you see in the graph, the process consist in get the data from some stream, something that there is not mentioning is that the data retrieved, if is not a csv that the class have inbuilt functions to parse it, you need to prepare it, ordering in a specific way depending the type of chart you are using (if is a line bar, you need to define the serie name’s for each axis and the values for it). after you have the data, set the style, as the background, the font type and size (it support ttf fonts) and the scale. and then you are ready to draw the chart, that the returned data can be printed to the user directly, of course first setting a image type stream with the header() function or write it in a file.
below, you can see some example code:
// Standard inclusions
include(“pChart/pData.class”);
include(“pChart/pChart.class”);
// Dataset definition
$DataSet = new pData; // initialize the data parser object
$DataSet->ImportFromCSV(“Sample/bulkdata.csv”,”,”,array(1,2,3),FALSE,0); //get the data input from a csv file
$DataSet->AddAllSeries();
$DataSet->SetAbsciseLabelSerie();
$DataSet->SetSerieName(“January”,”Serie1″);
$DataSet->SetSerieName(“February”,”Serie2″);
$DataSet->SetSerieName(“March”,”Serie3″);
$DataSet->SetYAxisName(“Average age”);
$DataSet->SetYAxisUnit(“µs”);
// Initialise the graph
$Test = new pChart(700,230); //setting the widht and height of the chart
$Test->setFontProperties(“Fonts/tahoma.ttf”,8); //the font used for the chart and the font size
$Test->setGraphArea(70,30,680,200); //the width, height, x and y position of the area where the graph will be drawn
$Test->drawFilledRoundedRectangle(7,7,693,223,5,240,240,240);
$Test->drawRoundedRectangle(5,5,695,225,5,230,230,230);
$Test->drawGraphArea(255,255,255,TRUE);
$Test->drawScale($DataSet->GetData(),$DataSet->GetDataDescription(),SCALE_NORMAL,150,150,150,TRUE,0,2);
$Test->drawGrid(4,TRUE,230,230,230,50);
// Draw the 0 line
$Test->setFontProperties(“Fonts/tahoma.ttf”,6);
$Test->drawTreshold(0,143,55,72,TRUE,TRUE);
// Draw the line graph
$Test->drawLineGraph($DataSet->GetData(),$DataSet->GetDataDescription());
$Test->drawPlotGraph($DataSet->GetData(),$DataSet->GetDataDescription(),3,2,255,255,255);
// Finish the graph
$Test->setFontProperties(“Fonts/tahoma.ttf”,8);
$Test->drawLegend(75,35,$DataSet->GetDataDescription(),255,255,255);
$Test->setFontProperties(“Fonts/tahoma.ttf”,10);
$Test->drawTitle(60,22,”example 1″,50,50,50,585);
$Test->Render(“example1.png”);
and this is the result
you can download the class from here, you can find documentation and the classes definition at here, and here several examples of how to create different types of graphs
i hope this help you in some way
.
Regards,
Shadow.
Related Post
Hi,
i wrote about this in the past (you can see some post at the end) but i’m writing again as i found the perfect solution to make a SVN update after a commit to a web directory.
the difference between the old and this new one, is that the old make a svn update in all the working copy, something like that is not a problem if you have some files, but when you have like 100K files, it takes too much time and resources. so the idea was to get a list of changed directories after each commit and run a svn update on each directory.
for this i used some bash scripting and a C program (the C program is needed when the files do not belong to the user who execute the post-commit script).
in the post-commit script put something like this:
svnlook dirs-changed /path/to/your/repository > /tmp/dirschanged
while read line
do
/path/to/C/Binary/updateFolder $line
done < “/tmp/dirschanged”
and save it. remember that after the svnlook (that is what return the list of directories that has been modified) and before the while, you can use sed to change any path of your repository and convert it into a valid full path in your web directory.
then, create a .c file and paste this code to make the binary:
#include <stddef.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
int main(int argc, char *argv[])
{int i;
for (i = 1; i < argc; i++) /* Skip argv[0] (program name). */
{printf(“making update to %s \n”,argv[i]);
execl(“/usr/bin/svn”, “svn”, “update”,argv[i],
(const char *) NULL);
}
exit(0);}
compile and set a chmod +s, and is done
. the binary will accept any amount of arguments as paths to run the svn update, anyway i’ll recomend to make 1 at time, so you have more control of it.
i know that this code could be improved, maybe using less bash scripting and more C coding, but i’m not good as before in C, so for me was more easy to make the loop and event the replacements with sed in the bash scripts.
i hope this help you in some way
Related Post
Hi,
some weeks ago someone told me that ngnix was better than apache as can handle more users and was more stable with big traffic. as i usually don’t discard the opinions and recommendations i receive, i started researching about this as i didn’t know anything about ngnix. for that, i wanted to write this post so can save you some time looking at the internet
. for my research i used sources as serverFault.com and other blog post where it benchmark different php scripts (custom and wordpress blogs).
Apache and ngnix, what is the diference?
the main difference between ngnix and apache is that the way both web servers handle the user requests. apache have a multi thread architecture and ngnix have a unique thread architecture to process the user request. this is the main difference between both, the other important difference are the config files and the rewrite rules, where the format is difference from apache and a new user need to learn this new way to format the htaccess and the config files. other than this, both can manage virtual hosts, aliases, etc..
Define the goal or purpose to choose.
i always say that there is no a complete tool or a ultimate language and technologies, each decision of what tool to use depends of the requirements of the project. in this case is the same, you need to evaluate your project to decide what to use.
after my research i found that ngnix have a greater performance, in terms of memory needed, when the ngnix is serving static content. static content is called all what are images, videos, flash, files etc.. and optimized and cached dynamic pages, like a wordpress blog with super cache plugin.
in term of speed both are almost equal, having a difference in favor to ngnix at serving static files.
Conclusion
when i started to research this, i have in mind 2 projects, one of them was a non-optimized sites and the other a highly optimized site that doesn’t have a lot of cached pages but have a lot of static content.
then my conclusion was that you need to choose depending of your project requirement, to use apache or ngnix or both (yes, both can be used at the same time).
if you have a crappy php site, don’t bother you, ngnix don’t going to give you any improvement, better, invest your time to improve the code.
if you have a highly optimized site and cached most of their pages and you don’t bother to rewrite any htaccess or config file in this new format, ngnix will give you a improvement in your server.
if you have a mixed site, highly optimized, but not too cached her pages, you can have both running, ngnix serving static content and apache serving the dynamic content, this will improve in some way your site with a better load balancing proportional of the percentage of static files are serving.
i hope this help you to decide in this matter, i’ll post later a tutorial of how to install ngnix and apache togheter
Regards,
Shadow
Related Post
Hi,
for a tweet of one of the person i follow, i noticed the existence of this project.
basically GlotPress provide a web end and administration for translation of phrases for development projects.
is a nice platform, easy to use and the well implemented usability make the translations something fun and not something boring as always
. i have contributed with some translations from english to spanish for the gravatar project.
the project is still under development, you can see more info here.
Related Post
Hi,
some new tips about subversion
if you need to update a web directory after someone make a commit just follow this guide: http://subversion.apache.org/faq.html#website-auto-update
i wanted to post this why it take me some time to figure out that a simple bash script don’t going to work and even if it worked with some tricks, i always getting a merge and not an update of the repository
some thing that the faq don’t mention is how to compile the program, if you are a newbie and don’t know how to do it, just run this command
gcc your_file_name.c -o your_binary_name
i hope it helps
Regards.
Shadow.
Related Post
Hi,
recently i changed how a REST API sent the info from xml to JSON, that mean that now the arrays was converted into objects after the json_decode(). don’t was too much problem till i see that my smarty templates don’t worked anymore
the change of each file don’t was an option and the convert from objects to arrays is wasting resources in nothing, so i made a hack in the smarty main class
basically in the file Smarty_Compiler.php at line numero 1203 i added this if():
if(is_object($from)){
$output .= “\$_from = $from;”;
$output .= “foreach(\$_from as $key_part=>$item){“;
}else{
and in the else, you wrap all the other code to parse arrays
now the foreach will parse objects and arrays
i hope it helps.
Regards,
Shadow.








