mschroeder 251 Bestower of Knowledge Team Colleague

Depending on the complexity of the directory structure you're trying to navigate i'd recommend looking at the Standard PHP Library (SPL) specifically at DirectoryIterator and RecursiveDirectoryIterator

They're going to greatly simplify navigating very complex hierarchies. The other thing that is nice is you can always wrap them with a filter iterator to filter out only particular file types or by filename etc, and then you could also wrap that in a sorting iterator, which would be more of a custom iterator, that would allow you to reorder based on whatever criteria you wanted.

Can always mix and match based on your requirements.

mschroeder 251 Bestower of Knowledge Team Colleague

jpGraph is a very full featured and very powerful graphing library.
Its not flashy and its not going to produce flash charts but it definitely gets the job done.

If you do want some fancier charts but still want to be able to use the system without relying on google's servers then check out Open Flash Chart 2 http://teethgrinder.co.uk/open-flash-chart-2/

mschroeder 251 Bestower of Knowledge Team Colleague

Has anyone else ever taken the XML/XSL approach?

I found generating XML representations of my output and using XSL style sheets to do the transformations with the php XSL extension to quite powerful and surprisingly fast.

It also truly separates your php from your template while also being a w3 standard.

mschroeder 251 Bestower of Knowledge Team Colleague

You could also use a PHP 5 DirectoryIterator from the SPL library.

$iterator = new DirectoryIterator('/path/to/directory/');

foreach($iterator as $fileinfo){
	if( !$fileinfo->isDot() && $fileinfo->isFile() ){
		echo $fileinfo->getPathname();
	}
}

