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">';
}
Related
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.
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.
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.
I have a page that I have used to retrieve some excel data written in php... by using phpexcel... this part provides me company information
echo '<form action="final.php" method="post">';
echo "<table border='1'>";
for ($rowcount = $rowCompanyInfoStart; $rowcount <= $rowCompanyInfoEnd; $rowcount++)
{
//$data = $objWorksheet->rangeToArray('A1:' . $maxCell['column'] . $maxCell['row']);
$rangeCoordinates = $colCompanyInfoStart . $rowcount . ':' . $colCompanyInfoEnd . $rowcount;
$rowData = $sheet->rangeToArray($rangeCoordinates, NULL, TRUE, FALSE);
echo "<tr>";
$companyname=$worksheet->getCell($column.$row)->getValue();
// echo $companyname;
foreach($rowData[0] as $result)
{
echo "<td>".$result." </td>";
}
echo "</tr>";
}
echo "</table>";
echo "<br />";
echo '<input type="submit" name="sub" value="Convert into PDF" />';
// echo '<input type="text" name="resName" value="$result">';
function getdatan()
{
global $result; // declare as global
return $result;
}
echo '</form>';
this part is where I get company information... it looks like the table area shown down part...
I retrieve info and able to show as "$result" variable and with submit button named "convert it into pdf" I send it into other php page where I use TCPDF ....
Normally, this part of second page
$pdf->SetFont('times', 'BI', 12);
// add a page
$pdf->AddPage('L', 'A4');
if(isset($_POST['submit']))
{
$result = $_GET['resName'];
$pdf->Write(20, $result, '', 0, 'C', true, 0, false, false, 0);
}
// set some text to print
$txt = <<<EOD
TCPDF Example 003
Custom page header and footer are defined by extending the TCPDF class and overriding the Header() and Footer() methods.
EOD;
// print a block of text using Write()
// $pdf->Write(20, $resultt, '', 0, 'C', true, 0, false, false, 0);
// ---------------------------------------------------------
ob_end_clean();
//Close and output PDF document
$pdf->Output('example.pdf', 'I');
However, I am unable to print "$result" in the second page... can you help me about how to print this table on pdf...
PS: please clarify your help...
Try this
Change :
echo '<input type="submit" name="sub" value="Convert into PDF" />';
To:
echo '<input type="submit" name="resName" value="Convert into PDF" />';
EDIT
Put this at the begining of your second page:
var_dump($_POST);
just to check what you are receiving from the first page.
Also change :
$result = $_GET['resName'];
to this:
$result = $_POST['resName'];
ok since I was on my own... I found solution by myself ....
on the first page of PHP...
session_start();
//rest of your code and then...
if($_SERVER['REQUEST_METHOD'] == 'POST') {
echo '<form action="final.php" method="POST">';
$tablo="<br />";
$tablo = $tablo."<table border=\"1\" cellpadding=\"2\" cellspacing=\"2\" align='center'>";
for ($rowcount = $rowCompanyInfoStart; $rowcount <= $rowCompanyInfoEnd; $rowcount++)
{
//$data = $objWorksheet->rangeToArray('A1:' . $maxCell['column'] . $maxCell['row']);
$rangeCoordinates = $colCompanyInfoStart . $rowcount . ':' . $colCompanyInfoEnd . $rowcount;
$rowData = $sheet->rangeToArray($rangeCoordinates, NULL, TRUE, FALSE);
//fazla bosluk olursa bunları aç ya da hucre bos mu kontrol et (cellExists ile)
//rowData = array_map('array_filter', $rowData);
//$rowData = array_filter($rowData);
$tablo= $tablo."<tr >";
$companyname=$worksheet->getCell($column.$row)->getValue();
// echo $companyname;
foreach($rowData[0] as $result)
{
$tablo= $tablo. "<td>".$result. " </td>";
}
$tablo= $tablo. "</tr>";
}
$tablo= $tablo. "</table>";
echo $tablo;
echo "<br />";
if($_SERVER['REQUEST_METHOD'] != 'POST') {
echo "SESSION Not AVAIL. first run.";
}
else{
$_SESSION['varname'] = $tablo;
}
echo '<input type="submit" name="resName" value="Convert into PDF" />';
}
so here I used both "POST request" instead of just "POST". It sends "REQUEST" without any "POST DATA"... and then for sending the data I created a a variable called "$table" I put all my rows and cell info into that and created a session so that second PHP can retrieve it....
ON the second PHP page I answer "request" and open "session" just like that
session_start();
//rest of your code and then...
if($_SERVER['REQUEST_METHOD'] != 'POST') {
echo "SESSION Not AVAIL. first run.";
$tablo = $_SESSION['varname'];
echo "SESSION now set.";
}
else{
$tablo = $_SESSION['varname'];
//echo "SESSION SET, value: " .$_SESSION['varname']. " and ". $_SESSION['color'];
}
if (isset($_SESSION['varname'])){
$tablo = $_SESSION['varname'];
// print_r($_SESSION);
//echo "Session Set: <br/>" . $tablo;
}
else{
echo "Session not set. Tablo is empty";
// echo "Session Set: <br/>" . $tablo;
}
so that's it!
I'm currently making a droplist but in the droplist let's say I only want to include only .txt extension files so any other extensions like .php .jpg or any other extensions will not be in in the droplist. How can I do that as simple as possible?
Another question is I want to make a warning IF the folder does not have any .txt extension files an error message will show. So even if there are other .jpg .php or any other files inside as long as there's no .txt file in the folder a warning will show.
Anyone able to give me a hand?
This is what I have done but it only shows a drop-list with no .txt at the end but it will still show other random files in the drop-list though.
if(!(is_dir("./aaa")))
{
die("Must create a folder first, sorry");
}
$lists = scandir("./aaa");
echo "<form action=\"./page2.php\" method=\"get\">";
echo "<select>";
foreach($lists as $list)
{
if(($list == ".") || ($list == ".."))
{
continue;
}
echo "<option value=\"";
echo basename($list,".txt");
echo "\">";
echo basename($list,".txt");
echo "</option>";
}
echo "</select>";
echo "</form>";
editted added the substr with $hasTxt
<?php
if(!(is_dir("./aaa")))
{
die("Must create a <strong>aaa</strong> folder first, sorry");
}
echo "<form action=\"./page2.php\" method=\"get\">";
echo "<select name=\"aaa\">";
$aaa_files = scandir("./aaa");
$hastxt = false;
foreach($aaa_files as $file_list)
{
if(($file_list == ".") || ($file_list == ".."))
{
continue;
}
if(strlen($file_list)>4 && strtolower(substr($file_list, -4))!='.txt')
{
continue;
}
else
{
$hastxt = true;
echo "<option value=\"";
echo basename($file_list,".txt");
echo "\">";
echo basename($file_list,".txt");
echo "</option>";
}
}
echo "</select>";
echo "<br/><input type=\"submit\">";
echo "</form>";
if($hastxt == false)
{
echo "Must create text files first, sorry";
die();
}
?>
This is what happens for the script that I have now if the folder does not have any txt files.
This is what I actually want if there's no txt file but of course without the arrow
For the first part, just like you continue on directories . and .., you can continue on non-text files:
if(strlen($list)>4 && strtolower(substr($list, -4))!='.txt') continue;
For the warning part, put a flag before the foreach
$hasTxt = false;
And set it to true whenever you get input you don't ignore (ie. after the if(unwanted) continue;)
$hasTxt = true;
Finally, after the foreach check the value of $hasTxt and use it as you prefer.
You could use PHP's substr() function to test the filenames:
if(substr($filename, -3) == 'txt') {
// show file
}
See here: http://php.net/manual/en/function.substr.php
Try this , Hope it will work you
<?php
if(!(is_dir("./aaa")))
{
die("Must create a folder first, sorry");
}
$lists = scandir("./aaa");
$i =0;
foreach($lists as $list)
{
if (strstr($list, '.txt')) {
$i++;
}
}
if($i == 0){
die("the folder does not have any .txt extension files");
}
echo "<form action=\"./page2.php\" method=\"get\">";
echo "<select>";
foreach($lists as $list)
{
if (strstr($list, '.txt')) {
echo "<option value=\"".substr($list,0, -4)."\">".substr($list, 0,-4)." </option>";
}
}
echo "</select>";
echo "</form>";
?>