May 15, 2013

How to import all classes within filesystem in php?

J Moore’s Question:

The folder structure is like so:

/main.php
  /lib/class1.php
  /lib/class2.php
  /lib/class3.php

I want to have main.php make available all the classes in lib without doing a ton of require/include. Is this possible? Is it possible to just include all files within a directory?

Create an autoloading function to load the class directly from your URL

function __autoload($class_name) {
    include "/lib/".$class_name . '.php'; //Add your folder structure like this
            // ^ Change the path to your specific need
}

//Then Simply
$class1_object = new Class1(); 
May 14, 2012

Using a variable inside an included file from function

Question by Djave

I’d like to have a header.php file throughout my site. I currently have the following:

header.php

<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="<?php if(isset($depth)){echo $depth;};?>css/style.css">

functions.php

function include_layout_template($template="", $depth="")
{
    global $depth;
    include(SITE_ROOT.DS.'public'.DS.'layouts'.DS.$template);
}

index.php

<?php include_layout_template('header.php', "../"); ?>

But $depth dissappears, I can’t even echo $depth; its just blank. How can I get the depth variable for use in header.php?

Answer by Sergey

You have to rename depth variable in function call

function include_layout_template($template="", $my_depth="")
{
   global $depth;
   //if need $depth = $mydepth

Answer by Starx

Your $depth variable is disappearing, because it is passed as parameter first but then defined to use the global parameter.

I will explain with an example:

$global = "../../"; //the variable outside
function include_layout_template($template="", $depth="")
{
    global $depth; //This will NEVER be the parameter passed to the function
    include(SITE_ROOT.DS.'public'.DS.'layouts'.DS.$template);
}
include_layout_template("header.php", "../");

To solve, simply modify the function parameter other than the depth itself.

function include_layout_template($template="", $cDepth="") { }
April 6, 2012

UTF-8 charset issues from MySQL in PHP

Question by Nick

this is really doing my nut…..

all relevant PHP Output scripts set headers (in this case only one file – the main php script):

header("Content-type: text/html; charset=utf-8");

HTML meta is set in head:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

all Mysql tables and related columns set to:

utf8_unicode_ci     Unicode (multilingual), case-insensitive

I have been writing a class to do some translation.. when the class writes to a file using fopen, fputs etc everything works great, the correct chars appear in my output files (Which are written as php arrays and saved to the filesystem as .php or .htm files. eval() brings back .htm files correctly, as does just including the .php files when I want to use them. All good.

Prob is when I am trying to create translation entries to my DB. My DB connection class has the following line added directly after the initial connection:

 mysql_query("SET NAMES utf8, character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'");

instead of seeing the correct chars, i get the usual crud you would expect using the wrong charset in the DB. Eg:

Propriétés

instead of:

propriétés

don’t even get me started on Russian, Japanese, etc chars! But then using UTF8 should not make any single language charset an issue…

What have I missed? I know its not the PHP as the site shows the correct chars from the included translation .php or .htm files, its only when I am dealing with the MySQL DB that I am having these issues. PHPMyAdmin shows the entries with the wrong chars, so I assume its happening when the PHP “writes” to MySQL. Have checked similar questions here on stack, but none of the answers (all of which were taken care of) give me any clues…

Also, anyone have thoughts on speed difference using include $filename vs eval(file_get_contents($filename)).

Answer by Sebastián Grignoli

You say that you are seeing “the usual crud you would expect using the wrong charset”. But that crud is in fact created by using utf8_encode() on an already UTF8 string, so chances are that you are not using the “wrong encoding” anywhere, but exceeding the times you are encoding into UTF8.

You may take a look into a library I made to fix that kind of problems:

http://stackoverflow.com/a/3521340/290221

Answer by Starx

There is a mysql_set_charset('utf8'); in mysql for that. Run the query at the beginning of another query.

July 12, 2010

How many 'includes' is too many as part of a common script startup sequence? Or is there no such thing?

Question by Hammerite

By “common script startup sequence”, what I mean is that in the majority of pages on my site, the first order of business is to consult 3 specific files (via include()), which centrally define constants, certain functions used in many scripts, and a class or two, as well as providing the database credentials. I don’t know if there’s a more standard term for such a setup.

What I want to know is whether it’s possible to have too many of these and make things slower as a result. I know that using include() has a certain amount of overhead because it’s another file to look for in the filesystem, parse, and execute. If there is such a thing as too many includes, I want to know whether I am anywhere near that point. N.B. Some of my pages include() still more scripts that they specifically, individually need (for example, a script that defines a function used by only a few pages), and I do not count these occasional extra includes, which are used reasonably sparingly anyway. I’m only worrying about the 3 includes that occur on the majority of pages and set everything up.

What are the 3 includes?

Two of them are outside of webroot. common.php defines a bunch of functions, classes and other things that do not vary between the development and production sites. config.php defines various constants and paths that are different in the development and production sites (which database to connect to, among other things). Of course, it’s desirable for this file in particular to be outside of webroot. config.php include()s common.php at the bottom.

The other one is inside webroot and contains a single line:

include [path to appropriate directory]/config.php

The directory differs between the development and production sites.

(Feel free to question the rationale behind setting up the includes this way, but I feel that this does provide a good, reliable system for preparing to execute each page, and my question is about whether it is bad to have that many includes as a baseline on each page.)

Answer by bisko

The best thing to do is use an accelerator of some kind, APC or eAccelerator or something like this to keep them cached in RAM. The reasons behind this are quite a few and on a busy site it means a lost.

For example a friend did an experiment on his website which has about 15k users a day and average page load time of 0.03s. He removed most of the includes which he used as templates – the average load time dropped to 0.01 secs. Then he put an accelerator – 0.002 secs per page. I hope those numbers convince you that includes must be kept as little as possible on busy sites if you don’t use an accelerator of some kind.

This is because of the high I/O which is needed to scan directories, find the files, open them, read them and so on.

So keep the includes to minimum. Study the most important parts of your site and optimize there by moving required parts to general includes and so on.

Answer by Starx

I dont believe the performance has anything do with no of includes, because think of a case where one included file contains 500 lines of codes and in another case you have 50 included files with just one line of code each.

July 5, 2010

Including JavaScript and CSS in a page (jQuery)

Question by Nimbuz

I recently came across the includeMany jQuery plugin to include external JavaScript and CSS files into a page. Although it was released in early 2009 there are NO references in blogs or elsewhere. I wonder if it’s usable? What is the experience using it?

Answer by Starx

You can include JavaScript and CSS using the example below. There is no need for any plugins.

To include JavaScript code, do this:

$.getScript("youpathtoscript.js",function() {
            //this script is loaded
});

To include CSS files:

$("<link/>", {
   rel: "stylesheet",
   type: "text/css",
   href: "styles/yourcss.css"
}).appendTo("head");
...

Please fill the form - I will response as fast as I can!