DirectoryIterators implement the SplFileInfo class (http://www.php.net/manual/en/class.splfileinfo.php) so anything available there is also immediately available in $fileinfo

From my quick tests and observations this always iterates over a directory alphabetically a -> z but documentation says it does not do any sorting prior.

If you wanted to make it sortable I can show you what a sortable iterator would look like since a DirectoryIterator is a little more "special" then your other iterators.

mschroeder 251 Bestower of Knowledge Team Colleague

@karuppasamy
Froger already explained why that solution is not a viable solution.

Sorry do you want to restrict or resize the image?

If you are trying to create a social networking application you will need either a Java or Flash application to handle the file upload process as PHP is very lacking in this aspect.

Reasons being is that PHP can only handle the file once it has been uploaded to the server. So if the size limit is 1mb and the user tries to upload a 1gb file they will have to wait and upload there file before PHP tells the user that the file is too large.

mschroeder 251 Bestower of Knowledge Team Colleague

Check out Plupload. It is a very interesting offering that allows you to configure a file uploader using a variety of different runtimes.
Flash, Gears, Silverlight, HTML5, HTML4, etc.

http://www.plupload.com/index.php

mschroeder 251 Bestower of Knowledge Team Colleague

I believe what you're looking for is something like the following

RewriteRule !\.(js|ico|gif|jpg|png|css)$ /index.php

Where any request which is not for a file of those types is routed to index.php (You would need to add pdf to that)

But I think a better solution would be to use something like the Zend Framework does:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

Which basically says if the requested file is not a directory, file (with size) or symbolic link, rewrite it to index.php.

mschroeder 251 Bestower of Knowledge Team Colleague

http://www.webhostingtalk.com read through their shared hosting offers forum or reseller or whatever you're looking for then search those companies on their site and read through topics about the host. Probably one of the most robust resources when it comes to host selection that I've found.

If you want to avoid the legwork, i highly recommend LiquidWeb http://liquidweb.com/. Have worked with them many times, have dealt with them on the dedicated and shared levels, and they're amazing. Their support is top notch.

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

I'm just curious to see what are favorite PHPers in terms of the following:
1. What is your favorite IDE (If you can tell why you love it, it will ice the cake)?
2. What is your favorite JS/PHP libraries (I would love to hear why)
3. What PHP framework do you use?
4. Anything else related?

1. PDT and/or Zend Studio (Little more polished).
2. jQuery
3. Zend Framework
4.

Frameworks seemed like overkill when i first started looking at them. But, once I got into more advanced projects frameworks really shined.

mschroeder 251 Bestower of Knowledge Team Colleague

You could verify the credit card number using the Luhn Algorithm. http://en.wikipedia.org/wiki/Luhn_algorithm There is a link at the bottom for an example of a php algorithm.

There are some resources I have seen online that describe the particulars of most major card providers in terms of length of card number, general acceptable ranges, as well as what to look for in terms of CVV's and often how frequently they expire.

Besides checking if the number is valid, the date is not expired and the other fields are filled in, I agree with pritaeas that the best way to do this would be through your payment gateway of choice.

mschroeder 251 Bestower of Knowledge Team Colleague

This is not an IE issue.
Get yourself Firebug for Firefox and the IE Developer Toolbar for IE7 -- maybe 6 and 8?

When I run through the example on firefox it is not removing the li tags from the list when i deselect a tag, just the input and the label.

Firefox is leaving the empty li tags and not displaying them or hiding them or something I assume it is your css. On IE7 the EXACT same behavior is occurring except IE7 is leaving the li's in their default state (expanded/not hidden?).

Both browsers show like this once i have removed items that i previously selected.

<ul class="selected">
<li> </li>
<li> </li>
</ul>
pritaeas commented: Useful comment, confirms my suspicion +4
mschroeder 251 Bestower of Knowledge Team Colleague

if you're making the form submit to itself then you need to make the index action in the index controller look for post data so it knows it needs to validate the form.

<?php

class IndexController extends Zend_Controller_Action
{
  public function indexAction()
  {
    $form = new Default_Form_Index();
    $request = $this->getRequest();

    //Check if we have post data
    if( $request->isPost() )
    {
      //If the form is NOT valid redisplay it with errors
      if( !$form->isValid($request->getPost() ) )
      {
        $this->view->form = $form;				           		
        return;
      }

      //Form passes validation and filtering
      //Do something with the data.
      $data = $form->getValues();

      //Maybe a redirect or change what view is getting rendered?

      //Just to stop execution after processing the form return;
      //return; 
    }

    //If no post data assume we're just displaying the form to the user
    $this->view->form = $form;
  }
}
mschroeder 251 Bestower of Knowledge Team Colleague

I've now tested it on both linux (centos) and windows (xp) and both php 5.2.10 and php 5.3.0 and don't see the dot directories showing up.

<?php 
error_reporting(E_ALL | E_STRICT);

$path = '/path/to/file';

$iterator = new RecursiveDirectoryIterator($path);
$recurse = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::SELF_FIRST);
echo "<ul>\n";
$x=0;
foreach ( $recurse as $file)
{
	$parts = explode('.',$file->getBasename());
	$extension = strtolower(end($parts));
	
	if( $file->isDir() && !$recurse->isDot() )
	{
		echo "<li><b>{$file->getBasename()}</b></li>\n";
		
	}
	else if( $file->isFile() && $extension == 'zip' )
	{
		//unlink($file->getPathname());
	}
	else if( $file->isFile() && ($extension == 'mp3' || $extension == 'mpa') )
	{
		echo "<li>
		      <input type = \"checkbox\" name = \"file$x\" value = \"{$file->getBasename()}\" />
		      <input type = \"hidden\" name = \"file".$x."_path\" value = \"{$file->getPathname()}\" />
		      <a href=\"{$file->getPathname()}\">{$file->getBasename()}</a>
		      </li>\n";
	}
	++$x;
}
echo "</ul>";
mschroeder 251 Bestower of Knowledge Team Colleague

change that line to:

$parts = explode('.',$file->getBasename());
$extension = strtolower(end($parts));

apparently explode returns its value by reference.

Are . and .. showing? In my quick testing they didn't show up at all.

mschroeder 251 Bestower of Knowledge Team Colleague

post what is on line 97 of your file. There is nothing in my code that is passed by reference.

The indentation will be a little more tricky but i'll see what i can do.

mschroeder 251 Bestower of Knowledge Team Colleague

I am not sure what the point of $x is in that function besides being a counter. But this should solve your recursion issue.

<?php 

//Path to starting point
$path = '/your/path/goes/here';

//Create a recursive directory iterator
$iterator = new RecursiveDirectoryIterator($path);

echo "<ul>\n";
$x=0;

