mschroeder 251 Bestower of Knowledge Team Colleague
<?php

<form action="ScoreCardAlpha.php" method="post">

A: <input type="text" name="$X" />

B: <input type="text" name="$Z" />

C: <input type="text" name="$W" />

// read input data on $W , $X or $Z has http// if so save after //

if(!filter_has_var(INPUT_post, "$X"))
 {
// if true
	**** deleate all char upto and including // then post to "$X"  ****
 echo("Input has been adapted and saved");
 }
else
 {
// if false
	**** post to "$X" ****
 echo("Input did not need adapting and has been saved");
 }

<input type="submit" />
?>

Maybe I am missing something, but I don't see how the code you provided can even execute. You should get a parse error as soon as it gets to the "<" in <form action="ScoreCardAlpha.php" method="post">

mschroeder 251 Bestower of Knowledge Team Colleague

For simple projects IDE's aren't going to make your life any easier, but when you have thousands of files, classes, and functions in a project that you need to be able to easily and quickly reference an IDE makes worlds of difference in my opinion.

mschroeder 251 Bestower of Knowledge Team Colleague

the printf based functions essentially cast values to a particular type and work with them in their respective ways. They also let you control things like precision, padding, etc etc. Look at the link i posted above, it has a lot of examples of what can be done with them.

They're really not the best way to prevent sql injection though. Prepared statements in my opinion are the best way to avoid sql injection, combined with the concept of "Filter Input, Escape Output"

mschroeder 251 Bestower of Knowledge Team Colleague

it is used in context with sprintf and printf etc? http://php.net/manual/en/function.sprintf.php

mschroeder 251 Bestower of Knowledge Team Colleague

There are several places the character set needs to be accounted for:

  1. Database Collation & Charset
  2. Table Collation & Charset
  3. Charset of the database connection

From within php:

Also if you are displaying the content the proper meta content-type header needs set in your html:

<meta http-equiv="content-type" content="text/html; charset=UTF-8">

and you should also be pushing this to the user via php's header() function:

header('Content-Type: text/html; charset=UTF-8');

The last two are really only for displaying in a browser properly. I believe your issue relates to the mysql connection charset. Hope this helps.

mschroeder 251 Bestower of Knowledge Team Colleague

What is the data type of your t_stamp column? I assume it is TIMESTAMP?

mschroeder 251 Bestower of Knowledge Team Colleague

You want to use the $storage->moveMessage( id, folder) method.
This site illustrates it a little more in detail: http://www.devcha.com/2010/06/how-to-removemove-messages-using-zend.html

The comments at the bottom of the Zend_Mail documentation also elaborate on this: http://framework.zend.com/manual/en/zend.mail.read.html

Automatically routing an email from a user to a particular folder would require some kind of intermediate logic that would look at all the emails and move them according to some kind of rule. Using a database or some kind of storage would make this possible.

mschroeder 251 Bestower of Knowledge Team Colleague
mschroeder 251 Bestower of Knowledge Team Colleague

Depends on the mysql extension you are using in php. mysql_affected_rows(), mysqli->affected_rows()

mschroeder 251 Bestower of Knowledge Team Colleague

just add another condition to the query then.

UPDATE table SET column = 'finish' WHERE STR_TO_DATE( date, '%m/%d/%Y' )= CUR_DATE() AND column = 'approve'
aizel commented: nicely done +1
mschroeder 251 Bestower of Knowledge Team Colleague

Is the date still stored as a string or is using a DATE column type in mysql?

UPDATE table SET column = 'finish' WHERE STR_TO_DATE( date, '%m/%d/%Y' )= CUR_DATE()

Something like that would probably work for you, assuming your structure is similar to what it was previously.

mschroeder 251 Bestower of Knowledge Team Colleague

If I follow correctly, when the user selects a month from the drop down, a two digit representation of the month is passed to the script. 01, 02, 03, etc. and you wish to then pull anything departing in that month.

You can do this relatively easily in SQL using something like this:

SELECT * FROM table WHERE MONTH( STR_TO_DATE(departure, '%m/%d/%Y') ) = 10

Where 10 is the integer value of the month supplied but the form. Beware that this is going to pull anything with month = 10 for ANY year.

***I assume you're departure column is stored as a string and is not using the DATE column type. Since it is not a supported MySQL date representation.

mschroeder 251 Bestower of Knowledge Team Colleague

You have another option if you want to still use heredoc:

