I want to increment a value from outside a php block - php

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\">";

Related

PHP Checkbox delete files from folder

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.

How run code when clicking on a looped button

I need to show a button for each value and do some function,
The following code is working for displaying the button only
but it doesn't show the result of the function after the button
$ids = [1,2,3,4,5,6];
foreach( $ids as $id ) {
$post_url = get_the_permalink($id);
echo $post_url."<input type='submit' name='doit' value='Change'><br>";
$doit = $_POST['doit'];
if(isset($_POST['doit'])){
echo get_post_field( 'post_name', $id)."<br>";
}
}
Can you try this solution?
I added an ID to the name field so when you click the button it runs only the if statement of this button.
Also make sure that the buttons are wrapped inside a form tag with a method attribute.
echo "<form method='post'>";
$ids = [1,2,3,4,5,6];
foreach( $ids as $id ) {
$post_url = "test.com";
echo "$post_url <input type='submit' name='doit_$id' value='Change'><br>";
if(isset($_POST['doit_'. $id])){
echo $id . "_RUNNING <br>";
}
}
echo "</form>";
Also $doit = $_POST['doit']; prints a NOTICE in php when it is not defined, it is better to check if $_POST['doit'] isset before assigning it to a variable.

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.

post form to database without leaving the page in a php echoed form

I think I really dug myself a hole here. I have a php file that creates a "notification list" with checkboxes. I want it to work in a way so the user will check the notification he read (in order to clean up his/her list), then the form will submit- by checking, and the 'notification' table in the database will be updated. My problem: it works, but it submits to the notification.php file. I don't want that.
I read several ways to solve it with AJAX but they require the checkboxes id's and as you can see below, The id's are being created by the php...
echo "<form name='noteform' id='noteform' action='notifications.php' method='POST'>";
echo "<ul>";
while($row = mysqli_fetch_array($result)) {
if ($row['type'] == 'group_request') {
echo "<li><input type='checkbox' name='check[]' value='" . $row['id'] . "' onclick='document.noteform.submit()' /><p1>" . $row['text'] . " | Approve? </li>";
}else{
echo "<li><input type='checkbox' name='check[]' value='" . $row['id'] . "' /><p1>" . $row['text'] . "</p1></li>";
}
}
echo "</ul>";
echo "</form>";
$check = isset($_POST['check']) ? $_POST['check'] : array();
foreach($check as $ch) {
$result = mysqli_query($conn, "UPDATE notifications SET `read`=1 WHERE id='$ch'");
}
?>
ps. The if($row['type'] == 'group_request') is just because that's the only notification type i made so far...
You don't have to by any means, but it would make your life a lot easier IMO. Here is a quick solution using jQuery:
$('#noteform').on('submit', function(event){
// Validate or whatever
// Submit
$.ajax({
'type': 'post',
'data': $(this).serialize(),
'url': 'path-to-notification.php',
'timeout': 50000
}).done(function(response) {
// success
}).fail(function(error) {
// error
});
event.preventDefault();
});
EDIT
Let's say you have "index.php", and within that file you have your form:
index.php
<?php
....
<form>
....
</form>
....
?>
Then either in and external .js file, or within index.php inside of a <script> tag, you would have the ajax method(s) above.
Next, you would have notification.php that would handle your form action(s).
notifications.php
if(isset($_POST['check'])
{
// check the value
// handle the form element
}
// sanitize the data
// run your update query
// return success/fail to the javascript
?>
In a nutshell, that's how I would set things up. Hope that helps!

Sharing a session variable between multiple php scripts

My question is that when I copy my array elements between different PHP scripts using session variables, nothing gets printed out. The following are my two PHP files.
file1.php
<?PHP
session_start();
$SQL = "SELECT * FROM tblquestions";
if ($db_found) {
$result = mysql_query($SQL);
$numRows = mysql_num_rows($result); //return number of rows in the table
echo '<FORM NAME ="form1" METHOD ="POST" ACTION ="file2.php">';
for ($i = 1; $i <= 2; $i++)
{
$db_field = mysql_fetch_assoc($result);
$qID[$i] = $db_field['QID'];
$question[$i] = $db_field['Question'];
$A[$i] = $db_field['qA'];
$B[$i] = $db_field['qB'];
$C[$i] = $db_field['qC'];
echo '<P>';
print $question[$i];
echo '<P>';
echo "<INPUT TYPE = 'Radio' Name = '".$qNum."' value= 'A'>";
print $A[$i];
echo '<P>';
echo "<INPUT TYPE = 'Radio' Name = '".$qNum."' value= 'B'>";
print $B[$i];
echo '<P>';
echo "<INPUT TYPE = 'Radio' Name = '".$qNum."' value= 'C'>";
print $C[$i];
//if (isset($_POST[$name_Value]))
$survey_Answers[$i-1] = $_POST[$qNum];
print '</BR>'.$survey_Answers[$i-1]."</BR>";
$question_Number = ltrim($qNum,'q');
$question_Number++;
$qNum ='q'.$question_Number;
}
echo '<p>';
$_SESSION['answers'] = $survey_Answers;
echo '<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Click here to vote">';
echo '</form>';
?>
On my Second file (file2.php), I have the following:
<?PHP
session_start();
if (isset($_POST['Submit1'])) {
$results = $_SESSION['answers'];
print $results[0];
}
?>
However, on my file2.php I get the following error: Undefined offset: 0 and nothing gets printed out.
echo '<p>';
session_start();
that canĀ“t work, session_start has to be called before any output!
if you put session_start() at the beginning of your file, you should be all right.
To use cookie-based sessions, session_start() must be called before outputing anything to the browser.
source: http://php.net/manual/en/function.session-start.php
You need to call session_start() before you output anything. It is a best practice to place it at the beginning of your script before you output anything.
Please Add the below code to every page you want to use the session data.Other wise it will return an error .
<?php
session_start();
?>
in file1.php session_start(); should be first line of the code same as in file2.php
There is a comment on the PHP manual page for session_start() which sounds very similar to your problem. http://php.net/manual/en/function.session-start.php#65944
It says that an array with integer keys assigned either as a straight array or using the integers will fail and the data will not pass to the next page.
Modify your code to use strings as keys.

Categories