//Foreach iteration do something.
foreach (new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::SELF_FIRST) as $file)
{
	
	$extension = strtolower(end(explode('.',$file->getBasename())));
	
	if( $file->isDir() )
	{
		echo "<li><b>{$file->getBasename()}</b></li>\n";

	}
	else if( $file->isFile() && $extension == 'zip' )
	{
		//unlink($file->getPathname());
	}
	else if( $file->isFile() && ($extension == 'mp3' || $extension == 'mpa') )
	{
		echo "<li>
		      <input type = \"checkbox\" name = \"file$x\" value = \"{$file->getBasename()}\" />
		      <input type = \"hidden\" name = \"file".$x."_path\" value = \"{$file->getPathname()}\" />
		      <a href=\"{$file->getPathname()}\">{$file->getBasename()}</a>
		      </li>\n";
	}
	++$x;
}
echo "</ul>";

It appears $x is just being used so there is a unique number to put into the checkboxes. However with php if you are using this to build a form that you can select music files to delete or move or whatever, using a checkbox name of `anything[]` will create a php array of checkbox values on submit.

Then your checkbox value can be the actual path to the file including the filename. No need to have the hidden input then.

mschroeder 251 Bestower of Knowledge Team Colleague

Just be very careful when working with values passed in the GET & POST arrays . Its extremely easy for them to be modified by the user and you have to be fully aware of this.

Probably the most common thing i've seen is the usage of $_GET and $_POST in queries or being used to dynamically include files in their raw, straight from the url, forms.

mschroeder 251 Bestower of Knowledge Team Colleague

That is what I was trying to illustrate as well, that it was a path problem, aka the filename was missing from the path, the code itself was fine. The example i posted was from the manual illustrating path + filename. I apologize for any confusion caused to the op.

mschroeder 251 Bestower of Knowledge Team Colleague

The problem you're having is $_FILES is an actual filename. your destination is a directory without a file name. its trying to create a file named "uploads", which is a valid filename on a linux system, in your dw folder. Try actually giving the file a filename in the destination path.

Example:

<?php
$uploads_dir = '/uploads';
foreach ($_FILES["pictures"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES["pictures"]["tmp_name"][$key];
        $name = $_FILES["pictures"]["name"][$key];
        move_uploaded_file($tmp_name, "$uploads_dir/$name");
    }
}
?>

Source: php.net (move_uploaded_file)

Notice how in that code the destination is /uploads/[name of the actual file]. Should solve your problem.

mschroeder 251 Bestower of Knowledge Team Colleague

Why even bother with all of the sanitizing when the php5 DOM does this for you.

Check out the following code...it is based on what you originally posted and creates the same XML. Its not a perfect representation of what your script does but i wanted to make sure it was something you could run and see the output of.

It will look a bit overwhelming, but its very repetitive. This is something that would best be broken into a function that is called in the loop but actually seeing the DOM should help you understand what is going on.

Notice how it encodes the url html code. For it to be valid xml the a tag would either be part of the xml or needs to be encoded into its entities which is what the DOM does by default or it could be wrapped in a CDATA tag.

Check out of the DOM info on php.net

<?php
$result = array();
$result[] = array(
	'position' => 'some job',
	'postdate' => '01/01/2009',
	'jobref' => 'abc12345',
	'jobid' => '0987654321',
	'description' => 'this is a description'
);

$result[] = array(
	'position' => 'some other job',
	'postdate' => '01/02/2009',
	'jobref' => 'abc1212341234345',
	'jobid' => '09876123454321',
	'description' => 'this is another description'
);

$result[] = array(
	'position' => 'some asdfasdfjob',
	'postdate' => '01/01/2037',
	'jobref' => 'abc1234sdfgsdf5',
	'jobid' => 'sdfg0987654321',
	'description' => 'this is the last description'
);

$fullurl = '';


$doc = new DOMDocument('1.0', 'utf-8');
$doc->formatOutput = …
mschroeder 251 Bestower of Knowledge Team Colleague

check out http://www.mysqlperformanceblog.com/ you will have to do some looking and some reading but provide a lot of really good information for performance tuning and/or what you can expect from both engines.

mschroeder 251 Bestower of Knowledge Team Colleague

