PHP Checkbox delete files from folder - php

I want to delete files from folder called "fajlovi". Multiple and singled delete should work. But it delete first file in folder (0 position in array of files in the folder). If I check any for files it will delete first 4 files instead files I checked. Here is the code:
$a = glob("fajlovi/*");
echo "<br>var_dump of \$a ------------------------<br><pre>";
var_export($a);
echo "</pre>end dump od \$a ------------------------<br><br>";
echo "Number od files in the directory: " . count($a) . "<br>";
echo "<form method='POST' action='" . $_SERVER['PHP_SELF'] . "'><table >";
echo "<th>File name:</th><th>Size MB:</th><th>Delete:</th>";
foreach ($a as $key => $value) {
echo "<tr><td>" . $value . "</td>";
echo "<td>" . round(filesize($value) / 1024 / 1024, 5) . " MB <br></td>";
echo "<td><input type='checkbox' name='checked[]'>" . $img_number = $key + 1 . "</td>";
}
echo "<tr><td colspan=3><input type='submit' name='delete' value='Delete'></td></tr>";
echo "</table></form>";
if (isset($_POST['delete'])) {
$checkbox = $_POST['checked'];
for ($i = 0; $i <= count($a); $i++) {
if (isset($checkbox[$i])) {
if (unlink($a[$i])) {
echo "Successfully deleted file" . $a[$i] . "<br>";
}
}
}
}
if (!empty($_POST['checked'])) {
var_dump($_POST['checked']);
}
1. This is screenshot of the page:
2.then I check images I want to delete:
3. After pressing Delete button, this is the result:
4. And after entering the page again, we can see that wrong images are deleted:

You need to give your inputs a value
<input type='checkbox' name='checked[]' value='{$key}'>
Here's some code to bump you in the right direction.
$files = glob('fajlovi/*');
$indicesToDelete = array_intersect((array)($_POST['checked'] ?? []), array_keys($files));
foreach ($indicesToDelete as $index) {
if (unlink($files[$index])) {
echo "Successfully deleted file" . $files[$index] . "<br>";
}
}
I wouldn't be implementing the deletion like this though. Instead of using the indexes provided by glob() as your method of locating files to delete, you should be using a key that uniquely and definitively identifies the file. At the very least this means using the filepath itself. Consider for example a scenario in which file(s) are added ore removed between when your form displays and you make and submit your selections for deletion. You could end up removing the wrong files.
Instead you might pass the filepath here:
<input type='checkbox' name='checked[]' value='{$value}'>
And then work with them instead of indices.
$files = glob('fajlovi/*');
$pathsToDelete = array_intersect((array)($_POST['checked'] ?? []), $files);
foreach ($pathsToDelete as $filepath) {
if (unlink($filepath)) {
echo "Successfully deleted file" . $files[$index] . "<br>";
}
}
As a final bit of advice:
You should check file_exists(), is_file(), or similar before doing the unlink. You should be doing everything you can to ensure you're only allowing the deletion of the files you intended.

Related

Using php to find the first element of an array and add it the class active to create a tab system with bootstrap.js

