Call function php uing jquery - php

Hello i want to call a function using jquery. I tried a lot of ways and I can't get it.
This my principal webpage.
I'am uploading a file csv and pressing 'Crear' button, it uplaod the file while call the function.
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<SCRIPT type="text/javascript">
$(function (){
$('#btnxml').click(function (){
alert("aki");
$('#contenidos').load('csv.php');
});
});
</SCRIPT>
</head>
<body>
<form action="index.php" id="filecsv" method="post" enctype="multipart/form-data">
<input type="file" multiple="multiple" id="file" name="up_csv[]"/>
<input type="submit" value="Cargar" name="btnxml" id="btnxml" /><br />
</form>
<?php
global $archivocsv;
//tipos de archivos permitidos
$extensionxml = array('csv','txt');
//destino
$rutaupcsv = './csv/';
//multicargador de archivos
$vt=0;
for($i=0;$i<count($_FILES['up_csv']['size']);$i++){
for ($j=-1; $j<count($extensionxml); $j++) {
if (strripos($_FILES['up_csv']['name'][$i], $extensionxml[$j])!== false) {
$filename = 'lista';
$destino = $rutaupcsv.$_FILES['up_csv']['name'][$i];
$archivocsv = basename($_FILES['up_csv']['name'][$i]);
move_uploaded_file($_FILES['up_csv']['tmp_name'][$i],$destino);
$vt=$vt+1;
break;
}
$ns=1;
}
}
?>
<div id="contenidos"></div>
csv.php
<?php
echo '<html>';
echo '<head>';
echo '<meta content="text/html;charset=utf-8" http-equiv="Content-Type">';
echo '<meta content="utf-8" http-equiv="encoding">';
echo '</head>';
function makecsv() {
global $archivocsv;
$csv = './csv/' . $archivocsv;
$doc = new DOMDocument();
$row = 1;
$handle = fopen($csv, "r");
# Rows Counter
$csvxrow = file($csv);
$csvxrow[0] = chop($csvxrow[0]);
$anzdata = count($csvxrow);
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
#Load Predefined XML Template
$xml2 = $xml;
$xmlruta = './Templates/';
$xml = $xmlruta.$data[1].'.xml';
$doc->load($xml);
$xp = new DOMXPath($doc);
for ($c=0; $c < $num; $c++) {
foreach($xp->query('/ROOT/HEADER/#KEY[. != ""]') as $attrib)
{
$attrib->nodeValue = $data[0];
}
foreach($xp->query('/ROOT/DATA/SAPMES/LOIPRO/E1FKOL/#AUFNR[. != ""]') as $attrib)
{
$attrib->nodeValue = $data[0];
}
foreach($xp->query('/ROOT/DATA/SAPMES/LOIPRO/E1FKOL/#MATNR[. != ""]') as $attrib)
{
$attrib->nodeValue = $data[1];
}
foreach($xp->query('/ROOT/DATA/SAPMES/LOIPRO/E1FKOL/#GAMNG[. != ""]') as $attrib)
{
$attrib->nodeValue = $data[2];
}
foreach($xp->query('/ROOT/DATA/SAPMES/LOIPRO/E1AFFLL/E1FVOL/#MGVRG[. != ""]') as $attrib)
{
$attrib->nodeValue = $data[2];
}
foreach($xp->query('/ROOT/DATA/SAPMES/LOIPRO/E1FKOL/#GSTRS[. != ""]') as $attrib)
{
$attrib->nodeValue = $data[3];
}
foreach($xp->query('/ROOT/DATA/SAPMES/LOIPRO/E1FKOL/#GLTRS[. != ""]') as $attrib)
{
$fecha = new DateTime($data[3]);
$fecha->add(new DateInterval('P1M'));
$attrib->nodeValue = $fecha->format('Y-m-d');
}
}
$name = $data[0] .'-'. $data[1];
$doc->formatOutput = true;
echo $doc->saveXML();
$rutafinal = './XML/';
$doc->save($rutafinal.$name.'.xml');
}
fclose($handle);
echo $anzdata . " XML Creados" . "<br />";
return $data;
}
makecsv();
echo '</html>';
?>
I can't call the function.
it doesn't do anything when i try to call it.
EDIT: I think the problem is in my function. function edite

Javascript can´t play with php directly because JS is client side (only in browser) and PHP is server side (only in browser). What you can do is a PHP file that has the code you want to invoke, and make JS call that page.
Separate the CVS code from the form and make JS call the new php with the CVS php functionality.