I think I have achieved what you were describing. There is some consolidation that could occur as there is minor repetitive code.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {

	function toggleReq()
	{
		$(':input.required').each( function() {
			$(this).show();
			$(this).next('label.required').show();
		});
	}
	
	$('.toggle').toggle(
		function() {
			var children = $(this).parent('fieldset').children(':input');
			$(children).each(function() {
				$(this).show();
				$(this).next('label').show();
			});
		},
		function () {
			var children = $(this).parent('fieldset').children(':input');
			$(children).each(function() {
				if( !$(this).hasClass('required') )
				{
					$(this).hide();
					$(this).next('label').hide();
				}
			});
		}
	);
	
	
$.onload = toggleReq(); 
});
</script>
<style>
	input
	{
		display: none;
	}
	label
	{
		display: none;
	}
</style>
</head>

<body>
	<form name="formID" id="questions-form" class="formular" method="post" action="">
    
		<fieldset class="fieldsetClass" id="question-0">
	        <legend>Question 1</legend>
            <div class="toggle">Click Here</div>
            
	        <input class="required" type="radio" name="answer[0]" value="0" id="radio-0-0" />
            <label class="required" for="radio-0-0">Green</label>
            
	        <input class="required" type="radio" name="answer[0]" value="1" id="radio-0-1" />
            <label class="required" for="radio-0-1">Red</label>
            
	        <input type="radio" name="answer[0]" value="2" id="radio-0-2" />
            <label for="radio-0-2">Orange</label>       
	    </fieldset>
        
	    <fieldset class="fieldsetClass" id="question-1">
	        <legend>Question 2</legend>
            <div class="toggle">Click Here</div>
            
	         <input type="radio" name="answer[1]" value="0" id="radio-1-0" />
             <label for="radio-1-0">21</label>
             
	         <input class="required" type="radio" name="answer[1]" value="1" id="radio-1-1" />
             <label class="required" for="radio-1-1">11</label>
             
	         <input class="required" type="radio" name="answer[1]" value="2" id="radio-1-2" />
             <label class="required" for="radio-1-2">23</label>     
	    </fieldset>
        
	</form>
</body>
</html>

I didnt make any changes to your form EXCEPT i changed the toggle divs to have a class of toggle instead of unique id's. This allows us to bind the same toggle event to every toggle div.

I also set the styles for input and label display:none right off the bat …

mschroeder 251 Bestower of Knowledge Team Colleague

@essential

I may be wrong, but wouldn't the onblur event mean the field needs to lose focus?

If its auto-submitting the form then it should probably wait for a delay indicating the user has finished typing. Something like the solution posted in the comments on this site: http://www.openjs.com/scripts/events/check_after_typing.php works very elegantly for this.

I didnt see anything in your code like this, so i apologize if i missed it.

mschroeder 251 Bestower of Knowledge Team Colleague

P.S.
You should ALWAYS store dates and times in the standard date/time format (YYYY-MM-DD HH:SS), and store them in date type fields, to avoid problems just like this one.

This is such a common topic that can be debated in so many different ways. The fact is BOTH the unix timestamp and mysql date fields are standards and php and mysql both provide the necessary mechanisms for converting between the two.

So I completely DISAGREE with always storing date time information in a textual fashion. Both have their place, both advantages and disadvantages.

^ beat me to the punch. What he said

mschroeder 251 Bestower of Knowledge Team Colleague

Google for Wildcard DNS

mschroeder 251 Bestower of Knowledge Team Colleague

They are two different technologies:

php is server-side and will be executed on the server with the results being displayed to the user.

jquery is client-side and will be executed in the user's browser.
the only code it can modify is the html code that is delivered by the server. plus being client-side all a user needs to do is view your source and navigate to your javascript files to see whatever it is you are doing with your code. there is not much if anything secure about it.

mschroeder 251 Bestower of Knowledge Team Colleague
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Test Page</title>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() 
{
	//Listens for form id "frm" to be submitted
	//When submitted checks if 1 or more checkboxes are checked.
	$('#frm').submit( function() {
		
		//Look for ONLY checked inputs under this form
		var n = $('#frm :checked').length;
		
		//If we have 1 or more show how many
		if( n > 0 ){ alert( n + ' are checked' ); }
		//Else show we have none that are checked
		else { alert( 'none are checekd' ); }
		
		//Prevents form submission for demo
		return false;
	});
});
</script>

