I'm trying to create a simple dynamic gallery with a radio button under each image to allow the user to select an image and submit the form. I'm not concerned with processing the form yet, I'd just like to figure out how to dynamically generate the form. Currently I'm creating the gallery with this;
<?php
$images = "image_gallery/";
$big = "big/";
$cols = 2;
if ($handle = opendir($images)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." && $file != rtrim($big,"/")) {
$files[] = $file;
}
}
closedir($handle);
}
$colCtr = 0;
echo '<table width="100%" cellspacing="3"><tr>';
foreach($files as $file)
{
if($colCtr %$cols == 0)
echo '</tr><tr><td colspan="2"><hr /></td></tr><tr>';
echo '<td align="center"><img src="' . $images . $file . '" /></td>';
$colCtr++;
}
echo '</table>' . "\r\n";
?>
It seems as though I should create the radio buttons inside of the foreach loop, but I'm not sure exactly where, or how.
I appreciate any help.
in your foreach loop:
foreach($files as $file){
if($colCtr %$cols == 0)
echo '</tr><tr><td colspan="2"><hr /></td></tr><tr>';
echo '<td align="center"><img src="' . $images . $file . '" /><input type="radio" name="should be common if to choose one between mutiples" value="the value you want to send via form" /></td>';
$colCtr++;
}
echo '</table>' . "\r\n";
Related
I need to have a php script that allows me to scan a directory and then, delete the files from it, my code works just fine, it lists all I need but, my problem is that I need to delete only a specific file from that directory and this script scans everything, in this case i am trying to delete only the .sql files created. However this script lists all types of files.
I leave my code below:
<?php
$fid= $_POST['fid'];
if (("submit")&&($fid != "")) {
foreach($fid as $rfn) {
$remove = "$dire/$rfn";
unlink($remove);
}
}
$handle=opendir($dire);
while (($file = readdir($handle))!== false){
if ($file != "." && $file != "..") {
$size = filesize("$dire/$file");
$list .= '<table class="table table-bordered table-dark table-hover" cellspacing="0" width="100%">';
$list .= '<tbody>';
$list .= '<tr style="text-transform:uppercase;">';
$list .= '<td><small>'.$file.'</small></td>';
$list .= '<td align="center"><small><input type="checkbox" class="form-control" name="fid[]" value="'.$file.'"></small></td>';
$list .= '</tr>';
$list .= '</tbody>';
$list .= '</table>';
}
}
closedir($handle);
echo $list;
?>
As you can see, this code works just fine, not pretty I know but I need to have a way to show only my SQL files and not the other types of files.
If you just want to check the file extension before deletion:
<?php
foreach ($fids as $fid) {
if (pathinfo($dire . '/' . $fid)['extension'] == 'sql') {
unlink($dire . '/' . $fid);
}
}
?>
Otherwise, you can scan your directory for only .sql with GLOB()
<?php
$dire = 'my_dir';
if (!empty($_POST['fid'])) {
$fids = $_POST['fid'];
foreach ($fids as $fid) {
unlink($dire . '/' . $fid);
}
}
?>
http://php.net/manual/en/function.glob.php
<?php
$files = GLOB($dire . '/*{.sql}', GLOB_BRACE);
?>
<?php if ($files): ?>
<?php foreach($files as $file): ?>
<table class="table table-bordered table-dark table-hover" cellspacing="0" width="100%">
<tbody>
<tr style="text-transform:uppercase;">
<td><small><?= basename($file); ?></small></td>
<td align="center"><small><input type="checkbox" class="form-control" name="fid[]" value="<?= basename($file); ?>"></small></td>
</tr>
</tbody>
</table>
<?php endforeach; ?>
<?php endif; ?>
I came across PHP's RecursiveDirectoryIterator some time ago. This built-in class will let you iterator through a directory and it's subdirectories and perform any action you want on the files in it.
Take a look at the example below on how to implement this:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// The directory to remove files from
$directory = $_POST['directory'];
// The extension se are looking for
$extension = $_POST['extension'];
// Construct the iterator
$it = new RecursiveDirectoryIterator($directory);
// Loop through files
foreach(new RecursiveIteratorIterator($it) as $file) {
if ($file->getExtension() == $extension) {
echo 'Removing ' . $file . "\n";
unlink($file);
}
}
}
Implementation
You can replace your code with the following script. Note that I have used the DirectoryIterator in this case because you only want to iterate through a single directory.
<?php
/**
* Directory overview
*/
// The directory to remove files from
$directory = '/path/to/directory';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
foreach ($_POST['fid'] as $filePath) {
unlink $filePath;
}
}
?>
<table class="table table-bordered table-dark table-hover" cellspacing="0" width="100%">
<thead>
<tr>
<th>File</th>
<th></th>
</tr>
</thead>
<tbody>
<?php foreach (new DirectoryIterator($directory) as $file): ?>
<?php if ($file->isDot() || !$file->isFile()) continue; ?>
} <tr style="text-transform:uppercase;">
<td><small><?= $file; ?></small></td>
<td align="center"><small><input type="checkbox" class="form-control" name="fid[]" value="<?= $file->getPathName(); ?>"></small></td>
</tr>
</tbody>
</table>
Resources
DirectoryIterator - Manual
I'm trying to make a gallery with PHP. I want to get all of the images out of a folder and then display them in rows of 3. I kind of have it working but the first 2 images mess up.
This is what I've tried:
$images = glob("$_SERVER[DOCUMENT_ROOT]/gallery/img*.{png,jpg,gif}", GLOB_BRACE);
echo '<table width="100%>';
$count="-1";
foreach($images as $image) {
if ($count%3 == 1) {
echo '<tr>';
}
$url=str_replace("/home/#####/public_html/gallery", "", $image);
echo '<td width="33%"><div class="gallery">';
echo '<img onclick="window.location='.$url.'" src="'.$url.'" alt="Image Alt" width="400" height="300">';
echo '</div></td>';
if ($count%3 == 3) {
echo '</tr>';
}
//echo $count;
$count++;
//echo "|".$count;
}
if ($count%3 != 1) {
echo ',</tr>';
}
echo '</table>';
//echo print_r($images);
This works kind of but it makes this:
(These are just stock photos, the real photos are a bit.. offensive)
I know I'm doing something wrong but I don't know what!
There were some errors in your code (see comments). Maybe try this:
$images = glob("$_SERVER[DOCUMENT_ROOT]/gallery/img/*.{png,jpg,gif}", GLOB_BRACE);
echo '<table style="width:100%">'; // error was here (missing ")
$count = 0; // error was here (counter = "-1")
foreach ($images as $image) {
// start <tr> on 0
if ($count == 0) {
echo '<tr>';
}
$url=str_replace("/home/#####/public_html/gallery/", "", $image);
echo '<td style="width:33%"><div class="gallery">'; // alternative
echo '<img onclick="window.location='.$url.'" src="'.$url.'" alt="Image Alt" width="400" height="300">';
echo '</div></td>';
// end tr at 3
if ($count == 3) {
echo '</tr>';
// reset counter
$count = -1;
}
$count++;
}
echo '</table>';
I think you have trouble with your $count initial value.
Try this:
$count="3";
foreach($images as $image) {
if ($count%3 == 0) {
echo '<tr>';
}
$count++;
...
Hello Stackers,
I'm having a question about jQuery. I have the following code, and I want that if I select one of the options, that the Image SRC changes to that path. (Direct, without any other clicks). Is this possible? (It's a kind of Live Preview of the selected image) I Tried, but it doesn't seem to be working.
The Form and Image Display
<b>Afbeelding</b><br><select name="choose" id="choose">
<?php
if ($handle = opendir('C:/inetpub/wwwroot/magieweb/images/news'))
{
while (false !== ($file = readdir($handle)))
{
if ($file == '.' || $file == '..')
{
continue;
}
echo '<option value="' . $file . '"';
if (isset($_POST['topstory']) && $_POST['topstory'] == $file)
{
echo ' selected';
}
echo '>' . $file . '</option>';
}
}
?>
</select><br><br>
<ul style="border: 1px solid #2087A1; list-style-type: none; margin-right:40px; min-height:30px;">
<li><strong style="color:#2087A1; margin-top:3px; margin-bottom:3px;">Nieuwsafbeelding Preview</strong></li>
<li><img id="blah" src=""></li>
</ul><br><br>
My jQuery
$('#choose').change(function(){
$('#blah').attr('src', this.value);
alert(this.value);
});
Thanks in Advance
Updated: retrieves selected option value from select box on change.
$('#my_select_box').change(function(){
$('#my_changing_image').attr('src', $('#my_select_box').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="my_select_box">
<option value="http://g-ecx.images-amazon.com/images/G/01/img15/pet-products/small-tiles/23695_pets_vertical_store_dogs_small_tile_8._CB312176604_.jpg">something</option>
<option value="https://pbs.twimg.com/profile_images/378800000532546226/dbe5f0727b69487016ffd67a6689e75a.jpeg">something else</option>
</select>
<img id="my_changing_image" src="http://g-ecx.images-amazon.com/images/G/01/img15/pet-products/small-tiles/23695_pets_vertical_store_dogs_small_tile_8._CB312176604_.jpg" />
https://jsfiddle.net/hqk1r8fk/1/
Good Day Everyone
Ok, so I have done as much as I understand and need some direction and help. Currently i'm very new to html/php so please bear with me. The plan is to list the text files from a Dir in a dropdown list, this I have done, now I would like to display the text file in the same page in a table upon submit button press. This is what I have so far, any input welcome as I am still learning!
The bash script is just a grep function to grab specific lines from the original file and copy it to /tmp.
Thanks Again
<html>
<head>
<title>Data Request</title>
</head>
<body>
<h1 align="center">Dispatch Report</h1>
<h2 align="center">Wrong Arrives Report</h2>
<table align="center" border="2">
<tr>
<td>Select Shift<br>
<form name="shiftfrm" id="shiftfrm">
<select name="shiftlist" id="shiftlist">
<option value="" selected="selected">--------</option>
<?php
$dir = opendir ("/var/www/files/");
while (false !== ($file = readdir($dir))) {
if (strpos($file, '.txt',1)) {
echo '<option value="' . $file . '">' . $file . '</option>';
}
}
?>
</select>
<input type="submit" id="submit" value="Submit"/>
<?php
if( ($handle = fopen( '/tmp/sh130418n.txt', 'r' )) !== false )
{
$output = '<table align="center" width="" border="2">';
while( ($data = fgetcsv( $handle )) !== false )
{
$output .= '<tr>';
foreach( $data as $value )
{
$output .= sprintf( '<td>%s</td>', $value );
}
fclose( $handle );
$output .= '</table>';
}
echo $output;
?>
</td></tr>
</table>
<?php
$output = exec('/var/www/cgi-bin/manualexceptget.sh');
echo "<pre>$output</pre>";
?>
</body>
</html>
assume <form method="post" action="">. Augment your file reading code:
if(!empty($_POST['shiftlist'])) {
$file = 'files/'.$_POST['shiftlist'];
if(file_exists($file)) {
if( ($handle = fopen( $file, 'r' )) !== false )
{
$output = '<table align="center" width="" border="2">';
while( ($data = fgetcsv( $handle )) !== false )
{
$output .= '<tr>';
foreach( $data as $value )
{
$output .= '<td>'.$value.'</td>';
}
$output .= '</table>';
}
echo $output;
fclose( $handle );
}
}
}
Edit: Fixed the isset() issue stated below. Changed some code, $handle was closed before reading was finished.
Edit2: I just put this in editor and saw many html tags, that were not placed properly (e.g. form not closed). Working sample at pastebin (tested on xampp)
Try Like this for (.txt) files..
<html>
<head>
<title>Data Request</title>
</head>
<body>
<h1 align="center">Dispatch Report</h1>
<h2 align="center">Wrong Arrives Report</h2>
<table align="center" border="2">
<tr>
<td>Select Shift<br />
<form name="shiftfrm" id="shiftfrm" method="POST">
<select name="shiftlist" id="shiftlist">
<option value="" selected="selected">--------</option>
<?php
$dir = opendir("files/");
while (false !== ($file = readdir($dir)))
{
if (strpos($file, '.txt', 1))
{
echo '<option value="' . $file . '">' . $file . '</option>';
}
}
?>
</select>
<input type="submit" name="submit" id="submit" value="Submit"/>
<br />
<?php
if (isset($_POST['submit']) && isset($_POST['shiftlist']))
{
if ($handle = file_get_contents('files/' . $_POST['shiftlist']))
{
$output = '<table align="center" width="" border="2">';
$output .= '<tr><td>';
echo $handle;
$output .= '</tr></td>';
$output .= '</table>';
} else
{
echo "No Content";
}
} else
{
echo "Please select the file";
}
?>
</td>
</tr>
</table>
</body>
</html>
I am working on a PHP Gallery application, and need some help here. Actually I have a page where images from a specific directory are displayed directly. With each one of the images displayed there is a dynamically generated submit button that will be used to delete respective images separately.
Every image has its own submit button, that will be used to delete that image. Being new to php I need some method that can be called to delete only that image from the actual or physical directory.
There is a similarity between image and button that I have coded it such that every image and its respective button has names such as "img_1" and its button is "del_1".
<form id="albumGallery" name="albumGallery" method="POST">
<?php
$dir = htmlspecialchars($_GET["p"]) . "/";
$imgs = array();
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if (!is_dir($file) && preg_match("/\.(bmp|jpe?g|gif|png)$/", $file)) {
array_push($imgs, $file);
}
}
closedir($dh);
} else {
die('cannot open ' . $dir);
}
$i=0;
echo "<div id='images'>";
foreach ($imgs as $idx=>$img) {
//$class = ($idx == count($imgs) - 1 ? ' class="last"' : '');
echo '<table style="float: left; border: 1px solid #EFEFEF; border-radius: 5px; padding: 5px; margin: 5px;"><tr><td><a href="'. $dir . $img .'" rel="example_group" ><img src="' . $dir . $img . '" alt="' . $img . '" id="'. "img_" . $i .'"/>
</a></td></tr><tr><td><input type="submit" class="ctrlDelete" value="" id="'. "del_" . $i .'"/></td></tr></table>';
$i++;
}
echo "</div>";
?></form>
So, I need to make a method so that each button deletes its respective image and the form is posted back to self.
For your issue, it is better to use anchors. You can style them as pseudo-buttons, if you want. Then just generate links like delete.php?id=23, which will execute the appropriate deletion script with $_GET argument passed.
Below is the very simple implementation:
<table>
<tr>
<td>Title</td>
<td>Image</td>
<td>Actions</td>
<tr>
<?php
foreach ($table as $row)
{
echo "<tr>";
echo "<td>".$row['title']."</td>";
echo "<td>".$row['image']."</td>";
echo "<td>";
echo "<a href='delete.php?id=".$row['id']."'>Delete</a>";
echo "<a href='edit.php?id=".$row['id']."'>Edit</a>";
echo "</td>";
echo "</tr>";
}
?>
</table>
delete.php and edit.php should contain the following code at the very end:
<?php
header("Location: http://www.example.com/");
?>
#Edward Ruchevits
Thanks for your help :D,
I did not use the header(); method but used the javascript's settimeout(); to redirect my page. Here is my code...
<script type="text/javascript">
setTimeout("window.location = '<?php echo $_SERVER['HTTP_REFERER'] ?>'", 1);
</script>
<?php
$path = htmlspecialchars($_GET["p"]);
unlink($path);
?>
I suggest adding the form tag inside your foreach loop and post each of those forms to self. Each form can simply include a hidden field with the image ID. Then each time the page loads, you can simply check the $_POST variable for the image and delete that before serving up your page.
Alternately, you might consider using checkboxes next to the images - then one form and one submit button can action multiple deletions in one - far more efficient in my opinion.
Hope this helps!