jQuery runs in the client's browser whereas your PHP is running on your web server. If you wish to call a PHP function from your jQuery code, your best option is to do so using AJAX.
You can find documentation for implementing an AJAX call in jQuery here: https://api.jquery.com/jQuery.ajax/

You'll need to print the actual hmtl to do the function.
PHP
<?php
print '<script> makecsv() </script>';
?>

Related

Why does my submit button fail to call php function?

I have a very simple php site that and am attempting to make it a little more dynamic. Previously, I required user to click on a link to open a new page containing several images together with some 'submit' buttons. Pressing a button called a php file that saved some information in a text box. This was working fine. However, I have now made the content a little more dynamic so that the user chooses an item from a popupmenu to update content in the same page. However, now the submit buttons produced dynamically do not seem to work. I am quite new to web development generally so not sure why this should be the case. Any help much appreciated.
This is the index.php file that populates the list box and sets up the page to dynamically manage the content.
'''php
<!doctype html>
<html>
<head>
<script>
function showImages( imageDate ) {
if ( imageDate == "") {
document.getElementById("imageTable").innerHTML ="";
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200 ) {
document.getElementById("imageTable").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", "dispData.php?imageDate="+imageDate, true );
xmlhttp.send();
}
}
</script>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Title</title>
<meta name="language" content="en" />
<meta name="description" content="" />
<meta name="keywords" content="" />
</head>
<body>
<?php
$myDirectoryStr = "trialImages/";
// open this directory
$myDirectory = opendir($myDirectoryStr);
// get each entry
while($entryName = readdir($myDirectory)) {
$dirArray[] = $entryName;
}
// sort into date order
sort( $dirArray );
// close directory
closedir($myDirectory);
// count elements in array
$indexCount = count($dirArray);
?>
<?php
// loop through the array of files and print them all in a list
$cnt = 0;
for($index=0; $index < $indexCount; $index++) {
$extension = substr($dirArray[$index], -10);
// start new row of table
if ($extension == 'tempIm.png'){
$dateStr[$cnt] = substr($dirArray[$index], 0, 8 );
$cnt++;
}
}
// count elements in array
$indexCount = count($dateStr);
// find unique dates
$dateStrUnique = array_values( array_unique( $dateStr, SORT_STRING ) );
// count elements in array
$indexCount = count($dateStrUnique);
echo '<form>';
echo '<select name="dates" onchange="showImages(this.value)">';
echo '<option value="">select date ...</option>';
for($index=0; $index < $indexCount; $index++) {
echo '<option value="' . $dateStrUnique[$index]. '">' . $dateStrUnique[$index] . '</option>';
}
echo '</select>';
echo '</form>';
?>
<br>
<div id="imageTable"><b> image information will be displayed here ... </b></div>
</body>
</html>
'''
This is the dispData.php file that produces the dynamic content used to update the div tag and containing the submit buttons and images
'''php
<?php
// recover some information
$imageDateTarget = $_GET['imageDate'];
// image directory
$myDirectoryStr = "trialImages/";
// open directory
$myDirectory = opendir($myDirectoryStr);
// get each entry
while($entryName = readdir($myDirectory)) {
$dirArray[] = $entryName;
}
// sort into date order
sort( $dirArray );
// close directory
closedir($myDirectory);
//count elements in array
$indexCount = count($dirArray);
echo '<table class="fixed">
<col width="200px">
<col width="200px">
<col width="100px">';
// loop through the array of files and display them in table
for($index=0; $index < $indexCount; $index++) {
$extension = substr($dirArray[$index], -10);
// start new row of table
if ($extension == 'tempIm.png'){ // input image place in first column
// image date
$imageDate = substr($dirArray[$index], 0, 8 );
// if image date the same as selected date then display image
if ( strcmp( $imageDateTarget, $imageDate ) == 0 ) {
echo '<tr>';
echo '<td>' . $dirArray[$index] . '</td>';
echo '</tr>';
echo '<tr>';
echo '<td height=400><img src="' . $myDirectoryStr . $dirArray[$index] . '" class="rotate90" " alt="Image" border=3 height=200 width=400></img></td>';
echo '<form action="writeNotes.php" method="POST">';
//search for matching image notes if they exist and display
$indexImageNotes = array_search( $imageDate . 'notes.txt', $dirArray );
if ($indexImageNotes){
$notes = file_get_contents($myDirectoryStr . $imageDate . 'notes.txt'); // read contents into string
echo '<td><textarea name = "notes" rows = "26" cols="30">' . $notes . '</textarea></td>';
}
else {
echo '<td><textarea name = "notes" rows = "26" cols="30">add some comments here ...</textarea></td>';
}
echo '<td><input type = "submit"></input><input type = "hidden" name = "imageDate" value = "' . $myDirectoryStr . $imageDate . '"></input></form></td>';
echo '</tr>';
}
}
}
?>
'''
And this is the writeNotes.php function that saves the text notes and should be called when the submit buttons are pressed
'''php
<?php
print_r("I am here");
$file = $_POST["imageDate"] . 'notes.txt';
$data = $_POST["notes"];
file_put_contents($file, $data);
?>
'''
Part of the problem is that I don't get any error messages, just a failure to execute the writeNotes.php function
I think there must be some mistakes in my earlier code as I have attempted a further simplified version and this seems to work. I simply populate a popupmenu below
'''php
<!doctype html>
<html>
<head>
<script>
function showImages( imageDate ) {
if ( imageDate == "") {
document.getElementById("imageTable").innerHTML ="";
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200 ) {
document.getElementById("imageTable").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", "dispData.php?imageDate="+imageDate, true );
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
<select name="dates" onchange="showImages(this.value)">
<option value="">select date ...</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</form>
<br>
<div id="imageTable"><b> information will be displayed here ... </b></div>
</body>
</html>
'''
And return the dynamic content here
'''php
<?php
echo '<form action="writeNotes.php" method="POST">
<td><input type = "submit"></input><input type = "hidden" name = "imageDate" value = "a_value"></input></form></td>';
?>
'''
And the writeNotes.php function
'''php
<?php
$file = $_POST["imageDate"];
print_r($file);
//header("Location: index.php"); //note there must be no output before using header
?>
'''
This seems to work without a problem. Apologies for asking the earlier question and thanks again for comments.