</head>
<body>
<form id="frm" action="#">
<div>
<label for="chb0">Check Field1: 
	<input type="checkbox" id="chb0" name="chb0" value="CheckBox #1">
</label><br> 
<label for="chb1">Check Field2: 
	<input type="checkbox" id="chb1" name="chb1" value="CheckBoX #2">
</label><br><br>
<input type="submit" value="submit" id="sbm" name="sbm">
</div>
</form>
<input type="checkbox" id="chb1" name="chb1" value="CheckBoX #2">
</body>
</html>

If you're going to be using javascript throughout your project I'd highly suggest looking at a library like jQuery. It will make you life much easier and the amount of power you gain as well as its cross browser compatibility is amazing.

This example illustrates checking if 1 or more checkboxes in your form a checked. the checkbox that is outside of the form will not contribute to the overall count. It also does NOT care what the inputs are named or their ids. It is looking for ANY input that is checked in …

mschroeder 251 Bestower of Knowledge Team Colleague

Actually in a purely PHP file, the closing tag ?> should be excluded.

It is necessary when you are jumping in an out of php control structures that are mixed with html or some other kind of output.

mschroeder 251 Bestower of Knowledge Team Colleague

Then the problem is in the code prior to:

echo '<tr>'.
'<td>'.$row['title'].'</td>'.'<td>'.$row['category'].'</td>'.'<td>'.$row['year'].'</td>'.
'<td>'.'<font size="2"><a href="edit.php?autoid="'.$row['autoid'].'">
edit</a></font>'.'</td>'.'<td>'.'<font size="2"><a href="delete.php?autoid="'.$row['autoid'].'" >delete</a></font>'.'</td>'.
'</tr>';

as it doesn't appear to actually be returning an autoid.

mschroeder 251 Bestower of Knowledge Team Colleague

There are some fine Ajax/Javascript libraries that exists:

http://jquery.com/
http://www.prototypejs.org

Are two very prominent ones, but there are countless others.
They all have Ajax examples and simplify working with the DOM etc.

mschroeder 251 Bestower of Knowledge Team Colleague

^ What they said.

mschroeder 251 Bestower of Knowledge Team Colleague

Well you're definitely right. regex is definitely slower when compared to str_replace especially as the length of the string increases. Although return str_replace(' ', '', $str); is not the same as return preg_replace('/\s*/m', ' ', $str); as the regex covers ALL whitespace, newlines tabs etc etc. When i ran your benchmarks on 5.3b1 str_replace did not replace tabs and new lines in the output.

However adding those to an array of replacements in str_replace still drastically spanked the regular expression replacement.

I feel kinda stupid for overlooking to most obvious solution to a few year old thread haha.

mschroeder 251 Bestower of Knowledge Team Colleague

Do you possibly have cookies disabled in FF and have php configured to use a cookie to store the session id?

mschroeder 251 Bestower of Knowledge Team Colleague

Thanks. Very elegant solution. Wish you were around when this question was originally posted.

Oh, and btw, please forgive my ignorance. Like all people who reinvent the so-called wheel, I didn't know it existed. Thanks for the enlightenment.

If it solves your problem how you need it to solve your problem then its a solution. There is always more than one way to skin a cat.

mschroeder 251 Bestower of Knowledge Team Colleague

That is because your column type is set to datetime or timestamp not certain which one actually produces that as I don't use the mysql datetime or timestamp data type.

To store a unix timestamp you just need an INT(10)

mschroeder 251 Bestower of Knowledge Team Colleague

or UNIX_TIMESTAMP()

mschroeder 251 Bestower of Knowledge Team Colleague

Store a UNIX Timestamp in that mysql column.

<?php
$iCurrentTime = time();

$iCurrentTime would result in an integer like: 1236884436
Which is the number of seconds since the Unix Epoch.

You can pass that integer into the php date() function and format it any way you want, and you can also calculate against it simply using basic math.

The only drawback is that it can not store dates after 01/2038 because it will exceed the size of a 32bit integer or Before 01/1970. By 2038 I imagine 64bit hardware or greater will pretty much be the norm.

mschroeder 251 Bestower of Knowledge Team Colleague