<?php
$author = "Anon";
echo 
$str = <<<_END
First Lines
Second Line.
Third Line.
- Written by $author.
_END;

echo nl2br($str);
?>

nl2br inserts <br /> tags before any new line characters in the string.

mschroeder 251 Bestower of Knowledge Team Colleague

Thats because newline characters are not the same as <br />. They are also not displayed on the output of the browser.

If you view the source of that output you will see that the text is actually on multiple lines.

mschroeder 251 Bestower of Knowledge Team Colleague

Are you trying to connect to a third party API using curl, e.g. Flickr, or are you trying to create an API for your application that other people will be able to connect to and utilize your application?

mschroeder 251 Bestower of Knowledge Team Colleague

What aspect of that is not working for you? That code works fine for me.

mschroeder 251 Bestower of Knowledge Team Colleague

The solution was provided in my previous post

instead of == 21 it should be == '21'

There is no value to me just giving you the solution and you just copying and pasting it into your code. By providing you the information I did, you can attempt to learn why you're having a problem and how to address it in the future.

You're still going to have a problems with the additional code you posted too:

else if ($pg=="21;n='.$get_numbers.'") { echo 'Numbers...'; }
else if ($pg=="21;l='.$get_letters.'") { echo 'Letters...'; }

$pg=="21;n='.$get_numbers.'" and pg=="21;l='.$get_letters.'" are not going to match "21;n=0" or "21;l=0". You have mixed concatenation, single quotes and double quotes together. Those conditions are going to try to match on the string "21;n='.0.'" which is not being passed in your url.

else if ($pg=="21;n='.$get_numbers.'") { echo 'Numbers...'; }

should be revised to

else if ($pg=="21;n=$get_numbers") { echo 'Numbers...'; }

In double quoted strings php will parse variables. If you use single quotes you need to concatenate your variable. e.g. else if ($pg=='21;n='.$get_numbers) { echo 'Numbers...'; } Both of these statements will yield the same result and should both work correctly.

mschroeder 251 Bestower of Knowledge Team Colleague

PHP is a loosely typed language.
$pg is always a string result from the url e.g. '21', '21;n=0', '21;l=0'

When you do a comparison against an integer value if($pg == 21) { echo 'Regular...';} $pg is cast to an integer value. So var_dump( (int) '21;n=0' ); will yield int 21.

Since you're doing a string comparison across the whole thing, instead of == 21 it should be == '21' OR you should split those up into individual variables and test the parameters individually like I was trying to suggest before...

mschroeder 251 Bestower of Knowledge Team Colleague

In your code $get_numbers and $get_letters are variables.
In the urls in the link you are building you are using the value of those variables in the url.

So, <a href="index.php?page=21;l='.$get_letters.'" would become <a href="index.php?page=21;l=1" in your html. If the value of $get_letters was 1. This would mean the value of $_GET would be '21;l=1' sans the quotes.

In your urls you are also concatenating the variables together with a semi-colon. If these are two different values they need to be passed with an ampersand. <a href="index.php?page=21&l='.$get_letters.'" In your code you can then test for these as separate values. $_GET and $_GET.

$page = (int) $_GET['page'];
$letter = $_GET['l'];
$numbers = $_GET['n'];
mschroeder 251 Bestower of Knowledge Team Colleague

I've only come across a few examples of this:

http://php-security.net/archives/3-X.509-PKI-login-with-PHP-and-Apache.html
Is one I bookmarked a while ago.

mschroeder 251 Bestower of Knowledge Team Colleague

Only place I have seen this kind of functionality is with Flash, Silverlight and Gears uploaders.

mschroeder 251 Bestower of Knowledge Team Colleague

When I view your site, I see two different content-type meta tags:

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  <title>Морайра Инвест - недвижимость в испании - Buy, Sell, Resa</title>
  <meta http-equiv="content-type" content="text/html;charset=utf-8">
  <meta http-equiv="content-language" content="ru">
  ...
</head>

You should only have 1 and you probably want to be using UTF-8 as this should contain the character sets you want to be working with.

http://www.phpwact.org/php/i18n/charsets
http://www.phpwact.org/php/i18n/utf-8
The first covers a great overview of the implications of characters sets in php and the second has a very detailed breakdown of many string functions and their risk level in terms of UTF-8 corruption.

This boils down to your outputted html needs to have a proper content-type meta tag and your application needs to send a proper content-type header and they should match.