I'd like to add an active class with PHP instead of using javascript.
But I probably broke the code somewhere.
I'm using bootstrap.js version 3 and I'm building my tabs using PHP because I need to use my tabs on the control panel in my app.
So essentially I didn't add any javascript or jquery so far, I'm just using the native functions for tabs in bootstrap.js (and jquery):
<?php foreach ($database as $item): ?>
<?php
if (isset($item['associations'])) {
foreach ($item['associations'] as $value) {
echo "<div class='modal' id='des_" . $value['des_id'] . "'>";
echo "<div class='modal-sandbox'></div>";
echo "<div class='modal-box'>";
echo "<div class='modal-body'>";
echo "<div class='close-modal'>✖</div>";
echo "<h3>Credit and values</h3>";
echo "<h5>" . $value["designation_name"] . " - Credit: " . $value["designation_credits"] . "</h5>";
echo "<ul class='nav nav-pills'>";
if (isset($value['credits']) && !is_string($value['credits'])) {
foreach ($value['credits'] as $credits) {
$first_element = reset($value["credits"]);
if (isset($value['credits'])) {
if ($first_element[4] == $credits[4]) {
echo "<li class='active'><a href='tab_" . $credits[4] . "' data-toggle='tab'>Identifier: " . $credits[0] . "</a></li>";
} else {
echo "<li><a href='tab_" . $credits[4] . "' data-toggle='tab'>Identifier: " . $credits[0] . "</a></li>";
}
}
}
}
echo "</ul>";
echo "<div class='tab-content clearfix'>";
if (isset($value['credits']) && !is_string($value['credits'])) {
foreach ($value['credits'] as $credits) {
if (isset($value['credits'])) {
if ($first_element[4] == $credits[4]) {
echo "<div class='tab-pane active' id='tab_" . $credits[4] . "'>";
} else {
echo "<div class='tab-pane' id='tab_" . $credits[4] . "'>";
}
echo "<div class='single-credit'>";
?>
<?=form_open();?>
<?php
echo "<input type='hidden' name='id' value='" . $credits[4] . "'>";
echo "<div>Identifier: <span>" . $credits[0] . "</span></div>";
echo "<input name='edit_credits' type='submit' value='Edit' class='submit'>";
echo "</div>";
echo "</div>";
echo "</div>";
?>
<?=form_close()?>
<?php
}
}
}
echo "</div>";
echo "</div>";
echo "</div>";
echo "</div>";
}
}
?>
<?php endforeach;?>
To explain my code I will start from the list:
Since it's a really complex array, I'm taking the first element with the reset function to add the active class only on that very element.
Then I added the href element to point to the id of the matching div later on, and then I close my list.
Later on, I create another loop and I use the id to match both the list and the div and I used the trick that I used before to add the class active only on my first element of my array.
Everything works except for the fact that, if I click another element of the list, the matching div won't work, the very first element of the array will keep the class active, so I can't switch beteween element.
I need to spot the error.
UPDATE:
The problem that I have with jquery, in this case, is that if I use a toogleClass for example like that:
$(".nav-pills li").click(function(e) {
e.preventDefault();
tab = $(this).find('a').attr('href');
$("#" + tab).toggleClass('active');
});
It won't be able to toggle properly the class on the first element, that one to which I added the class active with php.
I think you miss to change the URL when click it, in the backend (PHP) you need to know where the user is, so, you check the "parameter" and mark active or not the current tab.
For example:
printf("<div class='tab-pane %s' id='...'>", $credits[4] == $_GET['tab'] ? 'active':'');

I have a simple php script for throwing dices, but all dices have the same number

