• Secure PHP Programming

    Posted in php | Tuesday 9 September 2008 3:02 pm

    Writing insecure code is easy. Everybody does it. Sometimes we do it accidentally because we don?t realize that the security issue exists, and sometimes we do it on purpose because we suspect the bad guys won?t notice one little vulnerability. Secure programming is often overlooked because of ignorance, time constraints, or any number of other factors. Since security isn?t flashy until something goes wrong, it is often easy put it off.

    Once your application is compromised, you will realize there?s nothing more important. The best case scenario is that you lose days of productivity and suffer downtime while you fix what was damaged. The worst case scenario &em; your data is compromised and you have no idea if it is correct, much less what the hackers managed to copy and read. Did you expose usernames and passwords to the world? Did you happen to release the credit card information for thousands into the den of identity thieves? You?ll never really be able to know. It?s best to practice secure programming so you never need to ask yourself these questions.

    With this in mind, let?s examine three different classes of secure programming “no-noes,” storage risks, system risks, and exposure risks and discuss how we can prevent each of them. Server configuration and data transmission security are beyond the scope of this article, but the reader should be aware that they also play a major role in securing a web application.

    Storage risks are those risks involved in the storing data and interacting with a database server or file system. The most widely known of these in the infamous SQL injection attack. SQL injection is when you allow the user to input data into a query, and instead of a value he adds his own SQL into the query. The easiest way to prevent this type of attack is to escape every user variable that could touch your queries. Luckily, PHP has several build in functions for handling this, such as mysql_escape_string(). Essentially, this works by escaping characters in a string that could conceivably be used to terminate your query and run a user specified query.

    When should you escape user data? It all depends on who you talk to. Some programmers prefer to escape as soon as it enters the application, while others prefer to wait until just before it is placed into the query. Personally, I prefer to escape right before it is inserted into the query. I do this because I can always look at the code, see the database interaction, and see that the data was escaped before it was being used. I don?t need to search the entire source to make sure something was escaped.

    The second storage risk we?ll talk about is storing passwords as plain text (hereafter referred to as clear text). I know you guys do it; I?ve seen too many open source applications and too many in-house applications to believe that it doesn?t go on. Simply put, there is never any reason to store a password in clear text. It doesn?t matter if you?re storing the password in a database or a flat file, always store passwords as a hash. You can accomplish this simply enough by using PHP?s md5() function to transform the password before you insert it into your storage medium. Since md5 is repeatable, you can validate a password by simply using

    When should you transform the password to a hash? You should do it as soon as possible. Don?t let the password variable float around your application at all. As soon as you grab the password input, convert it into a hash. I prefer to do this by setting the password variable to its own hash, this avoids the chance of using the wrong variable in later code.

    Next, let?s talk about the usernames and passwords your program needs in order to interact with other applications (like database servers). You should always separate these out into a different PHP file than the rest of your code, and reference them as constants or variables. This not only makes your code easier to maintain (if you need to change a password, you know exactly where to look), it the event that your source gets released, you know that the password isn?t in that file. While it?s certainly true that they could grab your password file, it does reduce the risk considerably.

    Before we leave usernames behind, I want to touch on the concept of division of power. We?re not talking about the government in this case, but about database users. The database user accounts your program uses should have the minimum level of access they need in order to function correctly.

    If your application only reads from a database, then the database account it uses should only have SELECT permission on that particular database, and no access to any other database.

    To take this concept a step further, I prefer to create multiple database accounts for my web applications. Typically I create one account that only has INSERT permissions for the particular tables the software needs to write to, and a completely separate account that only has SELECT access. This makes sure that no INSERT queries are accidentally performed and mitigates the possible damage done by SQL injections.

    Of course, multiple accounts work best when there?s a clear separation between those who can write to a database and those who can read it (such as a CMS). In theory, you could use multiple accounts in any application but you run into problems with the number of open connections to the database. This is simply something that should be considered as a possibility during the design phase of your software.

    I?m a big advocate, as are most programmers, of breaking source code down into multiple files at every logical opportunity. However, I?ve noticed that a lot of PHP programmers have a nasty habit of naming PHP files they intend to use as libraries or other include types with the extension .inc, or .config, or some other non .php extension. This is a horrible idea because the server its running on might not be setup to parse these extensions as PHP files, so anyone loading the file would be exposing their source code (and potentially passwords, usernames, and other protected information) to the world. I prefer to prefix filenames myself, using inc_ or class_ when needed.

    While we?re discussing included files, I would like to talk about to other security precautions. If you have a PHP file that you intend to use only as part of a larger PHP application, add this line to the beginning of the file (__FILE__,

    %ARTICLEBODY%
    Return to Index SERVER['PHP_SELF']).

    This will cause the file to immediately terminate is someone tries to run it directly. A well written include or class file shouldn?t do anything when loaded on its own, but you can never be too careful &em; especially when a one line cut and paste can potentially save you so much heartache.

    The other include-related item I?d like to talk about is the difference between include() and readfile(). Include will tell the server to parse the file as PHP, while readfile tells the server to output the file as straight text. You should never use include on a file that is publicly writable (for example, if you have an application that appends user submitted data to end in order to simulate a graffiti wall or guest book) or on a file that you don?t control (files on other servers, or that others can edit). A malicious user could easily inject his own PHP into your system, causing untold amounts of havoc. At the same time, you should never execute readfile on a file that ends in .php. On a misconfigured system, this runs the risk of exposing your source code to the world. To summarize, use readfile() on html, txt, and remote files. Use include on local files with php code you want to execute.

    Now let?s talk about system risks. I think of system risks as those things related to the way code executes. The primary system risk in any application is invalid data. You can never valid data enough. As soon as user data enters the system, you should immediately verify it exists and that it is what you want it to be, if not your program should halt and prompt the user for better input.

    When validating data, you should use the tightest filter possible. For example, if your program is expecting a percentage, you should not simply verify that they entered something. Your program should verify that it is numeric and between 0 and 100.

    You should also validate at every level. Every time a function accepts input, verify that the data is what you expected it to be and react accordingly if the data is bad. This will make it more likely that you will catch bad data due a programming oversight, it also has the added advantage of catching logic errors in your software.

    Next, I?d like to talk about eval(), exec(), and their ilk (shell_exec(),system(), passthru(), and pcntl-exec()). Visit their respective php pages to find out more about them, but in actuality there is very rarely any reason to use them. Eval will run any php code passed to it as a variable. This is inherently dangerous because you no longer have absolute control over what code is executed. If you must use eval(), don?t ever run it with a variable that has been derived from a user determined value, otherwise you run the risk of a hacker injecting his code. Exec() and the like pose similar threats, allowing your script to interact with the command line is a level of power you should rarely, if ever, need.

    Finally, let?s talk about a couple of exposure risks. Usually, you don?t want to show your error messages to the world. For one, they freak people out. Secondly, they give hackers a wealth of information about potential bugs in your code. On production systems, always turn your error reporting off and use PHP?s errorlog() function instead.

    The last risk we?ll talk about is using session IDs. Simply put, try not to ever send the session id to the user. Sessions aren?t secure, but if you transmit the session ID you run an even greater risk of someone other than the expected user to act as a “man in the middle” (to steal an analogy) and piggy-back off of the legitimate user?s session. An example of this would be using a session id to hijack someone?s shopping cart and change a delivery address, get credit card information, or do something even more malicious depending on the system.

    We?ve discussed many security risks involved with programming in PHP, but they boil down to a few simple concepts.

    * Never trust the user &em; don?t let them run code on your sever and always validate any data they send you.

    * Don?t give the user, or your software, any level of access greater than the absolute minimum needed to successfully accomplish their tasks.

    * Don?t tell the user more than they need to know &em; don?t let them see your code, the session id, or any error messages that you didn?t create specifically for them,.

    PHP Hosting

    Posted in php, webhosting | Sunday 31 August 2008 9:54 am

    PHP hosting is a server-side scripting environment that is used to create dynamic web pages. PHP is an abbreviation for Hypertext Preprocessor, an open source language widely used by programmers and web developers. The fact that it is open source gives it a lot of advantages over proprietary programming languages. Due to this reason, PHP has been the most famous server-side scripting language and almost all hosting providers offer PHP hosting services nowadays.

    PHP is an object oriented language. The way PHP hosting works is that the web server would filter a request document using PHP and generates the output from PHP to the web browser. These documents are usually in HTML format with PHP tags inside. The tags can be run on both Windows and UNIX servers. In terms of output text, PHP is capable to generate any format such as XHTML and XML.

    With PHP, web developers would be able to perform any CGI tasks, such as generate dynamic contents or send and receive cookies. PHP is also capable of outputting PDF files, Flash videos and images on the fly at high speed. This is possible due to its ability to save the required files in its file system and forming a server-side cache.

    There are a host of advantages of using a PHP hosting. For beginners, it is a relatively easy language to learn and work on. While for seasoned developers, there are a lot of advanced applications and features that comes with PHP hosting. In terms of cost, it is one of the cheapest hosting solutions as it is an open-source technology. There are also programming tools that come free with PHP hosting, contributed by programmers worldwide.

    PHP is especially strong in relational databases, which are used for dynamic contents, product catalogs and e-commerce applications. The relational database application that comes with PHP is called MySQL, which is also open-source. It is known for its high reliability, precision and flexibility. These advantages have made it the more preferred alternative compared to proprietary databases systems.

    Overall, PHP hosting is one of the most complete hosting packages available in the industry. It is perfect both for beginners who require easy-to-use hosting services and for advanced users who require powerful web applications. The value that it offers is even more significant due to its inexpensive pricing, especially compared to proprietary hosting services.

    Why has Google banned my website?

    Posted in php | Tuesday 19 August 2008 10:33 pm

    As an SEO company this is one question we get very often. There are few bigger problems for an Internet business or search engine marketer than to find that their website has disappeared from Google’s search rankings. Sometimes their website doesn’t even rank for their own web site’s name. How did this happen? Read below to find out some of the reasons why a site may have been banned from Google and what to do to get back in the rankings. Usually there is no warning for being banned or penalized by Google except for the steady drop of sales and visitors to your site. Many site owners and search engine optimization firms are left with little to no idea why they were removed and can be left scratching their heads as to how to get back in. While there are many reasons why a site has been banned, here are a few of the more common reasons. If your site has been banned contact your SEO company or give Big Oak a call to help you get back on the right track to high Google rankings.

    1. Robots and Meta Tags
    The first and simplest solution many be that your robot.txt file has been changed to prevent search engines from entering your site. Or your meta tags could be directing the search engine robots to exclude your site. While this would be highly unlikely, it is best to rule this out. So check your robot.txt file (if you have one) and your meta tags. Unless you want your site hidden, you should never read this in your meta tags: . If you see this, you are blocking your site from Google.

    2. Cloaking (A Big Google No-No)
    Straight from Google’s website: “The term “cloaking” is used to describe a website that returns altered web pages to search engines crawling the site. In other words, the web server is programmed to return different content to Google than it returns to regular users, usually in an attempt to distort search engine rankings. This can mislead users about what they’ll find when they click on a search result. To preserve the accuracy and quality of our search results, Google may permanently ban from our index any sites or site authors that engage in cloaking to distort their search rankings.”

    If your website or web pages are set up to display different information for a search engine spider versus a real person, then you are cloaking. Cloaking delivers one version of a page to an Internet user and a different version to a search engine. The cloaked page is packed with keyword and terms that the site wants to be highly rank for so, in essence, they are cheating. There are good reasons for cloaking as well, such as targeted advertising, but if you are trying to manipulate your rankings you should put an end to this immediately.

    3. Duplicate Content or Websites
    If Google finds multiple web pages have the same content they may penalize each website for this. Of course, someone may have copied your content and Google banned you even though it was your original content that was taken. Make sure no other site is using your content. You can do this by performing a Google search using some of your text with quotation marks (”) around it. If you do find someone is using your original copy visit here to learn more about copyright infringement: http://www.google.com/dmca.html.

    4. Hidden Text and or Links
    How can text been hidden? Well, there are a variety of ways - some are more sneaky than others. But is boils down to this: it is considered hidden if the text or link is invisible to the website visitor but can be seen by search engine spiders. This used to be done quite often, such as making your text white on a white background or using cascading style sheets (CSS) to hide your text, but search engines can easily spot this today so it is best to avoid it altogether.

    5. Keyword Spam and Keyword Stuffing
    Ever seen a web page with a very awkwardly written first paragraph where a certain word is repeated ad nauseam? Here’s an example:
    “We sell the best father’s day gifts for father’s day. If you like to celebrate father’s day we can help with the best father’s day gifts for father’s day.”

    Care to guess which keywords are being targeted? This is keyword spamming or stuffing but it is just the tip of the SEO iceberg. This is just the content on the page, there is probably keyword stuffing happening in the code: in the meta tags, invisible text, alt tags, title tags and comment tags. etc. If the word or phrase is repeated too often Google can place a filter to reduce the site’s rankings or simply ban the site. Keyword density can be tricky but, as a general rule, Big Oak shoots for 3% to 12% of all text on a page to be our targeted keywords.

    6. Doorway Pages
    Defining a doorway page can be difficult so here is our definition that could potentially ban your site in Google: pages that are created in order to attract search engine spiders and be ranked highly for their targeted keywords. Real visitors find this page and then continue to the “real” website from there. Hence the name “doorway page”. These pages aren’t in the navigation most of the time. If you come across a page where much of the information is duplicated from other pages on the site but it is different in terms of keywords only, this is most likely a doorway page.

    As you can see this can be a gray area. Some pages on a website may focus on a particular subject and be innocent of trying to lure search engine spiders only for high rankings. Err on the side of caution and make sure the page is useful and part of the your site’s navigation.

    7. Redirect Pages
    Sneaky redirection pages are set up in groups from 5 to hundreds. They all target similar and related keywords or phrases. Usually, the only links on these pages are links to other pages in the same family creating a false sense of related linking.
    These pages don’t necessarily contain content that any human would be interested in. These pages may show up high in Search Engine Results Pages (SERPS), but when you click on one of these pages from the SERPS, you will be redirected to another page. In other words, the page you click to see is not the page you actually get to read.
    The redirect can be automatic, done with a meta refresh command or through other means such as a the mouse moving while on the redirect page.

    8. Buying Links
    While buying links may not get you banned, they can certainly hurt your page rank. Google has slowly been catching on to this fad and has measures in place to put your site in limbo for 6-8 months (known as the “sandbox effect”) so you can’t instantly benefit from buying links to your website. Many sites that sell links are being devalued by Google, making an investment in this strategy a waste of money and time. Ultimately, stay away from buying links to increase your ranking.

    9. Linking to Bad Neighborhoods
    Link campaigns are good thing when done correctly; we would say they are a necessity in today’s SEO world. But linking to bad neighborhoods are a sure way to lose your rank in Google. If you aren’t careful about who you are linking to you can easily disappear overnight. Basically, while you may be ethical and do everything right linking to someone who isn’t can be considered guilt by association. Always verify your links to other sites. Make sure they have page rank in Google and are indexed by Google. Try searching for their URL to see if they are indexed. Avoid linking to any sites that use spamming techniques to increase their search engine rankings. Regularly checking outbound links from your site and removing any offenders is a good idea.

    A few site types to avoid:
    - Free-for-all link farms
    - Adult sites
    - Gambling sites

    10. Code swapping
    Optimizing a page for top ranking, then swapping another page in its place once a top ranking is achieved.

    What does Google say?
    “Don’t deceive your users, or present different content to search engines than you display to users,” Google says, and they list some bullet points on avoiding being banned.

    Avoid hidden text or hidden links.
    Don’t employ cloaking or sneaky redirects.
    Don’t send automated queries to Google.
    Don’t load pages with irrelevant words.
    Don’t create multiple pages, subdomains, or domains with substantially duplicate content.

    Avoid “doorway” pages created just for search engines, or other “cookie cutter” approaches such as affiliate programs with little or no original content.
    Google also states:

    “Avoid tricks intended to improve search engine rankings. A good rule of thumb is whether you’d feel comfortable explaining what you’ve done to a website that competes with you. Another useful test is to ask, ‘Does this help my users? Would I do this if search engines didn’t exist?’”

    While creating a page without a thought to search engines is probably going a little too far, optimizing your site for an organic search, as long as it conforms to their standards, is perfectly acceptable.

    We pride ourselves on being an ethical SEO company. We follow the guidelines and do things the right way. There is no easy path or shortcut to high rankings in Google or any other search engine.
    We welcome any questions and are always willing to share information with clients and perspective clients. Give Big Oak a call today for a free consultation and search engine report to find out where you rank in the major search engines. Whether you feel you have been banned or just want to show up higher in Google’s search engine results, we can help you.

    Beware of Google Ban!
    If you are carrying out search engine optimization your site for high positioning in major search engines such as Google, Yahoo! and MSN you need to make sure you don’t get banned by accident…

    IMP**** In the spirit of fair play and providing depth in its results, Google frowns on duplicate content. Some web site owners purchase multiple domains and copy their content for both domains. They mistakenly think that having another domain with the same content is just going to replicate their success, but unfortunately it isn’t that easy!

    Another more common mistake is to have multiple domains pointing at the same site - this can be as simple and unintentional as having www.refreshedmedia.co.uk point to www.refreshedmedia.com. Unfortunately the outcome is to end up with 2 copies of your site in the search engines and they don’t like it.

    What’s the solution? In most cases, a 301 redirect is your best bet. It’s a server-side redirect most administrators can handle in a few minutes. In effect, it’s a proper way of telling search engines to ignore the content from the redirected website, and just take it from the original.

    You may have many good reasons for owning multiple domains, including brand protection. For example, we own refreshedmedia.com AND refreshedmedia.co.uk for the simple reason that we don’t want someone else feeding off our success and diverting our customers away, simply by purchasing 1 domain for a few Ј.

    So how do you keep Google and friends happy?

    If you secure more than one domain, redirect the other sites to your main website using a 301 redirect, or use the extra domains for unique content (perhaps showcasing other products or services).

    Solution:

    ****How to get back into Google

    Once you have cleaned up your website (and we mean really cleaned it up as you may only get one chance to get back in), you should contact Google. Explain that you made a mistake, you have corrected it and certainly won’t do it again.

    You don’t have to contact Google but it can’t hurt. They will eventually spider your site again and see that you have cleaned up your website. You may have to wait a few months for Google to re-index your site so be patient and don’t tinker with your website too much unless dictated by your site’s products or content needs.

    The worst case scenario is to start a new site. Sometimes this can be necessary but only in the most extreme cases.

    [VACANCY] Freak PHP Programmer

    Posted in php | Tuesday 19 August 2008 10:30 pm

    We are a IT company located in Jakarta (Gandaria) as a provider of IT solutions and outsourcing services.
    We have been developing an Asset Management System and a Digital Document Management System, that interconnected each other.

    We need a strong and freak PHP artist to become our team member.
    ARE you ?

    <?php
    if ($phpExperts && $needJobs ) {
    mail($me,“PHP Experts” , $resume );
    }
    ?>

    Objectives:
    - To design and administer software and databases.
    - To test and develop software.

    Responsibilities:
    - Develop some codes that are needed for the project’s website development
    - Manage systems provided for business study and plan

    Education:
    - Hold Minimum Diploma degree in Computer Science or Information Technology or any course related

    Required skill(s) :
    - Excellent PHP programming Skills
    - Understand about Webservices in PHP
    - Experienced in framework, CMS development
    - Skilled in CSS and xHTML, concerned in latest web standards

    Prefered Skill(s) :
    - PHP Framework - Zend | Prado | Sympony | Cake
    - CMS Customize
    - AJAX
    - Web Design (Template, icons, menu, CSS)
    - Web Security
    - Knows how to handle Linux Servers (Red Hat).

    - postgreSQL (syntax and design)
    - Oracle (syntax and design)

    Prefered experience/knowledge
    - Asset Management System
    - Digital Document Management System (Filing)

    Full-Time, Part-Time and Contract position available.

    Work in a team,
    Able to work under pressure and willing to work overtime,
    Productive and able to work hard under pressure

    Please send your CV to :
    doddy@gipindo.com | doddy.prima@gmail.com
    + with screen-shoot or web-address of portfolio
    Doddy Prima Kd

    Monitoring Search Engine Positions

    Posted in php | Tuesday 19 August 2008 10:29 pm

    Since search engines are the first stop for people on the Internet looking for goods or services, the position your web site appears in search results is an important factor. If your URL shows up far down the results list, the chances of the consumer never finding you increase incrementally. Once you achieve a high search engine position, it is essential that you make sure you maintain the high ranking you have worked so hard to achieve. This means you must come up with a strategy to monitor your search engines positions. This strategy is crucial to the success of any marketing campaign. Think of your search engine positions as your online portfolio. Would you let your stock portfolio be ruled by chance and market fluctuations, or would you keep close tabs on your stocks so you could buy and sell when the time is right? This is the way you must consider your search engines positions.

    Be aware that at first, after you have launched your search engine campaign and done all the right things to increase your rankings, you will most likely see a continual upward climb. What you need to be on the lookout for is the moment that upward climb reaches a plateau. When this happens, your search engine position campaign moves into stage two, the monitoring and protecting stage.

    In stage two, do not be concerned about the short-term fluctuations in your positions. These are similar to the subtle rising and falling of stocks in a portfolio. Short-term movement is an integral part of the whole process. It’s the long-term changes that you must watch for and prepare to act on immediately.

    Analyzing the long-term trends of search engines positions is imperative. The way in which search engines rank web sites may change at the drop of hat. If you are unaware of these changes - many of which are subtle yet can be deadly to your ranking - your position may drop to the bottom of the list before you can get your bearings. To prevent this kind of precipitous drop, you must create a system to monitor your positions on a monthly basis. Devise a chart to keep tabs on your top ranking positions or your top pages, and make sure to watch “the market” closely.

    Each search engine uses a formula to compute web site rankings. When a search engine changes this formula in any way, it may raise or lower your ranking. Some search engines use a number of different formulas, rotating them so that a formula doesn’t become overused or outdated. Depending on which formula is being applied, your search engine position may suddenly drop or rise in rank significantly. Therefore, you must check your positions frequently in order to catch when a search engine changes formulas and what effect it has on your positions.

    You must also deal with your competition - a crucial factor you must always be vigilant about. Your competitor’s position may suddenly rise, automatically lowering your position. Or their position may drop, pushing your position higher. Each month, expect position changes due to the continual changes that are occurring in your competitor’s position, and be prepared to adjust your marketing strategy to compensate for decreased rankings. Monitoring these fluctuations will also give you vital information about how to improve your web site to increase your position in search results.

    Of course, you must discern what the most popular search engines are in order for your monitoring efforts to be effective. Right now, there are ten popular search engines that direct most of Internet traffic to your sites. The challenge you face is that these top ten may change from month to month.

    This means that your must not only monitor your search engine positions, but you must also keep track of the ranking popularity of the search engines you are monitoring. Find out which search engines people use most frequently every month and be sure to live in the present! People are fickle about their favorite search engines, and it takes constant vigilance to follow their dalliances. The search engines they loved when you first launched your campaign may be old news in the next few months. You must adjust your list of engines according to the whims of the Internet users. Check out http://www.searchenginewatch.com/reports/netratings.html for a current list of web site favorites.

    Another factor to monitor carefully is a sudden drop of your positions in all search engines. This is not the same as monthly fluctuations - this is a neon red warning sign! It could mean a number of different things.

    It all your search engine positions have plummeted, it may indicate that search engines spiders - those sneaky programs that seek out your site and rank their positions - have found some type of problem with your web site. If you have recently changed the code, for instance, the spider may become utterly confused and consequently drop your positions disastrously. If a spider creeps up on your web site when it is down for adjustments or changes, you may actually disappear from a search engine index entirely. Or a search engine may drastically change its formula, and suddenly all of your web site come up as irrelevant. If that search engine is a current favorite, it may create a domino effect, causing all of your position to drop in all search engines.

    Some search engines rely on the results from other search engines, and it is vital that you know which engines these are and keep track of all the engines they influence. The biggest problem here is that search engines will sometimes change affiliations, and this can create a major shift in the geography of the Internet. For example, recently Yahoo decided to display only results gleaned from Google. So you must not only monitor your own positions, but you must keep abreast of seismic shifts in the landscape of the Internet as a whole.

    Finally, pay attention to your keywords. Keywords are the foundation bricks of the entire search engine system, and they demand individual scrutiny in your monitoring efforts. If you have found that a number of your positions have plummeted, it may mean that a page of your web site has become invisible or inaccessible to search engine spiders. Or the competition for that particular keyword or phrase has recently rocketed into outer space. In either case, you must act quickly and efficiently to regain lost ground.

    Your search engine marketing campaign is an investment. If costs you time and money on a continual basis. Protect this investment as diligently as you would your financial portfolio. In the same way, track your positions from an objective perspective, and monitor your positions on a regular basis. Make sure your time and effort reap rewards by keeping your eye on the big picture - your long-term marketing campaign.

    No need for set/get methods in Python

    Posted in php | Monday 18 August 2008 5:58 pm

    Python code doesn’t typically use the get and set methods so common in PHP. Normally, when writing PHP code, you carefully protect your instance variables by making them private, so callers can only interact with them via getter and setter methods. For example:

    class Book {
      private $title;
    
      public function setTitle($title) {
        $this->title = $title;
      }
    
      public function getTitle() {
        return $this->title;
      }
    }
    
    $book = new Book;
    $book->title = 'Code Complete';

    However, in PHP, the code above returns the following error:

    Fatal error: Cannot access private property Book::$title

    Python’s solution to this problem is more readable, it has a construct called a “property”. Properties are a neat way to implement attributes whose usage resembles attribute access, but whose implementation uses method calls. These are sometimes known as “managed attributes”. Basically, a property is a way to make a function call look like an instance variable reference. For example:

    class Book {
      private $title = property(getTitle, setTitle);
    
      public function setTitle($title) {
        $this->title = $title;
      }
    
      public function getTitle() {
        return $this->title;
      }
    }
    
    $book = new Book;
    $book->title = 'Code Complete';

    Whenever someone writes $book->title, they’re really calling $book->getTitle(). Although the class has getters and setters, the callers of the class still get to use the original, simpler, easier-to-read syntax for accessing the value.

    This way you get the best of both worlds: clean and simple client access to your class, and protection and flexibility within the class.

    Examples

    Python (run code)

    class Book(object):
    
        def get_title(self):
            return self.__title
    
        def set_title(self, title):
            self.__title = title
    
        title = property(get_title, set_title)
    
    Book.title = 'Code Complete'

    PHP (run code)

    class Book {
      private $title;
    
      public function __get($property) {
        if (!property_exists($this, $property)) {
          throw new Exception('No such property: ' . $property);
        }
    
        $method = 'get' . ucfirst($property);
        if (!method_exists($this, $method)) {
          throw new Exception('No such method: ' . $method);
        }
    
        return $this->$method();
      }
    
      public function __set($property, $value) {
        if (!property_exists($this, $property)) {
          throw new Exception('No such property: ' . $property);
        }
    
        $method = 'set' . ucfirst($property);
        if (!method_exists($this, $method)) {
          throw new Exception('No such method: ' . $method);
        }
    
        $this->$method($value);
      }
    
      public function setTitle($title) {
        $this->title = $title;
      }
    
      public function getTitle() {
        return $this->title;
      }
    }
    
    $book = new Book;
    $book->title = 'Code Complete';

    As you can see in the example above, PHP allows you to do something similar using the __get and __set methods, but can be a bit tricky to get right. Python’s “property” construct lets you do this painlessly.

    [PHP] Use an IP based authentication method (Basic)

    Posted in php | Monday 18 August 2008 5:57 pm

    So, enough of the tutorials and on to the scripts! This script is a very basic authentication method using an IP address and only displaying the login form to users (so is a secondary stage authentication method).

    The script

    <?php
    // The two variables that will decide if the person’s IP matches :D
    $myip = “127.0.0.1″;
    $ip = $_SERVER['REMOTE_ADDR'];
    // Now we do the quick check :D
    if ($myip == $ip) {
           echo ‘<center><b>Welcome User!</b><br /><br /><b>Your IP: ‘;
           echo ($ip);
           echo ‘<br /><br /><font color=”green”><b>Access granted!</b></font>’;
           echo ‘</center>’;
           die();
          }
    else {
          echo ‘<center><b>Access forbidden!</b></center>’;
       die();
         }     
    ?>

    The explanation
    So, the long winded explanation. The two variables $myip and $ip are used in the script to ensure the code is nice an clean and very easy to customise. The $myip variable is the only variable that needs to be edited and must match to your IP (in the script, it is set as 127.0.0.1 as I created the script for use on a local web server testing environment). The $ip variable uses $_SERVER['REMOTE_ADDR'] to get an accurate IP address as reported by the web server to PHP and is vertually impossible to forge or fool!

    We then move on to the if statement and the actual checking and it is pretty self explanitory if you have been following my previous tutorials. If $ip is the same as $myip, then the statement is true and so executes, if not, the statement is false and the else statement executes :D

    Have fun implementing this quick script……. and stay tuned for more!

    Waves,
    Matthew Gall

    php session/cookies failed on certain page

    Posted in php | Monday 18 August 2008 5:57 pm

    Ever faced a situation where your supposed to be authenticated-by-session or cookie failed? it works initially, but on certain page, it fails.. and you don’t know what went wrong because you cold swear that the exact same piece of code works on the previous page but not on another page..!

    Well, most probably here’s how your php authentication code look like, where you included it in every part of your php page, either using session or cookie. The example below uses session:
    =======================================
    session_start();

    if ($_POST){
    $_SESSION['user']=$_POST["user"];
    $_SESSION['pass']=$_POST["pass"];
    }

    include (”dbconf.php”);    //the php file that contains the database settings
    // query for a user/pass match
    $result = mysql_query(”select status from login
    where user=’” . $_SESSION['user'] . “‘ and pass=’” . $_SESSION['pass'] . “‘ “) or die (mysql_error());
    =======================================

    Then the code above works for first page, second page… but on the 3rd page it returns an error. Or sometimes the session/cookie suddenly disappeared, and it returns invalid username/password! Let me tell you two thing:

    1) The page before the session/cookie fails have a Submit button with the method set as POST.
    2) Now let me tell you where it went wrong. See the line if ($_POST){ above? THAT’s WHERE it went wrong. Instead of writing only $_POST, you should write something like ($_POST['username'] || $_POST['password']) or whatever your username and password box named in the previous page. Because if you wrote only $_POST, and a page has a Submit button with method POST, the line if ($_POST) will trigger and passes the now empty $_POST["USER"] to $_SESSION['user'] since there are no input box named as USER or PASSWORD in the page (and even if they do, most probably it’s not meant for password authentication), and of course, the sql query below it will return an error since it now queries using an empty or wrong $_SESSION['user'] and $_SESSION['pass']!

    I faced the above problem because I tend to copy paste codes from supposed-to-be session tutorial. IMHO, it’s a bad practise to write a tutorial which can complicate matters in the future, although probably they only meant to simplify things.

    In summary, here’s how your session authentication should look like:

    ==============================

    if ($_POST['username'] || $_POST['password'])
    {
    $_SESSION['username']=$_POST['username'];
    $_SESSION['password']=$_POST['password'];
    }
    ==================================

    Hope this post helps someone out there!

    Mascara Php

    Posted in php | Monday 18 August 2008 5:57 pm

    Trabalhei em um projeto aonde alguns dados estavam no banco sem mascara, por exemplo o telefone. No banco estava 1212341234, perguntei porque não colocar no banco com mascara e me responderam que era para economizar espaço, nisso comentei que disco hoje em dia está tão barato e se seria vantagem fazer isso mesmo a resposta que eu obtive foi que o problema não era o espaço em si, mas o trafego de rede.

    Nao me convenceu 100%, mas tive que fazer uma função básica de criar mascaras e estou disponibilizando ela aqui.

    [sourcecode language='php']
    public static function mascara($mascara,$palavra){
    $pont_palavra = 0;
    $resultado = “”;
    if( strlen(trim($palavra)) < 0 )
    for($i = 0; $i < strlen($mascara); $i++){
    $mascara_char = substr($mascara,$i,1);
    if ($mascara_char == ‘#’){
    $resultado .= substr($palavra,$pont_palavra,1);
    $pont_palavra++;
    }else{
    $resultado .= $mascara_char;
    }
    }
    return $resultado;
    }
    [/sourcecode]


    mascara(”(##) ####-####”,”1212341234″); // (12) 1234-1234

    TorrentFlux - PHP BitTorrent Client

    Posted in php | Monday 18 August 2008 5:56 pm

    TorrentFlux is an web-based system ( PHP ) for managing bit torrent file transfers. It is an open source package (GPL) and developed for Linux, Unix & BSD platforms on the ubiquitous LAMP stack.

    Screenshots from version 2.1:

    TorrentFlux

    Here’s what you need to use TorrentFlux

    • A Unix like OS (Linux, BSD, Solaris, etc.)
    • A Web Server that supports PHP (e.g. Apache)
    • SQL Database (MySQL, Postgres)
    • PHP 4.3.x or higher
    • Python 2.2 or higher
    • Note: Some add-ons may have additional requirements

    Want to download and start using TorrentFlux ? Download Now!

    TorrentFlux also has some Add-ons & Utilities that you can use .

    Next Page »