Why isn't my fread working?

Together is a program that is meant to look into a "csv" file with holidays in it, allow someone to choose a button labeled a number, and then write to file the holiday randomly chosen. It isn't working. Any help? Specifically the "choose.php" isn't working and isn't recieving any errors when I enable the ini_set settings, etc.
HTML FILE:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function start(){
$.ajax({
url:"cgi-bin/php/holiday/start.php",
success:function(code){
$("div#content").html(code);
}
});
}
function choose(link){
var data_id = $(link).attr('rel');
var post = {
id : data_id
}
$.ajax({
url:"cgi-bin/php/holiday/choose.php",
data:post,
method:"POST",
success:function(code){
$("div#content").html(code);
}
});
}
$(document).ready(function(){
start();
});
</script>
</head>
<body>
<header id='header'></header>
<div id='content'></div>
<div id='footer'></div>
</body>
</html>
start.php
<?php
$row = 1;
if (($handle = fopen("csv/index.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p>There are {$num} choices left</p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
?><button onClick='choose(this);' class='choice' rel='<?php echo $c;?>'><?php echo $c;?></div><?php
}
}
fclose($handle);
}?>
choose.php
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$file = fopen("csv/index.csv","r");
$holidays = explode(',',fread($file));
fclose($file);
shuffle($holidays);
$file = fopen("csv/choices.csv","a");
$holiday = $holidays[$_GET['rel']];
fwrite($file, "MY NAME GOT " . {$holiday});
fclose($file);
unset($holidays[$_POST['rel']]);
$file = fopen("csv/index.csv","w");
fwrite($file,implode(",",$holidays);
fclose($file);
echo "YOU GOT {$holiday}";
?>
csv/index.php
christmas,chinese new year
csv/choices is empty
fread() requires a second argument, the number of bytes to read. If you want to read the whole file, you can use the filesize() function:
$holidays = explode(',',fread($file, filesize($file)));
But if you want to read an entire file, you can use file_get_contents().
$holidays = explode(',', file_get_contents("csv/index.csv"));
And you can rewrite the file with:
file_put_contents("csv/index.csv", implode(',', $holidays));

How can I remove query string from URL?

Here is my code. It is a simple html form with two inputs. All data is saved into xml file using DOMDocument a then all data from XML file is inserted into the table below the form. I added two buttons edit and delete (x). Now I can edit and delete any user/player from the table. And here is my problem. I need to remove query string from URL after deleting or editing. I want to add a new user/player into the table after deleting. When I delete manually query string from URL everything works fine again. But I want to delete query string automatically after deleting some user. Sorry for my English hoping you understand me. Thanks in advance!
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$xml = new DOMDocument("1.0", "utf-8");
if (is_file('database.xml')) {
$xml->load("database.xml");
$db = $xml->getElementsByTagName('db')->item(0);
} else {
$db = $xml->createElement("db");
$xml->appendChild($db);
$db = $xml->getElementsByTagName('db')->item(0);
}
$newPlayer = $xml->createElement("player");
foreach ($_POST as $key => $value) {
$playerStuff = $xml->createElement($key, $value);
$newPlayer->appendChild($playerStuff);
}
$db->appendChild($newPlayer);
$xml->save("database.xml");
}
$name = $number = "";
if (isset($_GET['action']) && $_GET['action'] == 'edit') {
$xml = new DOMDocument("1.0", "utf-8");
$xml->load("database.xml");
$player = $xml->getElementsByTagName('player')->item($_GET['id']);;
$name = $player->getElementsByTagName('name')->item(0)->nodeValue;
$number = $player->getElementsByTagName('number')->item(0)->nodeValue;
}
if (isset($_GET['action'])) {
switch ($_GET['action']){
case 'edit':
$xml = new DOMDocument("1.0", "utf-8");
$xml->load("database.xml");
$player = $xml->getElementsByTagName('player')->item($_GET['id']);
$nameEl = $player->getElementsByTagName('name')->item(0);
$numberEl = $player->getElementsByTagName('number')->item(0);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$newName = $xml->createElement("name", $_POST["name"]);
$nameEl->parentNode->replaceChild($newName, $nameEl);
$newNumber = $xml->createElement("number", $_POST["number"]);
$numberEl->parentNode->replaceChild($newNumber, $numberEl);
$db = $xml->getElementsByTagName('db')->item(0);
$lastElement = $db->lastChild;
$lastElement->parentNode->removeChild($lastElement);
}
$xml->save("database.xml");
break;
case 'delete':
$xml = new DOMDocument("1.0", "utf-8");
$xml->load("database.xml");
//$xml = $dokument->getElementsByTagName('xml')->item(0);
$player = $xml->getElementsByTagName('player')->item($_GET['id']);
$player->parentNode->removeChild($player);
$xml->save("database.xml");
break;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>PLAYERS</title>
<link rel="stylesheet" href="stylesss.css">
</head>
<body>
<form action="" method="POST">
<input type="text" name="name" value="<?php echo $name ?>">
<input type="text" name="number" value="<?php echo $number ?>">
<input type="submit" value="INSERT">
</form>
<?php
$xml = new DOMDocument("1.0", "utf-8");
if (is_file('database.xml')) {
$xml->load('database.xml');
$players = $xml->getElementsByTagName("player");
echo "<table>";
echo "<tr><th>" . "Player Name" . "</th><th>" . "Number". "</th></tr>";
foreach($players as $key => $player){
echo "<tr>";
foreach($player->childNodes as $data) {
echo "<td>". $data->nodeValue ."</td>";
}
echo "<td>
<a href='?id={$key}&action=edit' class='buttons edit'>EDIT</a>
<a href='?id={$key}&action=delete' class='buttons delete'>&#10006</a>
</td>";
echo "</tr>";
}
}
echo "</table>";
?>
</body>
</html>
I would say to redirect header("Location: your-page.php"); The page you redirect to can be the same page but without the query string. It means that if someone refreshes you will not repeat the same action. So, something like this. You have to use the header function before anything is written to the page, it will not work if it is used after HTML or after something is print or echo to the page.
if (isset($_GET['action'])) {
switch ($_GET['action']){
case 'edit':
$xml = new DOMDocument("1.0", "utf-8");
$xml->load("database.xml");
$player = $xml->getElementsByTagName('player')->item($_GET['id']);
$nameEl = $player->getElementsByTagName('name')->item(0);
$numberEl = $player->getElementsByTagName('number')->item(0);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$newName = $xml->createElement("name", $_POST["name"]);
$nameEl->parentNode->replaceChild($newName, $nameEl);
$newNumber = $xml->createElement("number", $_POST["number"]);
$numberEl->parentNode->replaceChild($newNumber, $numberEl);
$db = $xml->getElementsByTagName('db')->item(0);
$lastElement = $db->lastChild;
$lastElement->parentNode->removeChild($lastElement);
}
$xml->save("database.xml");
break;
case 'delete':
$xml = new DOMDocument("1.0", "utf-8");
$xml->load("database.xml");
//$xml = $dokument->getElementsByTagName('xml')->item(0);
$player = $xml->getElementsByTagName('player')->item($_GET['id']);
$player->parentNode->removeChild($player);
$xml->save("database.xml");
break;
}
header("Location: your-page.php");
}