I tried to make a dice script in php that should look like this one:
http://u11626.hageveld2.nl/po/opdracht1b/index.php
this is the link to mine:
http://u10511.hageveld2.nl/po/opdracht1b/index.php
Sorry if the answer is really obvious but i just can't figure out why the script doesn't work.
btw: "knop" means "button",and the pictures that I use as dices are called dobbelsteen1, dobbelsteen2 ..... dobbelsteen 6
<?php
session_start();
if (!isset($_SESSION["d1"]) || !isset($_SESSION["d2"]) || !isset($_SESSION["d3"])) {
$_SESSION["d1"]=0;
$_SESSION["d2"]=0;
$_SESSION["d3"]=0;
}
elseif (isset($POST["knop1"])) {
$_SESSION["d1"]=0;
}
elseif (isset($POST["knop2"])) {
$_SESSION["d2"]=0;
}
elseif (isset($POST["knop3"])) {
$_SESSION["d3"]=0;
}
elseif (isset($POST["knop4"])) {
$_SESSION["d1"]=0;
$_SESSION["d2"]=0;
$_SESSION["d3"]=0;
}
echo "d1 =" . $_SESSION["d1"];
echo "d2 =" . $_SESSION["d2"];
echo "d3 =" . $_SESSION["d3"];
if ($_SESSION["d1"]==0) {
$f = rand(1,6);
}
if ($_SESSION["d2"]==0) {
$g=rand(1,6);
}
if ($_SESSION["d3"]==0) {
$h=rand(1,6);
}
echo $f;
for ($r=1; $r<4; $r++) {
if (!$f==0) {
$f = 0;
echo "
<div align='center'>
<img src='dobbelsteen" . $f . ".gif'>
<form method='post'>
<input type='submit' name='knop1' value='Dobbelsteen gooien'>
</form>
";
}
elseif (!$g==0) {
$g = 0;
echo "
<div align='center'>
<img src='dobbelsteen" . $g . ".gif'>
<form method='post'>
<input type='submit' name='knop2' value='Dobbelsteen gooien'>
</form>
";
}
elseif (!$h==0) {
$h = 0;
echo "
<div align='center'>
<img src='dobbelsteen" . $h . ".gif'>
<form method='post'>
<input type='submit' name='knop3' value='Dobbelsteen gooien'>
</form>
";
}
}
?>
i have written what i consider an optimal script for this dice throwing exercise you are doing. I am giving you all the answers here but hopefully you will research my approach and learn from it.
<?php
//Start the php session
session_start();
//Initialise local dice array
//Check the session variable for already set values, if not set a random value
//Use TERNARY OPERATORS here to avoid multipl if else
$dice = array(
0 => (!empty($_SESSION['dice'][0])) ? $_SESSION['dice'][0] : rand(1, 6),
1 => (!empty($_SESSION['dice'][1])) ? $_SESSION['dice'][1] : rand(1, 6),
2 => (!empty($_SESSION['dice'][2])) ? $_SESSION['dice'][2] : rand(1, 6)
);
//If form has been submitted, and our expected post var is present, check the dice we want to role exists, then role it
//$_POST['roll_dice'] holds the index of the local dice value array element we need to update
if(!empty($_POST['roll_dice']) && !empty($dice[intval($_POST['roll_dice'])])){
$dice[intval($_POST['roll_dice'])] = rand(1, 6);
}
//Save the updated values to the session
$_SESSION['dice'] = $dice;
//Loop over the dice and output them
foreach($dice as $dice_index => $dice_val){
echo "<div class='dice' style='height:100px;width:100px;background-color:red;text-align:center;margin-bottom:50px;padding-top:10px;'>";
echo "<p style='style='margin-bottom:20px;'>".$dice_val."</p>";
echo "<form method='post'>";
echo "<input type='hidden' name='roll_dice' value='".$dice_index."' />";
echo "<input type='submit' value='Roll Dice' />";
echo "</form>";
echo "</div>";
}
?>
To add a new dice simply increase the size of the $dice array. For example the next one would be:
3 => (!empty($_SESSION['dice'][3])) ? $_SESSION['dice'][3] : rand(1, 6)
and then 4, and so on.
I hope this helps.
There are couple of issues with your script, as #Marc B has said "you never save the random numbers back into the session" also you are accessing the post data using $POST where as it should be $_POST, hope that can help you fixing your script.

PHP multi upload files with custom title

I'm having a problem with my MySQL insert. When I upload a file, data like "filename", "time", and "gid" are inserted correctly. But "title" is empty.
Why is the "title" not being inserted?
<?php
$max_no_img = 10; // Maximum number of images value to be set here
echo "<form method=post action='' enctype='multipart/form-data'>";
echo "<table border='0' width='400' cellspacing='0' cellpadding='0' align=center>";
for ($i = 1; $i <= $max_no_img; $i++) {
echo " <tr><td><input type='text' name='title[]'></td><td><input type=file name='images[]' class='bginput'></td></tr>";
}
echo "<input type='hidden' name='gid' value='$info[id]'>";
echo "</table>";
echo "<br /> <center><input type=submit value='Dodaj sliku'></center>";
echo "</form>";
while (list($key, $value) = each($_FILES['images']['name'])) {
// echo $key;
// echo "<br />";
// echo $value;
// echo "<br />";
if (!empty($value)) { // this will check if any blank field is entered
$time = time();
$gid = addslashes($_POST['gid']);
$title = $_POST['title'];
$filename = rand(1, 100000) . $value; // filename stores the value
$filename = str_replace(" ", "_", $filename); // Add _ inplace of blank space in file name, you can remove this line
$add = "slike/$filename"; // upload directory path is set
// echo $_FILES['images']['type'][$key]; // uncomment this line if you want to display the file type
// echo "<br />"; // Display a line break
copy($_FILES['images']['tmp_name'][$key], $add);
mysql_query("INSERT INTO slike (title,slika,time,gid) VALUES ('$title','$filename','$time','$gid')") or die(mysql_error());
echo "Uspesno pritisnite <a href='/admin/?page=gall&id=$info[id]'>ovde</a>";
// upload the file to the server
chmod("$add", 0777); // set permission to the file.
}
}
}
}
Just as your script handles multiple uploaded images, each image has a corresponding title input.
<input type='text' name='title[]'>
So, the "title" data will be posted as an array:
Array (
[0] => title1
[1] => title2
[2] => title3
[3] => title4
)
You'll need to handle the array of titles appropriately, by using a key that corresponds to the array of uploaded images to reference each associated title. From the looks of your code, you may be able to use the $key variable that is defined in your while loop, like so:
$title = $_POST['title'][$key];
Note: There also seem to be a couple of extra closing braces } in your PHP code.