Beyond what the articles mentions, your database connection needs to be set to the proper character set.
-MySQL Extension
http://www.php.net/manual/en/function.mysql-set-charset.php

-MySQLi Extension
http://php.net/manual/en/mysqli.set-charset.php

-PDO Extension
http://www.galengrover.com/web-development/setting-the-connection-charset-with-php-mysql/

Within your database you also need to set the proper character set and collation
http://dev.mysql.com/doc/refman/5.0/en/charset-database.html
Your tables will also have similar settings.

Hopefully this helps and gets you pointed in the right direction. Iñtërnâtiônàlizætiøn in php can be a real pain.

mschroeder 251 Bestower of Knowledge Team Colleague

-nevvermind
Singletons are almost always an indication of poor code design. They're extremely difficult to mock and test. Essentially the problem with singletons is you place the responsibility for determining the objects life cycle in the wrong place.

More beneficial to have a factory class that handles initialization and returns a single instance of a particular class if necessary.

-kroche
Looking at your code it looks like your domain objects are all extending the database class to provide database access. This will also become troublesome if you ever have to test your code independently. Something to consider would be to make your database class external and keep your domain objects isolated. If a domain object needs database object, then pass the database instance into the domain object when created. This opens the doors for utilizing the factory pattern and/or dependency injection to create domain objects and handle initializing any dependencies a domain object may have.

mschroeder 251 Bestower of Knowledge Team Colleague

You need an extension that is built for 5.3 and VC6 and is thread safe version

http://downloads.php.net/pierre/php_printer-svn20100319-5.3-vc6-x86.zip

mschroeder 251 Bestower of Knowledge Team Colleague

Check out something like plupload http://www.plupload.com/.
It supports chunking on multiple different types of uploaders which won't make the upload go any faster, but effectively the user sees progress and the script isn't running for the entire 10mb upload, only long enough to process a chunk of n size.

My experiences with it thus far have been mostly positive, its documentation is a little lacking though.

mschroeder 251 Bestower of Knowledge Team Colleague

It is nice to see someone who is actually doing some reading and looking on their own.

I read up on the "array_map()", can you elaborate a little on that please? Not quite grasping it yet.

array_map, simply executes the trim() function on every item in an array. In my example its running trim() on every item returned by the explode statement. This just cleans up any extra whitespace left around those strings.

As for the code you posted, it looks like a good start but, it appears like it is mixing the logic for listing events as well as deleting them.

When you list them, you just need to get the content of the file, explode the contents and iterate over the returned results. In the link you will also need something identify which event it is you want to delete from the file. Looking back I see each event is prefixed with "###-". So I will use that to break down the file in a special way.