How to call a Php Function from html

I am using a PHP scraper by using simple PHP DOM library. I wrote a function which scrapes data that I need. How can I call that function from html page? I need to show that data in my html page. I am using AngularJS framework and I am working with views.
Here is my code.
function Islamabad_data(){
// Array Declaration
var isb_hi_temp = new Array();
$fhtml1 = file_get_contents('http://www.accuweather.com/en/pk/islamabad/258278/daily-weather-forecast/258278');
$fhtml1 = str_get_html($fhtml1);
$day6 = file_get_contents('http://www.accuweather.com/en/pk/islamabad/258278/daily-weather-forecast/258278?day=6');
$day6 = str_get_html($day6);
echo "Islamabad Data<br>";
echo" <br>High temperature <br>";
foreach($fhtml1->find('#feed-tabs .temp') as $element){
echo $element->plaintext;
?>
isb_hi_temp.push('<?php echo $element; ?>');
<?php
}
$i=0;
foreach($day6->find('#feed-tabs .temp')as $element)
{
if($i<2)
{
echo $element->plaintext;
?>
isb_hi_temp.push('<?php echo $element; ?>');
<?php
$i++;
}
}
echo isb_data;
}
I know this is not an answer but I've simplified your code. It looks like you want to generate a JavaScript array that can be fetched by Angular. Step 1 one is to properly generate the JSON you need. There were a lot of mistakes in your code -- you cannot intermix JavaScript and PHP in the way that you were doing. Usually in PHP we'll generate an array object using PHP then call json_encode to create the JSON object that will be accessed by the client (in this case, you are using Angular as your client).
function Islamabad_data(){
$fhtml1 = file_get_contents('http://www.accuweather.com/en/pk/islamabad/258278/daily-weather-forecast/258278');
$fhtml1 = str_get_html($fhtml1);
$day6 = file_get_contents('http://www.accuweather.com/en/pk/islamabad/258278/daily-weather-forecast/258278?day=6');
$day6 = str_get_html($day6);
//echo "Islamabad Data<br>";
//echo" <br>High temperature <br>";
$hiTemp = array();
foreach($fhtml1->find('#feed-tabs .temp') as $element){
$hiTemp[] = $element;
}
$i=0;
foreach($day6->find('#feed-tabs .temp')as $element) {
if ($i<2) {
$hiTemp[] = $element;
}
$i++;
}
echo json_encode( $hiTemp );
}
Step 2. Use Angular to call your PHP service. Here is an oversimplified example to help you:
function Hello($scope, $http) {
$http.get('/some/where/somefile.php').
success(function(data) {
$scope.islamabadData = data;
});
}
Also you should really be using Accuweather's API instead of doing data scraping.
http://apidev.accuweather.com/developers/
It might help you:
function loadCitiesData($scope, $http) {
$http.get('/some/where/somefile.php?Islamabad=1').
success(function(data) {
$scope.islamabadData = data;
});
$http.get('/some/where/somefile.php?Lahore=1').
success(function(data) {
$scope.LahoreData = data;
});
}
And your somefile.php file:
<?php
if( !empty($_GET['Islamabad']) ){
$fhtml1 = file_get_contents('http://www.accuweather.com/en/pk/islamabad/258278/daily-weather-forecast/258278');
$fhtml1 = str_get_html($fhtml1);
$day6 = file_get_contents('http://www.accuweather.com/en/pk/islamabad/258278/daily-weather-forecast/258278?day=6');
$day6 = str_get_html($day6);
//echo "Islamabad Data<br>";
//echo" <br>High temperature <br>";
$hiTemp = array();
foreach($fhtml1->find('#feed-tabs .temp') as $element){
$hiTemp[] = $element;
}
$i=0;
foreach($day6->find('#feed-tabs .temp')as $element) {
if ($i<2) {
$hiTemp[] = $element;
}
$i++;
}
echo json_encode( $hiTemp );
}elseif( !empty($_GET['Lahore']) ){
// your code, $yourArray = array('something');
// echo json_encode( $yourArray );
}elseif( !empty($_GET['Multan']) ){
// your code, $yourArray = array('something');
// echo json_encode( $yourArray );
}
?>