adding multiple files PHP

I have the working script below but instead of image 1, image 2, image 3, image 4 being next to the boxes I want different names for each. Is there an easy way to do this?
Thanks in advance!!
Also where would I put
header("Location: thankyou.php");
exit();
Because at the moment after putting this in, it just directs straight to the thankyou.php not the page below (document.php)
<?php
$max_no_img = 4; // Maximum number of images value to be set here
echo "<form method=post action='' enctype='multipart/form-data'>";
echo "<table border='0' width='400' cellspacing='0' cellpadding='0' align=center>";
for ($i = 1;$i <= $max_no_img;$i++) {
echo "<tr><td>Images $i</td><td>
<input type=file name='images[]' class='bginput'></td></tr>";
}
echo "<tr><td colspan=2 align=center><input type=submit value='Add Image'></td></tr>";
echo "</form> </table>";
while (list($key, $value) = each($_FILES['images']['name'])) {
//echo $key;
//echo "<br>";
//echo $value;
//echo "<br>";
if (!empty($value)) { // this will check if any blank field is entered
$filename = rand(1, 100000) . $value; // filename stores the value
$filename = str_replace(" ", "_", $filename);
$add = "upload/$filename"; // upload directory path is set
copy($_FILES['images']['tmp_name'][$key], $add);
echo $add;
// upload the file to the server
chmod("$add", 0777); // set permission to the file.
}
}
?>
</body>
</html>
After this line:
$max_no_img = 4;
Define an array with the names you're willing to give to each image:
$imgs_names = array('name for first image' , 'name for second image' , 'name for third image'); //and so on...
and instead of:
echo "<tr><td>Images $i</td><td>
write:
echo "<tr><td>Images ".$imgs_names[$i-1]."</td><td>
About using header , there's a problem since you already used echo.
Add ob_start() at the beginning of the file and ob_flush() at the end of the file,
now you can add the header() even after sending output.
EDIT2: Regarding your comment , there's an alternative way for redirection.
Add:
$submit = true;
After:
chmod("$add", 0777); // set permission to the file.
And after:
}
}
Add:
if(isset($submit) && $submit)
{
echo '<meta http-equiv="refresh" content="0; url=http://www.yoursite.com/thankyou.php">';
}

I want to increment a value from outside a php block

Basically its a web page where someone would press a button to increment the $selection variable. Globals and statics do not seem to work.
Code looks like this:
<?php
if(isset($_POST['next']))
{
displaynext();
}
else
{
global $image_folder = "/images/";
echo "global declared";
global $selection;
$selection = 1;
}
function displaynext()
{
$selection++;
if (file_exists($image_folder."/".$selection.".png")) {
echo "<img src=\"$image_folder/".$selection.".png\">";
}
else {
echo "No next image was found for $selection in ".$image_folder."/".$selection.".png";
}
?>
<form action="<?=$_SERVER['PHP_SELF'];?>" method="post">
<input type="submit" name="next" value="Next">
</form>
Once PHP runs and the output is sent to the client, the code will not run unless the page is requested again from the server. You could create a session variable and use that to store the variable across page requests. You need to either access the page again or perform an AJAX request to call your PHP code again.
Instead of using Global, why don't you use a $_SESSION var?
Put:
global $selection
inside your function, so:
global $selection;
$selection++;
Just use another form element.
<input type=hidden name=selection value=1>
Do a sanity check like is_numeric on $_POST['selection'] before displaying the image tag. If $_POST['selection'] is set, increment it for the input tag above.
Full example:
<?php
$selection = 0;
$image_folder = "images/";
if (isset($_POST['selection'])) {
$userSelection = $_POST['selection'];
if (is_numeric($userSelection) && file_exists($image_folder . $userSelection)) $selection = $userSelection;
}
echo "<img src=\"images/" . $selection . ".png\">";
echo "<form action=\"" . $_SERVER['PHP_SELF'] . "\" method=post>";
echo "<input type=hidden name=selection value=\"" . ($selection + 1) . "\">";
echo "<input type=submit name=subnext value=\"Next\">";

Categories