function getEvents( $path )
{
	$events = array();
	
	//Make sure the file exists and we can read it
	if( is_readable( $path ) {
		//Read entire file in.
		$content = file_get_contents( $path );
		//Explode by =>
		$dirtyEvents = explode( '=>', $content );
		//Iterate over each $dirtyEvent and look for its identifier
		//Split it into a key and value pair that is unique to the event.
		foreach( $dirtyEvents as $event ){
			//Get the position of the first dash
			$dashPos = …
mschroeder 251 Bestower of Knowledge Team Colleague

Assuming everything is on a single line.

My initial thought on this, is to change the format of the file you're creating so each event is on its own line. This would eliminate the need for a separation character, new line, new event. This would also make it possible to work with the entire file line by line instead of having to load the entire file into memory.

With the current format, the process for parsing this would be to load the entire file (1 line assumed) into memory (file_get_contents() etc.) and then explode that line with the '=> ' separator. Unset the event item to delete. Put the string back together and write it back to the file.

$line = file_get_contents( 'somefile.txt' );

//Explode the line and trim each of the items in the array.
$events = array_map('trim', explode( '=> ', $line ));

//Delete the event from the events array
unset( $events[0] );

//Put the remaining lines back together into one line.
$line = implode( '=> ', $events );

//Write it back to the file
...

This should work well for small files, but if your files would ever grow to a large size, this will become very inefficient as it has to load the entire file into memory. A few hundred lines, no big deal, a few hundred thousand lines and you'll quickly see performance hits.

This isn't tested, but you should get the idea and be able to adapt it as needed.

mschroeder 251 Bestower of Knowledge Team Colleague

Can you post a sample of the produced text files as well? That should be enough to get an understanding of how to process them out.

mschroeder 251 Bestower of Knowledge Team Colleague

Can you post an example of the format of the text files you're trying to work with?

mschroeder 251 Bestower of Knowledge Team Colleague

PayPal provides a variety of SDK's just for this specific purpose
https://www.x.com/community/ppx/sdks

I see no reason to use something that doesn't appear to have been updated since 2005.

-OP

If you are requiring all of your users to pay to have access then this is easy. If they are not logged in, send them to a login page. If they don't have an account have a register page which accepts their account information email/password as well as payment information. Process the payment info. If it succeeds create the user in the database and log the transaction somewhere. DO NOT store the CC #s. This is what using a payment gateway prevents. Once the user is created, redirect them to the login page or automatically put them through the login process with their account information.

If you need to go beyond the paid sees everything and guest see nothing model then you will need to implement some form of roles/permission system. Where users in a certain role, 'guest', 'registered', 'admin', etc. have certain permissions. When accessing a page the system would need to identify the user (session) and make some determination whether they are allowed to view that page.

This is overly simplified, but should point you in the right direction.

mschroeder 251 Bestower of Knowledge Team Colleague

What was the reasoning for it to be designed as a singleton?

mschroeder 251 Bestower of Knowledge Team Colleague

I see no reference to him using PHP2 in this thread anywhere...I see lots of references to his files being called PHP1 PHP2 etc though. Please enlighten me to where I'm missing this piece information.

mschroeder 251 Bestower of Knowledge Team Colleague

Glad I could be of help.

mschroeder 251 Bestower of Knowledge Team Colleague

?! I didnt flag your post as bad! I'm sorry but I really didnt! I pressed Post Reply then my browser said I wasn't connected to the internet =.=, I really didnt flag your post but if I did for whatever reason I didnt mean it!

I just did a simple

<?php
session_start();
$_SESSION['greeting'] = "Hello world";
echo $_SESSION['greeting'];
echo '<a href="PHP2.php">Next</a>';
<?

and in PHP2

<?php
session_start();
echo $_SESSION['greeting'];
<?

and that didnt even work...

Of course this isn't going to work...your php ending tags are wrong... ?> NOT <?
If you have error_reporting enabled and ran that code exactly as you posted it, you should be getting a parse error.

<?php
//code
?>
<?php
session_start();
$_SESSION['greeting'] = "Hello world";
echo $_SESSION['greeting'];
echo '<a href="PHP2.php">Next</a>';
?>
<?php
session_start();
echo $_SESSION['greeting'];
?>

-richieking
$HTTP_SESSION_VAR was deprecated in php 4.1.0 by $_SESSION.

mschroeder 251 Bestower of Knowledge Team Colleague

I wouldn't put to much focus on it, you'd have to be echoing millions of session variables for it to even begin to make an impact. Spend the time optimizing the more bottleneck prone areas of your code, you'll see a much bigger return.

mschroeder 251 Bestower of Knowledge Team Colleague

There is a fatal flaw to loading the entire file into an array like that. It loads the entire file into memory. If the file only has 30 lines no big deal. If the file as 30000 lines then it will be an issue.

Here is what I recommend instead (PHP 5.1.2 > only):

<?php

/*
 * Create a new SplFileObject representation of the file
 * Open it for reading and writing and place the pointer at the beginning of the file
 * @see fopen for additional modes
 */
$file = new SplFileObject('database.txt', 'a+');

/*
 * Set a bitmask of the flags to apply - Only relates to reading from file
 * In this case SplFileObject::DROP_NEW_LINE to remove new line charachters
 * and SplFileObject::SKIP_EMPTY to remove empty lines
 */
$file->setFlags(7);

/*
 * Lock the file so no other user can interfere with reading and writing while we work with it
 */
$file->flock(LOCK_EX);

/*
 * Create a SplTempFileObject
 * 0 indicates not to use memory to store the temp file.
 * This is probably slower than using memory, but for a large file it will be much more effective
 * than loading the entire file into memory
 * @see http://www.php.net/manual/en/spltempfileobject.construct.php for more details
 */
$temp = new SplTempFileObject(0);

/*
 * Lock the temp file just in case
 */
$temp->flock(LOCK_EX);

/*
 * The line we're hoping to match and remove
 * DO NOT include any line ending charachters these have been stripped already
 */
$delete = 'Some line to …
mschroeder 251 Bestower of Knowledge Team Colleague

Just an FYI, array_filter will also do just this when not supplied with a callback function. It will remove anything that when compared as a boolean evaluates to false. More examples in the menu.

<?php

$array = array(
	'1',
	'',
	'Full, Gen. 3',
	'',
	'TMSWK2D',
	'9',
	'Poor write quality',
	'2',
	'',
	'Full, Gen. 1',
	'',
	'TMSWK2C',
	'',
	'Read Only, Clean Tape',
);

var_dump($array);
$array = array_filter($array);
var_dump($array);
array
  0 => string '1' (length=1)
  1 => string '' (length=0)
  2 => string 'Full, Gen. 3' (length=12)
  3 => string '' (length=0)
  4 => string 'TMSWK2D' (length=7)
  5 => string '9' (length=1)
  6 => string 'Poor write quality' (length=18)
  7 => string '2' (length=1)
  8 => string '' (length=0)
  9 => string 'Full, Gen. 1' (length=12)
  10 => string '' (length=0)
  11 => string 'TMSWK2C' (length=7)
  12 => string '' (length=0)
  13 => string 'Read Only, Clean Tape' (length=21)
array
  0 => string '1' (length=1)
  2 => string 'Full, Gen. 3' (length=12)
  4 => string 'TMSWK2D' (length=7)
  5 => string '9' (length=1)
  6 => string 'Poor write quality' (length=18)
  7 => string '2' (length=1)
  9 => string 'Full, Gen. 1' (length=12)
  11 => string 'TMSWK2C' (length=7)
  13 => string 'Read Only, Clean Tape' (length=21)
mschroeder 251 Bestower of Knowledge Team Colleague

[OFFTOPIC]

My apologies for taking this off topic for a second. But this comment struck my interest.

TheSecOrg
Also try not to use session variable raw like..

echo $_SESSION['username']

dont keep to that.

always put it in a standard variable. eg..

if($_POST){
$_SESSION['name']=$_POST['name'];
//dont forget to trim,strip_tags, etc.. clean always inputs that you receives even if it come from heaven. angels sometimes get lazy. trust no inputs.
}
// refer to session variable and put it in normal variable for use.
$foo=$_SESSION['name'];
echo $foo;

you get the idea?

:) Explore.

-evstevemd
-richieking

I was reading through this thread and saw this comment and having never heard this before had to do some research. Richieking is absolutely right in terms of setting a global to a local variable being faster to echo out. But, it is only nominally faster and I saw consistent results up over 100,000 echos.

I benchmarked this at 100 cycles of echoing a variable 1000 times:

First result is echoing the $_SESSION value directly.
Second result is echoing $var after $var = $_SESSION.
Third result was setting it to an array item instead of a variable. (Just out of curiosity)

Running Benchmark: Speed Between Accessing A $_SESSION Variable Or Local Rep Of A Session Variable
======================================================================
Running Test: test_Iterate_Session
	Cycles: 	 100
	Mean: 		 0.0004818988 secs.
	Median: 	 0.0004801750 secs.
	Mode: 		 0.0005009174 secs.
	Range: 		 0.0001130104 secs.
	Min: 		 0.0004498959 secs.
	Max: 		 0.0005629063 secs.
======================================================================
Running Test: test_Iterate_Local_Session_Rep
	Cycles: 	 100
	Mean: 		 0.0003332329 secs.
	Median: 	 0.0003280640 secs.
	Mode: …
mschroeder 251 Bestower of Knowledge Team Colleague

Its a best practice to declare constants in uppercase, but there is no requirement to do it this way. Why introduce a dependency on something so trivial.

The only place that works is in a double quoted string. It doesn't work anywhere else. It doesn't save any considerable code to do it this way.

<?php
ini_set('display_errors',1);
error_reporting(E_ALL|E_STRICT);

//Comment me out to see notices
//Define COMMENT as 'NOT' so when $row[COMMENT] is called...
//We get the value of $row['NOT'] instead...
define('COMMENT', 'NOT');

$row = array(
	'COMMENT' => 'comment',
	'NOT' => 'not comment',
);

echo "$row[COMMENT]".PHP_EOL; //comment
echo "{$row[COMMENT]}".PHP_EOL; //not comment
echo $row[COMMENT].PHP_EOL; //not comment
echo sprintf('%s', $row[COMMENT]).PHP_EOL; //not comment

echo $row["COMMENT"].PHP_EOL; //comment (swapped quotes from around string to array key)
echo "{$row['COMMENT']}".PHP_EOL; //comment
echo $row['COMMENT'].PHP_EOL; //comment (duplicate of 1)
echo sprintf('%s', $row['COMMENT']).PHP_EOL; //comment
comment
not comment
not comment
not comment
comment
comment
comment
comment
mschroeder 251 Bestower of Knowledge Team Colleague

Why this???

All this concatenations ???

from line 6-14. Writing code like this means you want a bug.

you could do all that in a very simple like this.

$message ="New Contact Information

$row[FIRST]
$row[LAST]

$row[AGE]
$row[GENDER]

$row[EMAIL]
Cell $row[CELL]
 Home $row[HOME]

$row[CITY]

$row[LOCATION]
$row[TIMEBLOCK]

$row[PREFCTCT] 
$row[COMMENT]
Fitness Goals: 
Lose weight: $row[LOSE] 
Gain muscle: $row[GAIN]
Lean and tone: $row[LEAN]
Injury Rehabilitation: $row[REHAB]
Sports specific training: $row[SPORTS]
Overall fitness: $row[OVERALL]
$row[COMMENT]
";

This works and its easier. Arrays from $_POST,$_GET, and from Mysql_fetch_array can work like this without the '' and "".

By removing the quotes from those associative array keys EVERY single one of those will throw a Notice. You simply don't notice this because you either have error reporting turned off or suppressed. Bad practice to get into.

http://php.net/manual/en/language.types.array.php

Scroll down to the section called "Why is $foo[bar] wrong?"

mschroeder 251 Bestower of Knowledge Team Colleague

eval should be avoided at all costs. Especially if you're passing user supplied information into it.

I saw a really good implementation talking about creating a mathematical parser that could take an equation as a string and parse it out to its components and then evaluate it using order of operations, but for the life of me, I can't find at the moment.

mschroeder 251 Bestower of Knowledge Team Colleague

you can also do this simple on php.

this is very simple function. ha ha

<?php
funtion foo(){
    // first receive the post variable from the form

$bar=$_POST['num'] ;

$numberDetails= split ('+',$bar); // split and take details
for ($c=0;$c<count($numberDetails);$c++){
// basic run through

$hoo+=$numberDetails[$c];



}
echo "The sum is ".$hoo; // echo answer. 

}
?>

ha ha have fun
all in less than 2 minutes
Explore :)

Again, split is depreciated as of 5.3. If you're developing on ANY version of php at this point you should avoid it, in favor of other options which already exist.

Just an FYI its bad form to have a function call in the second portion of a for loop. for ($c=0;$c<count($numberDetails);$c++) will call count( array ) on every iteration of your loop. 3 array keys no big deal. Thousands it will add up. for ($c=0,$count = count($numberDetails); $c < $count; $c++){ http://php.net/manual/en/control-structures.for.php

Another solution to the problem.

<?php
$string = '2 + 2';
echo array_sum( explode('+', str_replace( ' ', '', trim( $string ) ) ) );
mschroeder 251 Bestower of Knowledge Team Colleague

Line 27:

list($file,$extension) = explode('.', basename($path));

explode is not returning 2 array pieces. So that means $path does not contain what you think it does from somewhere higher up. My guess is $path = $uriparts['path']; is not returning a filename but rather a path.

$fileParts = explode('.', $basename($path));
$file = isset($fileParts[0]) ? $fileParts[0] : '';
$extension = isset($fileParts[1]) ? $fileParts[1] : '';

Line 35:

list($key,$val) = preg_split('/=/',$b);

Again preg_split is not returning an array with two items.
It looks like your trying to parse the query string into variable = value pieces.
Look at parse_str in the manual, it does just this.
Also when splitting by something as simple as an '=' avoid regular expressions they're very slow compared to straight string manipulations.

$query = isset( $uriparts['query'] ) ? $uriparts['query'] : '';
  $anchor = isset( $uriparts['anchor'] ) ? $uriparts['anchor'] : '';
  if ($a = explode('&',$query)){
    foreach ($a as $b) {
	  list($key,$val) = preg_split('/=/',$b);
	  switch ($key) {

TO

$query = isset( $uriparts['query'] ) ? $uriparts['query'] : '';
$anchor = isset( $uriparts['anchor'] ) ? $uriparts['anchor'] : '';
$a = array();
//parse the string and put into the array $a
parse_str($query, $a);
if( !empty($a) ){
  foreach($a as $key => $value ){
     switch( $key ) {

    //Do rest of code or skip if $a has no key value pairs
}

Line 45:

$result .= $cat_name['categories_name'];

This last one is easy.

function transform_uri($param) {
  //Define the result variable
  $result = '';
  ....

As far as using the @ operator to suppress errors. …

mschroeder 251 Bestower of Knowledge Team Colleague

Short tags can definitely be disabled, however they are enabled by default.

If they are disabled, there are ways to use a stream wrapper to replace <?= to <?php echo on the the fly, but its merely a workaround.

RTM

mschroeder 251 Bestower of Knowledge Team Colleague
[form]
[input type='text' name='username' value='<?=$value?>']


[/form]

The little php snippet inside the form input value.

Are you getting the idea??
:)

Unless php short tags are disabled.
Some good discussion on the topic: http://stackoverflow.com/questions/200640/are-php-short-tags-acceptable-to-use

mschroeder 251 Bestower of Knowledge Team Colleague

strstr() does not satisfy the ops original conditions. The op wants the last item in a comma delimited string, without knowing what the item is prior.

mschroeder 251 Bestower of Knowledge Team Colleague

I added richieking's suggestion to my test code which is updated on github if interested.

For starters in php 5.3 split() is depreciated so its worth avoiding now.
preg_split is the suggested replacement, so I added this as well.

The results were pretty much what I expected this was a snapshot of a run with 10000 items in the string:

array_pop test
Total Time: 0.0065879822 seconds.
---------------------------------------
explode test
Total Time: 0.0072600842 seconds.
---------------------------------------
trim test
Total Time: 0.0030097961 seconds.
---------------------------------------
ltrim test
Total Time: 0.0000169277 seconds.
---------------------------------------
substr test
Total Time: 0.0000491142 seconds.
---------------------------------------
split test
Total Time: 0.3050770760 seconds.
---------------------------------------
preg_split test
Total Time: 0.0080001354 seconds.
mschroeder 251 Bestower of Knowledge Team Colleague

I was going to suggest array_pop(explode(', ', $string)); but the more I thought about it I figured creating an array out of n items in a string wasn't going to be the most efficient way to do it. So I ran some quick micro benchmarks to get an idea of just how much of a performance hit it would take.

I ran 4 different methods through the test and ran each test 5 times averaging the results.
array_pop - is the method I was going to suggest
trim - is the method Manny7 posted
ltrim - is the method paulrajj posted
substr - is the method Borzoi posted

I ran the benchmarks with strings made of 5 items, 100 items and 10000 items.

Results:
5 String Items
array_pop - .00003300s
trim - .00002360s
ltrim - .00001640s
substr - .00004559s

100 String Items
array_pop - .00010295s
trim - .00003781s
ltrim - .00001636s
substr - .000012765s

10000 String Items
array_pop - .00687265s
trim - .00320082s
ltrim - .00001755s
substr - .00005536s

The method posted my paulrajj is by far the fastest in every test. If you look at these quick benchmarks the ltrim method is almost 400x faster than array_pop when working with a substantial amount of items.

<?php
//paulrajj
$last = ltrim(strrchr($text, ", "), ", ");

**These were all run on a PHP 5.3.3 installation on Windows 7-64 Pro. …

mschroeder 251 Bestower of Knowledge Team Colleague

That is a shame PDO is not installed on your hosting server.
You have a couple options:

  1. MySQLI w/Prepared Statements
  2. MySQLi wo/Prepared Statements
  3. MySQL w/mysql_real_escape_string

Personally I favor MySQLi over MySQL.

Look at the following php.net manual pages:
http://www.php.net/manual/en/book.mysqli.php
http://www.php.net/manual/en/mysqli.connect.php
http://www.php.net/manual/en/mysqli.prepare.php
http://www.php.net/manual/en/class.mysqli-stmt.php

There are enough complete examples there that you should be able to port that small section of code to MySQLi with little effort.

Essentially your process will be:

  1. Connect to the database server
  2. prepare the statement (if you're using prepared statements still)
  3. execute the statement/query
  4. iterate over the results
mschroeder 251 Bestower of Knowledge Team Colleague

That would be my fault.

if( count( $rowset ) == 1 ){
     //We only have exactly 1 row returned.
     $row = $rowset[0];
     $_SESSION['id'] = $row['id'];
}

That should fix it.