Open selected listbox item

Pierre K
Pierre K used Ask the Experts™
on
Hi all,

I have the following script and would like to know where I would place code to open the item once it is selected from the listbox.
I'm planning on using the header('Location: ...;) method but have no idea where to place it in the code

I hope I made myself clear on what I need
Thanks a lot

<?php
session_start();

error_reporting(E_ALL);

// THE DESIRABLE FILE NAMES ARE KEPT IN AN ARRAY
//should be able to find 123*.xml
//$signals = Array($_SESSION['username'].'*.xml'=>'regex');
//$signals = Array($_SESSION['username'].'.*\.xml'=>'regex');
  $signals = Array( '^' . $_SESSION['username'].'.*\.xml'=>'regex');
  
// THE OPTION STATEMENTS ARE COLLECTED IN AN ARRAY
$options = Array();

// COLLECT THE FILE OBJECTS
$path = realpath(getcwd());
$objs = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);

// ITERATE OVER THE OBJECTS TO FIND THE DESIRABLE FILES
foreach($objs as $path => $obj)
{
    $name = $obj->getFileName();
    // this is looking for "exact" matches.
    if (in_array($name, $signals))
    {
        $options[]
        = '<option value="'
        . $path
        . '">'
        . $name
        . '</option>'
        ;
    }
	else
	{ //echo 'Searching for '.$name.PHP_EOL;
		foreach($signals as $k=>$v)
		{
            // is you set $signals = [ '123*.xml/'=>'regex', '456*.txt'=>'regex']
            //the if clause below will get executed
			if( $v=='regex' )
			{
				if( preg_match('/'. str_replace('/','\\/',$k) .'/',$name))
				{
					$options[]
					= '<option value="'
					. str_replace($_SERVER['DOCUMENT_ROOT'],'', $path)
					. '">'
					. substr($name,strlen($_SESSION['username']),strlen($name)-4-strlen($_SESSION['username'])) //Only pass file name without ext
					. '</option>'
					;
				}
			}

            // is you set $signals = [ '123'], but you have the following files: '123.xml', 'xyz-123.txt'
            // the if clause below will get executed and will find both, because this is a "contains" filter
			elseif( stripos($name, $v)!==false )
			{
				$options[]
				= '<option value="'
				. str_replace($_SERVER['DOCUMENT_ROOT'],'', $path)
				. '">'
				. $name
				. '</option>'
				;
			}
		}
	}
}

// GENERATE THE OPTION STATEMENTS
$opts = implode(PHP_EOL, $options);

// CREATE THE HTML USING HEREDOC NOTATION
$html = <<<EOD
<p>Leave History<br>
<select name="listbox" size="1">
<option value="">Open to view</option>
$opts
</select>
</p>
EOD;

// SHOW THE HTML
echo $html;

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Expert of the Year 2008
Top Expert 2008
Commented:
Try:
<?php
session_start();
error_reporting(E_ALL);

