mschroeder 251 Bestower of Knowledge Team Colleague

I have used LiquidWeb and recommended to it many people for everything for shared, vps, dedicated, virtualization etc etc. In years of service I have never personally experienced a LiquidWeb outage.

If you check out WHT they have great reviews and used to be very active members of that forum.

Their support is top notch including 24/7 phone support. Pick up the phone, dial the number, talk to a real person in the states, get your problem solved. They go above and beyond for their customers and absolutely get what you pay for.

mschroeder 251 Bestower of Knowledge Team Colleague

Cache expiration time entirely depends upon what is being cached. Without a particular use case there isn't really a "standard".

mschroeder 251 Bestower of Knowledge Team Colleague

This is not caching. You're actually causing your script to do more work when it tries to serve from cache than when you're just generating the content dynamically.

The way caching should work, is when your script runs, it attempts to load a cache, via unique identifier (key, hash, filename, etc). When that cache request fails, because it is expired or it does not exist, then it proceeds to execute the code that will be saved into the cache, saves to the cache and displays what it generated.

This is hopefully just to give you an idea of what you might expect, if you want a more appropriate OOP solution, you'd probably want a Cache Interface that multiple cache adapters (file, db, mongo, memcache, etc) can implement so you have a consistent api. Perhaps even all tucked away behind a cache factory that handles creating the different cache instances based on a supplied adapter.

<?php

class Cache
{
	protected $_key;
	
	public function __construct( array $settings = array() )
	{
		//Do something with your settings
		//Set maximum lifetime?
		//Set directory path?
	}
	
	public function load( $key )
	{
		$this->_key = $key;
		
		if( $this->isValid( $key ) )
		{
			$cache = file_get_content('some/path/to/some/file.cache');
			return $cache
		}
		
		return false;
	}
	
	public function save( $cacheable )
	{
		//saves the generated content somewhere
		//maybe check for object and serialize automatically (setting?)
	}
	
	public function isValid( $key )
	{
		//Validate the cache exists and is not expired etc.
		//return true or false
	}
	