Paginate list of files in php

I have php code for list all ".swf" files in a folder. (The name of the files is always:
"99-dd-mm-YY_HH-mm-ss.swf", example: "01-19-06-2011_18-40-00.swf".
When I have more than 500 files in the folder is complicated to see and to refresh the page.
I need paginate the list of files.
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type">
<title></title>
<script type="text/javascript">
function submitform()
{
document.myform.submit();
}
</script>
</head>
<body>
<form name="myform" action="some.php" method="post">
<?php
echo "\n<br>\n";
echo "<a href='javascript:this.location.reload();' style='color: #000000; font-weight: normal'>Refresh</a></br>";
echo "<tr>\n<td>\n<a href='javascript:javascript:history.go(-1)'>\n";
echo "<img src='../../inc/img/back.png' alt='Back'";
echo " border=0>\n";
echo "<b> Back</b></a></td>\n";
echo "\n</tr>\n";
echo "\n<br>\n\n<br>\n";
$folder='.';
function order($a,$b){
global $folder;
$directory='.';
return strcmp(strtolower($a), strtolower($b));
}
$folder=opendir($folder);
while($files=readdir($folder)){
$ext = pathinfo($files, PATHINFO_EXTENSION);
if ($ext == 'swf') { //con esta línea saco el nombre index.php del listado
$file[]=$files;
usort($file, "order");
}
}
$n = 0;
foreach($file as $archiv){
$n = $n + 1;
$day = substr($archiv, 3,10);
$day = str_replace("-","/", $day);
$hour = substr($archiv, 14,8);
$hour = str_replace("-",":", $hour);
echo "<img alt='Ver $archiv' src='../../inc/img/video.png'> Video $n, Día: $day, hour: $hour\n ";
echo "<input type='submit' name='xxx' value='$archiv'></td>\n";
echo "\n</tr>\n";
echo "<br>";
}
closedir($folder);
echo "\n<br>\n";
echo "<tr>\n<td>\n<a href='javascript:javascript:history.go(-1)'>\n";
echo "<img src='../../inc/img/back.png' alt='Back'";
echo " border=0>\n";
echo "<b> Back</b></a></td>\n";
echo "\n</tr>\n";
?>
</form>
</body>
</html>
When required to go through lots of folders and files, try the Iterator object. A nice example:
function get_files($dir)
{
$dir = new DirectoryIterator($dir);
$list = iterator_to_array($dir, false);
return array_slice($list, 2);
}
This will get all the file names (if you have php 5.3 or higher) very fast and will do the if dir_exists / file_exists for you! The array_slice so it removes the . and .. directory.
I used this code for simple pagination
<?php
// Include the pagination class
include 'pagination.class.php';
// Create the pagination object
$pagination = new pagination;
// some example data
foreach (range(1, 100) as $value) {
$products[] = array(
'Product' => 'Product '.$value,
'Price' => rand(100, 1000),
);
}
// If we have an array with items
if (count($products)) {
// Parse through the pagination class
$productPages = $pagination->generate($products, 20);
// If we have items
if (count($productPages) != 0) {
// Create the page numbers
echo $pageNumbers = '<div>'.$pagination->links().'</div>';
// Loop through all the items in the array
foreach ($productPages as $productID => $productArray) {
// Show the information about the item
echo '<p><b>'.$productArray['Product'].'</b> 243'.$productArray['Price'].'</p>';
}
// print out the page numbers beneath the results
echo $pageNumbers;
}
}
?>
Here there is pagination class and the example for download:
http://lotsofcode.com/php/php-array-pagination.htm
Thanks for all!
Like #Tessmore said, Spl Iterators are teh awesomesauce. According to the docs, you only need PHP > 5.1 for the basic iterators.
Cross-posting an example --
DirectoryIterator and LimitIterator are my new best friends, although glob seems to prefilter more easily. You could also write a custom FilterIterator. Needs PHP > 5.1, I think.
No prefilter:
$dir_iterator = new DirectoryIterator($dir);
$paginated = new LimitIterator($dir_iterator, $page * $perpage, $perpage);
Glob prefilter:
$dir_glob = $dir . '/*.{jpg,gif,png}';
$dir_iterator = new ArrayObject(glob($dir_glob, GLOB_BRACE));
$dir_iterator = $dir_iterator->getIterator();
$paginated = new LimitIterator($dir_iterator, $page * $perpage, $perpage);
Then, do your thing:
foreach ($paginated as $file) { ... }
Note that in the case of the DirectoryIterator example, $file will be an instance of SplFileInfo, whereas glob example is just the disk path.

Categories