if( array_key_exists('request',$_POST) && array_key_exists('listbox',$_POST) && 'ajax'==$_POST['request'] && '.xml'==strtolower(substr($_POST['listbox'],-4)_ )
{
`	header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
	readfile($_POST['listbox']);
	exit;
}
// THE DESIRABLE FILE NAMES ARE KEPT IN AN ARRAY
//should be able to find 123*.xml
//$signals = Array($_SESSION['username'].'*.xml'=>'regex');
//$signals = Array($_SESSION['username'].'.*\.xml'=>'regex');
  $signals = Array( '^' . $_SESSION['username'].'.*\.xml'=>'regex');
  
// THE OPTION STATEMENTS ARE COLLECTED IN AN ARRAY
$options = Array();

// COLLECT THE FILE OBJECTS
$path = realpath(getcwd());
$objs = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);

// ITERATE OVER THE OBJECTS TO FIND THE DESIRABLE FILES
foreach($objs as $path => $obj)
{
    $name = $obj->getFileName();
    // this is looking for "exact" matches.
    if (in_array($name, $signals))
    {
        $options[]
        = '<option value="'
        . $path
        . '">'
        . $name
        . '</option>'
        ;
    }
	else
	{ //echo 'Searching for '.$name.PHP_EOL;
		foreach($signals as $k=>$v)
		{
            // is you set $signals = [ '123*.xml/'=>'regex', '456*.txt'=>'regex']
            //the if clause below will get executed
			if( $v=='regex' )
			{
				if( preg_match('/'. str_replace('/','\\/',$k) .'/',$name))
				{
					$options[]
					= '<option value="'
					. str_replace($_SERVER['DOCUMENT_ROOT'],'', $path)
					. '">'
					. substr($name,strlen($_SESSION['username']),strlen($name)-4-strlen($_SESSION['username'])) //Only pass file name without ext
					. '</option>'
					;
				}
			}

            // is you set $signals = [ '123'], but you have the following files: '123.xml', 'xyz-123.txt'
            // the if clause below will get executed and will find both, because this is a "contains" filter
			elseif( stripos($name, $v)!==false )
			{
				$options[]
				= '<option value="'
				. str_replace($_SERVER['DOCUMENT_ROOT'],'', $path)
				. '">'
				. $name
				. '</option>'
				;
			}
		}
	}
}

// GENERATE THE OPTION STATEMENTS
$opts = implode(PHP_EOL, $options);

// CREATE THE HTML USING HEREDOC NOTATION
$URL =$_SERVER['SCRIPT_NAME'];

$html = <<<EOD
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
	jQuery('#fileList').on('change',function(){
		jQuery.ajax({'url':'{$URL}'
					, 'method':'POST'
					,'data': {'request':'ajax','listbox':jQuery(this).val()}
					}).done(function(data){
						//whatever you need to do upon success
					});
	});
});
</script>

<p>Leave History<br>
<select id="fileList" name="listbox" size="1">
<option value="">Open to view</option>
$opts
</select>
</p>
EOD;

// SHOW THE HTML
echo $html;

Open in new window

Author

Commented:
Nothing happens when I run the script - the listbox doesn't appear anymore
Expert of the Year 2008
Top Expert 2008

Commented:
>>  the listbox doesn't appear anymore
You mean when you first load the page? If so, take a look at your server log.  Most likely there is a runtime error that prevents the script from completing and hence the reason you don't even see the list.
Announcing the Winners!

The results are in for the 15th Annual Expert Awards! Congratulations to the winners, and thank you to everyone who participated in the nominations. We are so grateful for the valuable contributions experts make on a daily basis. Click to read more about this year’s recipients!

Author

Commented:
@hielo - I cleared the cashe etc but it still doesn't appear.
I don't have enough pHp knowledge to spot a problem.
When I revert to the script before your changes it does appear again.
Expert of the Year 2008
Top Expert 2008

Commented:
Do you have access to the command line?  If so, do a syntax check from the command line:
php -l your file.php

Line 5 seems to be missing a closing parenthesis at the very end, but I suggest you check the syntax from the command line if possible -- just to make sure all syntax problems are addressed first.

Author

Commented:
@hielo - thanks for tip about the syntax. I found another one and fixed it.
Now the listbox does appear so I'm very close to the goal

I replaced your line:
//whatever you need to do upon success

With this line:
header('Location: index.html');

Just to test but it did nothing. Any advice on that please?

Author

Commented:
Ultimately I would like to 'browse' to the the file named $name in the script in line 55 when it gets selected since the file will reside in the same directory my php file is located so I'm thinking it should just open it I hope
Expert of the Year 2008
Top Expert 2008

Commented:
>> header('Location: index.html');
That will not work because header() is a php function -- it executes on the server-side before the html is sent to the browser.  If you need to do redirection, you need to use client-side rediretion:
window.location.href = "http://site.com/index.html";

Author

Commented:
@hielo - Thanks for pointing that out
I'll play around with the suggested option

All the best!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial