Jesse Jesse - 1 year ago 59
PHP Question

PHP Error undefined index, search script

I am receiving the following error from my script.

[Tue Dec 01 09:17:10 2015] [error] [client xxxx] PHP Notice: Undefined index: search in xxx/search.php on line 3, referer: http://xx/

Additionally I get the following error sometimes as well

PHP Notice: Undefined offset: 4 in xxx/search.php on line 21, referer: http://xxx/search.php?search=C8053A-B&submit=Search

The code for search.php is

// Words
$words = trim($_GET["search"], ' ');
echo '<br>';
echo '<div align="center">';
echo '<form method="get" action="search.php?" id="searchform">';
echo '<input type="text" name="search">';
echo '<input type="submit" name="submit" value="Search">';
echo '</form>';
echo '</div>';
if ($words != '')
echo 'Search Results for <b>'.$words.'</b>:';
$file = fopen('inv.csv', 'r');
$crossw = $words;
$words = array($words);
$words = array_map('preg_quote', $words);
$regex = '/'.implode('|', $words).'/i';
print('<table border="1"><tr><td width="150">Primary Part #</td><td width="75">Price</td><td width="75">Qty Avail</td><td width="105">Searched #</td><td width="375">Description</td></tr></table>');
while (($line = fgetcsv($file)) !== FALSE) {
list($part, $price, $qty, $cross, $desc) = $line;
if(preg_match($regex, $cross)) {
print('<table border="1"><tr><td width="150">'.$part.'</td><td width="75">'.$price.'</td><td width="75">'.$qty.'</td><td width="105">'.$crossw.'</td><td width="375">'.$desc.'</td></tr></table>');
if ($crossw != '')
echo 'End of results.';

I want to get rid of the error without turning off logging in my php.ini.

What is the source/reason for the error?

Answer Source

This notice invites you to take into account the possibility that the search url parameter is not always set (perhaps when you first browse that search page ?).

$words = trim($_GET["search"], ' ');

You're assuming here that the ̀$_GET["search"] variable is always available for you to use, which is not the case.

This case should be properly handled in php with an isset() construct with a ternary operator (shorthand for if/else statement) like so :

$words = isset($_GET["search"])?trim($_GET["search"], ' '):''; // $words will be set to an empty string in case the search param is not set.