	public function expire( …
diafol commented: Nice +8
mschroeder 251 Bestower of Knowledge Team Colleague

I believe what you are looking for is autoloading, which php does have. http://php.net/manual/en/language.oop5.autoload.php

As far as the :: are you referring to the context of self:: static:: etc or are you referencing namepspaces as the use of :: in namespaces was dropped in lieu of \

mschroeder 251 Bestower of Knowledge Team Colleague

A tree structure is probably the wrong way to go about this. The data structure you describe would be more of a graph. Where each node can have 1:n connections to additional nodes. A tree structure is really best suite for parent-child kind of relationships.

http://en.wikipedia.org/wiki/Graph_(data_structure) has some general information on graph data structures and also provides some information on ways to represent your nodes in a graph as well as some common graph traversal algorithms.

Once you have solved your traversal across the graph you will be left with a resultant that can be represented as a doubly linked list (http://en.wikipedia.org/wiki/Doubly-linked_list) which will provide you with a bi directional set of nodes you iterate across. PHP's SPL actually has a data structure for doubly-linked lists already which is why I mention this.

mschroeder 251 Bestower of Knowledge Team Colleague

PHP is a server side language. It does not have access to the client machine. If you wanted to do something like this, you would need some kind of client based code (flash or java probably) which could possibly use php to drive some of the underlying functionality, chat, logging, authentication etc.

mschroeder 251 Bestower of Knowledge Team Colleague

Are you running the 64bit WampServer package?

If so, can you access http://localhost ?

mschroeder 251 Bestower of Knowledge Team Colleague
<?php

$db_host = "localhost";
$db_username = "root";
$db_pass = "";
$db_name = "el";

@mysql_connect("$db_host","$db_username","$db_pass") or die ("could not connect"); 
@mysql_select_db("$db_name") or die ("No database found");
echo"you are connected to the DB<br>";

$result = mysql_query('SELECT * FROM attendace_info_old');

//Will return a positive integer
$fieldCount = mysql_num_fields( $result );

//Access field names by index starting from 0, so we must subtract 1 from the fieldCount
$lastFieldName = mysql_field_name( $result, ($fieldCount - 1) );

echo $lastFieldName;
mschroeder 251 Bestower of Knowledge Team Colleague

There is little that can be avoided of mixing html with your php in this instance however, I think the alternative control structures make for a nicer read than having your block of html encased in a single echo statement.

If you want to remove your php even more from your html, HEREDOC and NOWDOC (php 5.3 +) make this very easy with a little sprintf/printf usage.

There really isn't a right or wrong in this case, except your original example, but that was corrected by jtreminio.

<?php for( $i = 0; $i <= 10; $i++ ): ?>
	<tr>
		<td>
			<input name='rate<?php echo $i; ?>' id='rate<?php echo $i; ?>' type='text' onkeyup='integeronly(this)' >
		</td>
		<td>
			<input name='qty<?php echo $i; ?>' id='qty<?php echo $i; ?>' type='text' onkeyup='integeronly(this)' >
		</td>
		<td>
			<input name='amt<?php echo $i; ?>' id='amt<?php echo $i; ?>' type='text' readonly='readonly'>
		</td>
	</tr>
<?php endfor; ?>

If you want to take the chance you can use the shorttag echo, but ymmv:

<?php for( $i = 0; $i <= 10; $i++ ): ?>
	<tr>
		<td>
			<input name='rate<?=$i?>' id='rate<?=$i?>' type='text' onkeyup='integeronly(this)' >
		</td>
		<td>
			<input name='qty<?=$i?>' id='qty<?=$i?>' type='text' onkeyup='integeronly(this)' >
		</td>
		<td>
			<input name='amt<?=$i?>' id='amt<?=$i?>' type='text' readonly='readonly'>
		</td>
	</tr>
<?php endfor; ?>

You could also use HEREDOC with the sprintf functions, *BUT* you must escape the '$' placeholder. This will work with php < 5.3.

<?php
$html = <<<HTML
<tr>
	<td>
		<input name='rate%1\$s' id='rate%1\$s' type='text' onkeyup='integeronly(this)' >
	</td>
	<td>
		<input name='qty%1\$s' id='qty%1\$s' type='text' onkeyup='integeronly(this)' >
	</td>
	<td>
		<input name='amt%1\$s' id='amt%1\$s' …
mschroeder 251 Bestower of Knowledge Team Colleague

If you are completely new to Git, there is a great step-by-step tutorial site that will actually walk you through some hands on exercises and teach you most of the fundamentals of using Git: http://gitimmersion.com/

qazplm114477 commented: Thanks for the link! +1
mschroeder 251 Bestower of Knowledge Team Colleague

Would second the use of GIT.
I have used CVS and SVN previously but GIT beat them both hands down.

It does take some getting used to though since you're not dependent on any central repository/server.

mschroeder 251 Bestower of Knowledge Team Colleague

I didn't even notice that when I posted before, not only was the bracket wrong, but the same function is declared twice in the class.

Without actually knowing how the code works there really isn't much anyone will be able to do to help you resolve the issue. You need to eliminate one of those functions, or combine them, but they seem to be doing two different things.

mschroeder 251 Bestower of Knowledge Team Colleague
<?php
$subjects = array(
	'abcd124',
	'abc1234',
	'passesTheTest',
	'fai1TheTest',
        'abc',
        '123',
);

$pattern = '/^[a-zA-Z]{4}/';

foreach( $subjects as $test ){
	if( preg_match( $pattern, $test ) > 0 ){
		echo 'pass'.PHP_EOL;
	} else {
		echo 'fail'.PHP_EOL;
	}
}
pass
fail
pass
fail
fail
fail
mschroeder 251 Bestower of Knowledge Team Colleague

While I don't understand your use case, and I think you're encrypting the url parameters for no value, you could do this with mod_rewrite.

However you would need some kind of indicator to tell it where to route the url params to.

e.g.
website.com/books/{encrypted} and your rewrite rules would rewrite this to website.com/books.php?enc={encrypted}

The encrypted text would be best represented by base64_encode( mcrypt_encrypt( http_build_query( $array ) ) );

Your script would then receive this string via the $_GET variable and you would need to decode it, unecrypt it, and then parse the query back into attribute value pairs.

Also if you choose this route be aware you will need to use a URI-safe base64_encode as + / and = are not uri safe.

mschroeder 251 Bestower of Knowledge Team Colleague

Just fix the following code:

class obs
 {
   function obsConfig()
   {
 
     $this->obsConfig['uri'] = 'http://backupserver.123-backup.com/obs/api/';
 {
   function obsConfig()
   {
     $result = $this->connect($this->obsConfig['uri'], $this->obsConfig['apiCall'], $command, 'POST');
   }
 }

with

class obs
 {
   function obsConfig()
   {
 
     $this->obsConfig['uri'] = 'http://backupserver.123-backup.com/obs/api/';
 }
   function obsConfig()
   {
     $result = $this->connect($this->obsConfig['uri'], $this->obsConfig['apiCall'], $command, 'POST');
   }
 }

and don't add a } at the end of the file like was posted before.

mschroeder 251 Bestower of Knowledge Team Colleague

What kmonroe posted may eliminate your $end error, but all that code does is add a } after the closing bracket of your function, which is NOT where the actual error exists.

If you look at the original code you posted on line 203, you will see you have a function definition in class obs that has two opening curly brackets instead of an opening and closing curly bracket.

mschroeder 251 Bestower of Knowledge Team Colleague

Make the column's data type blob.

mschroeder 251 Bestower of Knowledge Team Colleague

That error would imply you have a mismatched open/closing curly bracket somewhere in your code.

mschroeder 251 Bestower of Knowledge Team Colleague

What is the reasoning for encrypting/protecting what is in the url? Considering this is supplied/visible/modifiable by the user it should never be treated as trusted data and should always be filtered/validated before you use it in your application.

mschroeder 251 Bestower of Knowledge Team Colleague

Technically this is possible, in fact there are a vast amount of services that offer this kind of functionality. However, the complexity of creating something like this is outside of the scope of this forum.

If you want this kind of functionality I would suggest you look at some of the services that already offer this through an api. Some services I have used and worked with in the past include, SendGrid, Streamsend and MailChimp but there are many more.

mschroeder 251 Bestower of Knowledge Team Colleague

-phper

The problem I have with timestamps mostly has to do with the limited range they are available for, 1970 - 2038 approximately. If you were to try to store a date 30 years from today, say for a 30year mortgage, you will exhaust the 32bit integer timestamp.

Mysql's datetime and date data types do not suffer from this. It is also just as easy to do a range calculation with mysql's datetime columns.

e.g.

SELECT * FROM table WHERE table.`date` BETWEEN NOW() AND NOW() + INTERVAL 30 YEAR

Downside with that query would be the inability for mysql to cache its results because of the use of NOW(). However, if that is an issue it can be remedied by using the php DateTime class instead of the time() and date() functions, which does not suffer from the same range as the unix timestamp.

<?php
//Current DateTime
$now = new DateTime();
$start = $now->format( 'Y-m-d H:i:s' );

//add() is php 5.3.0 functionality
$now->add( new DateInterval('P30Y') );
//For php < 5.3.0
//$now->modify( '+30 year' );

$end = $now->format( 'Y-m-d H:i:s' );

$query = sprintf( 'SELECT * FROM table WHERE table.`date` BETWEEN "%s" AND "%s"', $start, $end );
echo $query; 
//SELECT * FROM table WHERE table.`date` BETWEEN "2011-02-22 20:20:52" AND "2041-02-22 20:20:52"
mschroeder 251 Bestower of Knowledge Team Colleague

Personally I prefer to store dates using the mysql date or datetime format, usually the later, but it is a personal preference.

You'll often see a unix timestamp in an int column, a mysql timestamp cplumn, and even sometimes a date stored as a string, which is the only one I would say is unacceptable and should be avoided.

Just however you choose to handle your dates, stick with it, don't mix and match date types throughout the application.

mschroeder 251 Bestower of Knowledge Team Colleague

You have basically finished the script, with the exception of two things.
You need to call the function, and your SQL statement should be looking for any delete_date values that are less than or equal to the current time. If you leave it as >= you will be deleting all articles that are set to expire in the future.

I'm not sure how your dates are stored in your database, but $current_date is unused in your function, and NOW() will only work if the delete_date column is a date/datetime/timestamp etc. (http://dev.mysql.com/doc/refman/5.0/en/datetime.html)

Also just a note, in files that are purely php, it is good practice to drop the closing ?>. This prevents any issues with whitespace after the closing tag.

<?php

function delete_expired() {
    $current_date = date("m.d.y"); 
    $sql = "DELETE FROM cms_table WHERE delete_date <= NOW()";
    $res = mysql_query($sql) or die(mysql_error());
}

delete_expired();
drewpark88 commented: Helped me a Bunch!! : ) +2
mschroeder 251 Bestower of Knowledge Team Colleague

Seeing the table structures would make this much easier to answer correctly.

Generally:
If you are updating purchase_order_detail.`component_item_id` then you need to update it to a value that already exists in the component_item table.

If you are updating component_item.`id` then having the FK constraint on purchase_order_detail.`component_item_id` set to ON UPDATE CASCADE would update the key in any table it was referenced.

mschroeder 251 Bestower of Knowledge Team Colleague

My initial guess after reading this, is that you are either not supplying a value for `component_item_id` (which can not be null) OR you are supplying a value which does not exist in your component_item table.

Can you post both the structure of your two tables, and also the query you are using.

mschroeder 251 Bestower of Knowledge Team Colleague

Instead of hard deleting them would it not be easier and more effective to just limit the display of them by the "delete_date" parameter?

So when displaying posts only display posts where delete_date < NOW()?

Then you have no time priority to physically remove the items from your database and could have a database "clean-up" routine that can be run manually whenever you are logged in, or maybe runs anytime a new post is made so you don't need a cron script etc to do it?

drewpark88 commented: Awesome! +2
mschroeder 251 Bestower of Knowledge Team Colleague

Whats the reasoning behind hard deleting the row in the first place?

mschroeder 251 Bestower of Knowledge Team Colleague

You need to read about Xpath if that is the route you want to take, it really isn't difficult but your Xpath expression up there is wrong, and it is not the one I posted previously.

Walk through the simple tutorials I posted earlier: http://www.w3schools.com/xpath/default.asp

mschroeder 251 Bestower of Knowledge Team Colleague

You can navigate to any node anywhere in an xml based (html) document with XPath. But, the path to get to that script node depends entirely on the rest of the document it is contained within.

For example if it was the first script tag in the head: /html/head/script[1] Once you have your selection narrowed down to that node you can easily parse the resulting content for those values specifically.

mschroeder 251 Bestower of Knowledge Team Colleague

In this example I load the html from the daniweb homepage and than query on ALL div's with id='stats', which should only be one. See the link below for some good tutorials on crash course xpath.

<?php
$html = file_get_contents('http://www.daniweb.com');

$dom = new DOMDocument('1.0', 'iso-8859-1');

//Suppress any warnings from invalid html markup
@$dom->loadHTML( $html );
$xpath = new DOMXPath( $dom );
$query = '//div[@id="stats"]';

$nodes = $xpath->query( $query );
foreach( $nodes as $node ){
	echo $node->nodeValue;
}

XPath: http://www.w3schools.com/xpath/default.asp
DomDocument: http://www.php.net/manual/en/class.domdocument.php
DomXpath: http://www.php.net/manual/en/class.domxpath.php

mschroeder 251 Bestower of Knowledge Team Colleague

You have to first get the contents of that page. Some options for this would be cURL, file_get_contents, sockets, fopen/fread/fclose, etc.

Once you have the content you have a few options for extracting that particular piece of information. You can try to use a regular expression with the preg functions to match on the tags around it. You can try loading it into simpleXML and using xpath to select the node from the document, drawback to this method is simpleXML does not like invalid documents (most html).

Or, my personal favorite use the php DOM object, set it to load HTML so it only throws warnings about invalid markup, suppress or trap the warnings so they're not displayed and then use xpath to grab just the nodes that contain the content you want.

Once you have your scraped data cache it so you don't need to make the request on every single page load and you'll have a pretty effective solution.

mschroeder 251 Bestower of Knowledge Team Colleague

You could use a honey pot. Essentially a form field that is hidden from display to the user and is purposely designed to be left empty. The thought is that when a bot comes along and spiders the form it will fill all the fields including the one supposed to be empty.

Lots of stuff has been written on their success rate.
http://nedbatchelder.com/text/stopbots.html
http://www.rustylime.com/show_article.php?id=338
http://haacked.com/archive/2007/09/11/honeypot-captcha.aspx
http://freshervisions.com/articles/an-alternative-to-captcha-honeypot-forms/
http://www.projecthoneypot.org/

mschroeder 251 Bestower of Knowledge Team Colleague

A quick count from my editor reveals 23 opening and 22 closing brackets. So you definitely got an issue there.

Beyond that I see a lot of other issues.

  1. include is not a function it is a language construct and does not need the parenthesis around the string.
  2. Line 22: $HTTP_POST_VARS has been deprecated since PHP 4.1.0 by $_POST
  3. Line 24: echo is not a function it is a language construct and does not need the parenthesis around the string.
  4. Line 27: end; is not a language construct or a function. Perhaps this should be exit, die or return?
  5. Line 57: Your foreach is iterating over the $name array and creating a local variable called $name
  6. ereg is deprecated as of PHP 5.3 and while it will continue to work refactoring to use preg functions is recommended
  7. Try to keep your function case correct. e.g. use die() instead of Die()
  8. Line 212: Watch having session_start so deep in your code as any output before that call will cause php to error
  9. $HTTP_SESSION_VARS is deprecated in lieu of $_SESSION
  10. Line 287: Use caution with php short tags (<? ?>) as they are not always enabled by default. In your usage you're already using the proper code to echo a variable in tags like <?php ?> If you intend to continue using the short tags use the short echo syntax: <?=$variable?>

A quick run through your code and those are things I noticed. Some are just constructive advice …

mschroeder 251 Bestower of Knowledge Team Colleague

Be careful with the getmxrr function, only since 5.3.0 has it been available on windows. If you know the environment you're writing the script for this won't be a problem, but if you're writing a script for others to deploy this is a limitation you will want to work around.

There is a good thread here: http://www.daniweb.com/forums/thread141944.html about this very topic. The solution could probably benefit from a little updating but its a solid concept.

mschroeder 251 Bestower of Knowledge Team Colleague

I've never seen an official naming convention either. jkon would have described the closest to what I'm familiar with.

If you are going to code to a standard I would suggest looking at the PEAR standards and than looking at their implementation in some larger projects.

PEAR: http://pear.php.net/manual/en/standards.php
Zend Framework: http://framework.zend.com/manual/en/coding-standard.coding-style.html
Symfony: http://trac.symfony-project.org/wiki/HowToContributeToSymfony#CodingStandards
Doctrine: http://www.doctrine-project.org/documentation/manual/1_0/nl/coding-standards

From what I've seen those big projects use variation of the PEAR standards.

mschroeder 251 Bestower of Knowledge Team Colleague

You could also used the list construct.
http://php.net/manual/en/function.list.php

mschroeder 251 Bestower of Knowledge Team Colleague

You could serve up an alternative image in its place via .htaccess but you can't force a page that displays your image to redirect to your website.

mschroeder 251 Bestower of Knowledge Team Colleague

If you're developing a web based application, than an architectural requirement is an internet connection. This really can't be avoided.

In the case of using lower-end connections a load balancing router with connections to two or more separate ISPs would be the best way to overcome the coincidental downtime. Most "business" grade carriers will have an SLA stating what their acceptable downtime is and what packet deliverability to expect. In most cases I'd wager you'll probably deal with power outages more frequently than internet outages. In which case you'll be without power anyways.

Personally if I was going to architecture the environment, I would have the database server in a remote data center. These facilities are designed with redundancy in mind to prevent power outages, hardware failure etc. If you're looking for additional redundancy than having your database replicated over several machines on a private lan in the data center would give you just that. Or if you're very worried you'd have it replicate to additional servers in multiple data centers.

So you already take precautions and have a plan for scaling if it would be necessary.
Internally the stores would deploy an application server with a web interface that was served locally to the point of sale terminals, and isolated from the external world. I particularly like the VPN access for remote connections here as smantscheff already suggested.

This internal application server would have its own database that would power the interface or the …

mschroeder 251 Bestower of Knowledge Team Colleague

If you do not use referential constraints with InnoDB than MySQL with NOT tell you it can't delete a record because of a foreign key constraint. Your checks for consistency in data will need to be performed in your code which opens yourself up for lots of other issues and additional checks that would not need to be performed with an understanding of how the constraints ON UPDATE and ON DELETE work.

Up until MySQL 5.5 MyISAM was the default table engine. This engine has no support for transactions or foreign keys even if you can use the syntax. Since MySQL 5.5 InnoDB is now the standard for table type, which it should be. Transactions and Foreign Keys are invaluable tools in database design especially when you get into more complex data structures.

The tool used to edit data is irrelevant in relation to foreign key constraints, navicat, heidi and even CLI are just accessors for the data and it's rules.

Learning SQL from the command line is invaluable and is the absolute go to for all of the reasons smantscheff pointed out. However, when working with teams of people and/or people who do not have SQL knowledge visual diagrams of your data structure and the relationships that exist within the data are key. Workbench happens to be the best tool I've see for this purpose. Workbench does not replace the understanding of sql, how to read and write it, it's datatypes, structure, optimizations etc. It is …

mschroeder 251 Bestower of Knowledge Team Colleague

Foreign keys are only relevant when the database tables are InnoDB. MyISAM does not support foreign key relationships in any way.

If you are using InnoDB you absolutely should be using the FK constraints for ON UPDATE and ON DELETE. These allow you to enforce your business rules on your data structure without having to implement the checks in your code.

e.g.
If you were to delete a cigar record, any table that contained additional information and referenced the cigar table primary key you could have those tables setup to cascade the delete, and remove the record in any linked table.

For modeling your database I highly suggest checking out MySQL Workbench (http://wb.mysql.com/) you can design the entire database in a graphical manner including the foreign key relationships etc and you can than export the sql for creating the database.

Also I would suggest adopting a solid set of naming conventions for your database. It will really make your life easier in the long run when everything follows the same conventions. Personally I use a set of conventions that are a slightly modified version of http://weblogs.asp.net/jamauss/pages/DatabaseNamingConventions.aspx

mschroeder 251 Bestower of Knowledge Team Colleague

It looks like only POST values get sent to php://input.
I reworked the function so it gets it's values from the $_SERVER variable.

<?php
function getRealGet()
{
	$pairs = explode( '&', $_SERVER['QUERY_STRING'] );
	$vars = array();
	foreach ($pairs as $pair) {
		$nv = explode("=", $pair);
		$name = urldecode($nv[0]);
		$value = urldecode($nv[1]);
		$vars[$name] = $value;
	}
	return $vars;
}

var_dump( getRealGet() );
OmniX commented: nice code example +4
mschroeder 251 Bestower of Knowledge Team Colleague

My experience is the same as pritaeas.

mschroeder 251 Bestower of Knowledge Team Colleague

Because ++$a and $a++ do two different things.

Just because you don't use them doesn't mean they aren't used.

A quick grep over the Zend Framework for example yields 46 files that use the ++$a syntax.

An interview would be used to determine your understanding of PHP as a language. When you start looking at specific technologies, e.g. PayPal, Database Connections, etc. these things will all vary greatly project to project and company to company.

This is why frameworks in large development environments are so common because a company worried about quality is not going to let you run free and just hack together code however you feel like it that day. A company that develops using Zend/Symfony/Cake/Doctrine for example would interview you on your Zend/Symfony/Cake/Doctrine Knowledge because it is documented and easy to establish a baseline for proficiency and understanding of the framework as well as PHP.

Figure even if the company has their own framework of sorts that they build all of their applications on. Anyone outside of the company would have a slim chance of being familiar with it. So they wouldn't be looking for your knowledge of XYZ framework that has been developed in house, they're looking for your understanding of core php and how easy it will be to familiarize you with their environment and get you up to speed with their standards.

mschroeder 251 Bestower of Knowledge Team Colleague

You can extrapolate from the function posted here: http://www.php.net/manual/en/language.variables.external.php#94607

mschroeder 251 Bestower of Knowledge Team Colleague

http://us3.php.net/variables.external

Explains why those periods are converted to underscores.
Through the comments there are also other characters that are mentioned that appear to be converted as well.

OmniX commented: useful link, thanks. +4
mschroeder 251 Bestower of Knowledge Team Colleague

You are redeclaring your variables inside your loops.
If you're looping over $result and than within that loop are setting $result to another value it will screw up the loop.

mschroeder 251 Bestower of Knowledge Team Colleague

Aaron,

The concept I was illustrating is very basic in theory but very powerful in implementation.

Essentially you use variables in the url to control what is generated by the page. So in your case, a url might be something like mydomain.com/index.php?u={user_id}&y={year}

When a user would access that page it would validate on the $_GET to make sure they entered a valid user and then it would use the value of $_GET to find any awards for the year.

mschroeder 251 Bestower of Knowledge Team Colleague

This would be the absolute wrong way to go about this.
You would be left with multiple copies of outdated code as soon as your updated your template to resolve any bugs/security holes etc.

I'm not sure what you're pages will be displaying, I'm going to assume its for a profile-like system.

In which case you should create a single point of entry, index.php (or any file) and use a variable in the url to switch between users.

e.g.
mysite.com/person/?u=bob (assuming index.php)
mysite.com/person/bob (using .htaccess & mod_rewrite)
mysite.com/person/profile.php?u=1 (non-index.php access)

This way as you uncover security issues, bugs etc. and you will. You can modify the code in one place. Also makes it easier to roll out updates or new features etc.

<?php

if( !isset($_GET['u']) ){
  echo 'Must specify a user';
  exit;
}

$user = $_GET['u'];

//Do some kind of validation/filtering on the user variable
if ( !is_valid($user) ){
   echo 'Invalid user!';
   exit;
}

//Compile down all information from user
//Do some SQL queries, load images, etc.

//Display the output to the user
echo $content;

**NOTE: This is NOT functional/working code. Just illustrates the basic concept of how this would work.

mschroeder 251 Bestower of Knowledge Team Colleague

Post what you have tried so far, even if it is not working.

mschroeder 251 Bestower of Knowledge Team Colleague

I don't think there is really a best practice for handling variables. It really depends on the scope requirements of the variables.

If you prefer to work with many individual variables than continue to use $var1, $var2, etc etc.
If you don't like having so many loose variables, you could create a single array (single or multiple dimensions) that contains all the values.

e.g.

<?php

$variable = array(
  'page' => array(
    'title' => 'Page Title',
    'width' => 960,
  ),
  'form' => array(
    'field1' => 'value',
    'field2' => 37,
    'field3' => true,
  ),
);

If you use the array you can access everything down using: echo $variable['page']['title']; You also could slug all the variables into an object if you prefer the object notation of object->variable;

$obj = new stdClass();
$obj->page = new stdClass();
$obj->page->title = 'Page Title';
$obj->page->width = 960;

Personally I don't see much value in using objects as just empty stores like that.

Beyond the way you use the variables, you have to consider persistence. $var = 4; is only available within its local scope and must be passed into functions/objects etc. This is also only persisted for the current request.

Sessions allow you to persist volatile data over multiple requests while the use maintains their session. $_SESSION['var'] = 4; => index.php => go.php => xyz.php echo $_SESSION['var']; //4 Sessions are also global and can be accessed anywhere at anytime. But if the user loses their association with the session or closes the browser …

fuston05 commented: Very helpful, and knowledgable! +2