GAH! Just realized how old this thread is, how did it get resurrected?!:-O

mschroeder 251 Bestower of Knowledge Team Colleague

In my previous post, you need to add a line to initialize $newstr. Corrected code should be as follows:

function StripExtraSpace($s)
{
$newstr = "";

for($i = 0; $i < strlen($s); $i++)
{
$newstr = $newstr . substr($s, $i, 1);
if(substr($s, $i, 1) == ' ')
while(substr($s, $i + 1, 1) == ' ')
$i++;
}

return $newstr;
}

For starters, functions in loops should be avoided whenever possible. e.g. for($i = 0; $i < strlen($s); $i++) also, you're doing a lot of extra work here.

I would suggest something like this:

<?php

$sTestString = 'This  is a stringwith    lots of 	odd spaces and tabs		
and some newlines too

lets see if this works.';

$sPattern = '/\s*/m'; 
$sReplace = '';

echo $sTestString . '<br />';
echo preg_replace( $sPattern, $sReplace, $sTestString );

Regular Expression removes ALL whitespace ( spaces, tabs, newlines) 0 or more times and also traverses multiple lines.

Put that in a file and run it in your browser, view the source and you'll see exactly what it has done.

No need to reinvent the wheel.

mschroeder 251 Bestower of Knowledge Team Colleague

Can you link to the W3C DOM Specs where you found that?

Dom Model 1
http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level-one-html.html#ID-22445964

http://www.w3.org/TR/REC-DOM-Level-1/level-one-html.html#ID-011100101 <== Search for "Interface HTMLDivElement"

HTML 4.0 DIV Definition
http://www.w3.org/TR/REC-html40/struct/global.html#edef-DIV

HTML 4.0 "disbaled" definition
http://www.w3.org/TR/REC-html40/interact/forms.html#adef-disabled -- It does say it is inheritable, but it is not valid in any of the elements you provided: http://www.w3.org/TR/REC-html40/index/elements.html

Its not on any of the elements in the 4.01 spec either
http://www.w3.org/TR/html401/struct/global.html#edef-DIV
http://www.w3.org/TR/html401/interact/forms.html#adef-disabled

mschroeder 251 Bestower of Knowledge Team Colleague
header( 'refresh: 5; url=http://www.example.com' );

Can also be a url relative to your site, like: home.php etc.

mschroeder 251 Bestower of Knowledge Team Colleague

nav33n: well that rules out the <b></b> tags then. haha. i've had issues with IE and FF going from one to the other and having broken functionality when I have a broken tag in the javascript. When I saw the <b>'s I figured it was worth a shot.

I also assume the OP means showing and hiding of the div, but based upon the status of the checkbox. I also made the assumption that the child nodes contained in that div were form elements in which case you could hide the div and disable the form and its fields... but not sure what additional benefit that would carry.

mschroeder 251 Bestower of Knowledge Team Colleague

Before i propose any other solutions, did you try removing the <b></b> tags from this line: <input type="checkbox" name="chkRecipeBook" id="chkRecipeBook" onclick="javascript<b></b>:disableAddressBook();" /> ?

mschroeder 251 Bestower of Knowledge Team Colleague

But the notices are important, I always like to develop with error_reporting( E_ALL | E_STRICT ); In a production environment I NEVER leave error reporting enabled.

The problem with the notices the OP was experiencing were just that, he didn't have variables initialized. But was testing for them in his scripts. Using some of the default php functions (e.g. isset and empty) we can circumvent that issue.

Obviously the best solution would be setting default values, and check types etc. But, one step at a time.

mschroeder 251 Bestower of Knowledge Team Colleague

It's the escaping in your html in this area

if ( empty( $_POST ) )
	{
		echo "<table border=\"0\" cellspacing=\"3\" cellpadding=\"3\">\n";
		echo "<form method=\"post\" action=\"./login.php\">\n";
		echo "<tr><td>Username</td><td><input type=\"text\" name=\"username\"></td><\tr>\n";
		echo "<tr><td>Password</td><td><input type=\"password\"name=\"password\"></td><\tr>\n";
		echo "<tr><td colspan=\"2\" align=\"center\"><input type=\"submit\" name=\"submit\" value=\"Login\"></td></tr>\n";
		echo "</form></table>\n";
	}
