PHP multi upload files with custom title - php

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.

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.

PHP-how to send data to another php-sql page and recive an chart image on the same page

PHP-how to send data to another php-sql page and recive an chart image on the same page
hi guys. i have an problem and i dont know how i could solve that. i have an mainpage, where i want to put some data in an input field, which would send
the data to an other page to create the chart. ok. thats not the problem. it works fine, if i open the secound page. the chart img is created. but if i want to stay on the mainpage klicking the button and recive the img from the secound page, the img is empty and i dont know how to realize that.
here is an short code of the mainpage.php
echo "<form action='#' method='post' type='text'>";
echo "Abzufragendes Jahr [JJJJ]:";
echo '<input type="text" name="eingabe_1" value="">';
echo "<input type='submit' name='eingabe_2' value='DB Abfrage'/>";
echo "<input type='submit' name='ausgabe_statistik' value='Charts erstellen'
formaction='#' formmethod='post'/></br></br></br></br>";
echo "</form>";
//Versuch das Bild zu erzeugen
if(isset($_POST['eingabe_1']) && isset($_POST['ausgabe_statistik'])) {
echo "<img src='charts/charts_jahr.php'> </br>";
}
and the secound page consists
include("../../PHP/pChart2.1.4/class/pData.class.php");
include("../../PHP/pChart2.1.4/class/pDraw.class.php");
include("../../PHP/pChart2.1.4/class/pImage.class.php");
include("../../SQL/log-in.php");
mysql_select_db(MYSQL_DATENBANK) or die("Auswahl der Datenbank fehlgeschlagen");
for ($a = 1 ; $a <= 365 ; $a++) {
$kalenderwoche[] = $a;
}
$var = $_POST['eingabe_11'];
$var_jahr = "j" . $var;
$Result = mysql_query("SELECT sum(gewicht) as gewicht_1 FROM $var_jahr group by datum",$db_link);
while($row = mysql_fetch_array($Result))
{
$gewicht[] = $row["gewicht_1"];
$fett[] = $row["fett"];
}
//chartpart
$myData = new pData();
$myData->addPoints($gewicht,"Serie1");
..
.
i thought over another solution to save the temp var in he sql and get the value for $var_jahr out of them. but i think thats not the solution right?
br and many thx for an solution!
My solution:
if ( isset($_POST['statistik_gewicht']) ) {
$var22 = $_POST['eingabe_1'];
mysql_query("update variablen set var1 = $var22 where id = 1");
mysql_query("update variablen set var_gewicht = 1 where id = 1");
echo "<div align='center'><img src='charts/charts_jahr.php'></div> </br>";
}
Not well, but it works! Write an tmp var over
echo '<td colspan="3">Abzufragendes Jahr [JJJJ]'; echo '<input type="text" name="eingabe_1" value="">';

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.

Show Array of Images

I'm trying to display image in 5 by 3 table.
I'm able to display the images if all empty(blank.png).
Here is the code
<?PHP
$ds ='\image';
$imagefile = array("EX_W1_01.png", "EX_W1_02.png", "EX_W2_01.png","EX_W3_01.png");
echo "<pre>"; print_r($imagefile);
$file = 'blank.png';
$d = $ds.$file;
echo "<table border = 1 width=\"540px\" cellspacing=\"0px\" cellpadding=\"0px\">";
for($row=1;$row<=5;$row++){
echo "<tr>";
for($col=1;$col<=3;$col++){
// echo"<td height=60px>W$row</td>";
//if()
echo"<td height=60px>W$row<img border = 1 height = 120 width = 120 src = $d ></td>" .PHP_EOL;
}
echo "</tr>";
}
echo "</table>";
?>
I want to display the images base on middle file name array $imagefile eg W1, W2 and if not in array, I will display the blank.png.
I was able to get the middle file name by this code, but I cannot display the images in correct row/col.
for($i=0;$i<count($imagefile); $i++) {
$wd = substr($imagefile[$i], 3, strpos($imagefile[$i], '_'));
}
Can you try this,
Based on your code add these when you echo the image,
$wd = substr($imagefile[$i], 3, strpos($imagefile[$i], '_'));
if($wd == *the increment either row or col*)
{
echo"<td height=60px>W$row<img border = 1 height = 120 width = 120 src = $d ></td>" .PHP_EOL;
}
else
{
echo"<td height=60px>No image</td>" .PHP_EOL;
}
See if it works.
Here it is
<?php
$ds ='/image';
$imagefile = array("EX_W1_01.png", "EX_W1_02.png", "EX_W2_01.png","EX_W3_01.png");
//echo "<pre>"; print_r($imagefile);
$default = 'blank.png';
?>
<table border = 1 width=\"540px\" cellspacing=\"0px\" cellpadding=\"0px\">
<?php
for($row=1;$row<=5;$row++){
?>
<tr>
<?php
for($col=1;$col<=3;$col++){
// construct the file name
$filename = 'EX_W' . $row . '_0' . $col . '.png';
// set the default image file
$imgPath = $ds . '/' . $default;
// in case the file name exists in your array with images,
// set the correct path to the image
if (in_array($filename, $imagefile)) {
$imgPath = $ds . '/' . $filename;
}
?>
<td height=60px>
<img border="1" height="120" width="120" src="<?php echo $imgPath; ?>"/>
</td>
<?php } ?>
</tr>
<?php
}
?>
</table>
As you can see I also prefer to "embed" the php code in the HTML. It makes no sense to me outputting HTML code through the PHP engine if it can be parsed as is ;-)

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">';
}

Categories