mschroeder 251 Bestower of Knowledge Team Colleague

Try this. I made several changes, including moving an IF/ELSE statement up into the prior control structure. I also revised your sql statements slightly.

See if this does the trick and if you have any questions i'll try to answer.

<?php
session_start();
include "./global.php";

echo "<title>Login</title>\n";

if( isset( $_SESSION['uid'] ) )
{
	echo "You are already logged in, if you wish to log out, please <a href=\"./logout.php\">click here</a>!\n";
} 
else
{
	if ( empty( $_POST ) )
	{
		echo "<table border=\"0\" cellspacing=\"3\" cellpadding=\"3\">\n";
		echo "<form method=\"post\" action=\"./login.php\">\n";
		echo "<tr><td>Username</td><td><input type=\"text\" name=\"username\"></td><\tr>\n";
		echo "<tr><td>Password</td><td><input type=\"password\"name=\"password\"></td><\tr>\n";
		echo "<tr><td colspan=\"2\" align=\"center\"><input type=\"submit\" name=\"submit\" value=\"Login\"></td></tr>\n";
		echo "</form></table>\n";
	}
	else 
	{
	
		$user = mss( $_POST['username'] );
		$pass = $_POST['password'];
		
		if( $user && $pass )
		{
			$sql = 'SELECT id FROM users WHERE username = "' . $user . '"';
			$res = mysql_query( $sql ) or die( mysql_error() );
			if( mysql_num_rows( $res ) > 0)
			{
				$sql2 = 'SELECT id FROM users WHERE username = "' . $user . '" AND password = "' . md5( $pass ) . '"';
				$res2 = mysql_query( $sql2 ) or die( mysql_error() );
				
				if(mysql_num_rows($res2) > 0)
				{
					$row = mysql_fetch_assoc($res2);
					$_SESSION['uid'] = $row['id'];
					
					echo "You have successfully logged in as " .$user;
				}
				else 
				{
				  echo "Username and password combination are incorrect!\n";
				}
		   }
		   else 
		   {
				echo "The username you supplied does not exist!\n";
		   }
		}
		else 
		{
			echo "You must supply both the username and password field!\n";  
		}
	}
}
mschroeder 251 Bestower of Knowledge Team Colleague

That is a Notice not an error, what it is telling you, is that your code is checking the value of $_SESSION even though the array key 'uid' does not exist in the $_SESSION array.

replace:

if($_SESSION['uid']){

with

if( isset( $_SESSION['uid'] )  ){

However, Notices should not affect your code, the only thing they make cause problems with is using the header() function as they can be unexpected output. So if the page is not displaying the login or register links something else is wrong.

mschroeder 251 Bestower of Knowledge Team Colleague

What is the actual error message you are getting, and what is the value of $_SESSION in this part of your code?

if($_SESSION['uid']){
      /** Add the following line **/
     echo $_SESSION['uid'];

     $sql = "SELECT id,username FROM 'users' WHERE 'id'='".$_SESSION['uid']."'";

     $res = mysql_query($sql) or die(mysql_error());
     if(mysql_num_rows($res) == 0){
          session_destroy();
          /** Displays login link **/
     }else {
          $row = mysql_fetch_assoc($res);
          /** displays logout link and info **/
     } 
}

Also, I don't believe your sql is correct.

$sql = "SELECT id,username FROM 'users' WHERE 'id'='".$_SESSION['uid']."'";

users is not a reserved word therefore does not need to be quoted.
Also id is not a reserved word and does not need to be quoted.
Finally, the value of $_SESSION is suppose to be an integer so again that does not need quoted.

MySQL Reserved Words

/** Type casting assumes you are using PHP5 **/
$sql = 'SELECT id, username FROM users WHERE id = '. (int) $_SESSION['uid'];

Hopefully my suggestions will solve your problem, but without the ACTUAL error message it is hard to say what exactly is causing the problem.

mschroeder 251 Bestower of Knowledge Team Colleague

I'm not sure if there will be a reliable alternative for the time being.
This is due to the Y2K38 problem. http://en.wikipedia.org/wiki/Year_2038_problem

nav33n commented: Wow! I never knew about Y2K38 problem! Thanks for the link. +10