Dropdown list with New folder option in PHP - php

I have this script that gets all the sub-directories and puts them into a dropdown list.
I have an option "New folder" to create a new folder by gathering the folder name - in this case, it's numbers like 995 - and discount it by one to create a dir called 994
<form action="index.php" method="post">
<select name="folderchoose" id="folderchoose" onchange="this.form.submit();">
<?php
$base = basename("$items[1]", ".php").PHP_EOL;
$newbase = $base -1;
if($_POST['folderchoose']==0){ mkdir("../albums/$newbase", 0700); }
$items = glob("../albums/*", GLOB_ONLYDIR);
natsort($items);
{?><option>select:</option><?
foreach($items as $item)
{
?> <option value="1"><? echo "$item\n "; ?></option><?
} ?> <option value="0" >New folder</option> <?
}
?>
</select>
</form>
Directory:<?php echo $_POST[folderchoose] ?><br />
<?php $base = basename("$items[1]", ".php").PHP_EOL;
$newbase = $base -1;
echo $newbase ?>
Two things aren't working properly: the mkdir function doesn't get the $newbase and create a directory called dir(??) automatically even if I'm not choosing 'New Folder'.

I have a couple of hints for you to improve your code. I do not fully understand your problem but this might help.
If you want to list a directory with all of its sub directories you should do something like this
function list_directory( $dirname ) {
foreach file in directory
if(is_dir($dirname)){
list_directory($dirname)
}
if(is_File($dirname)){
echo $dirname;
}
}
}
This is not usable code but a genral idea for you to work with.
If strange things start happening try doing this
var_dump( $var ); // The variable your are suspecting in your case $newbase

You need to change if($_POST['folderchoose']==0) to something else because 0 mean "null" and therefore the if statement is true and it will be executed.
or... Use isset() to make sure the form really get submitted, for example
if (isset($_POST['folderchoose'])) {
if ($_POST['folderchoose'] == 0) {
//do mkdir or something

Related

php dynamically creating a file on form submit

would any one know how to automatically create a file through PHP so when the tag is clicked it also have the file right now it's only a path which is displayed through a loop. but when you click it there is no file, of course, long story short how can I also create a file too with a loop so all links have files created through fopen or something, just like all of them have paths generated.
<?php
function display_user_docs($doc_array) {
// set global variable, to test later if this is on the page
global $doc_table;
$doc_table = true;
?>
<br>
<form name="doc_table" action="delete_doc.php" method="post">
<table width="300" cellpadding="2" cellspacing="0">
<?php
$color = "#cccccc";
echo "<tr bgcolor=\"".$color."\"><td><strong>Documentations</strong></td>";
echo "<td><strong>Delete?</strong></td></tr>";
if ((is_array($doc_array)) && (count($doc_array) > 0)) {
foreach ($doc_array as $doc) {
if ($color == "#cccccc") {
$color = "#ffffff";
} else {
$color = "#cccccc";
}
echo "<tr bgcolor=\"".$color."\"><td><a class=\"all-doc-link\" href=\"".$doc.".php\">".htmlspecialchars($doc)."</a></td>
<td><input type=\"checkbox\" name=\"del_me[]\"
value=\"".$doc."\"></td>
</tr>";
}
} else {
echo "<tr><td>No documentation on record</td></tr>";
}
?>
</table>
</form>
<?php
}
?>
You can use file_put_contents to create a file in PHP.
It takes two parameters, the first of which is the name of the file to create, and the second of which is the contents to put inside of the file.
For example, if I wanted to make a file called 123.txt which contains hello world, I would do the following:
file_put_contents("123.txt", "hello world");
The filename can contain slashes /, so that you can specify which folder to create the file in. Thus, if I wanted to make my 123.txt file in the folder abc, I can put abc/123.txt as the filename (as long as abc is in the same folder as the PHP script).
You can find more about file_put_contents in the PHP manual.

Try/Catch seems to work with $_POST but not with session variables, PHP

I'm working on a php tutorial where a thumbnail generation page allows me to select from a dropdown list of photos in a directory on my server and upon hitting the submit button, a thumbnail of given size is created using a custom thumbnail class (the thumbnail overwrites the original image, which is fine for what I'm doing now). It's basic stuff and works as expected.
The page code:
<?php
$folder = '../images/';
use ClassFiles\Image\Thumbnail;
if (isset($_POST['create'])) {
require_once('ClassFiles/Image/Thumbnail.php');
try {
$thumb = new Thumbnail($_POST['pix']);
$thumb->setDestination('../images/');
$thumb->setMaxSize(400);
$thumb->create();
$messages = $thumb->getMessages();
} catch (Exception $e) {
echo $e->getMessage();
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Thumb</title>
</head>
<body>
<?php
if (isset($messages) && !empty($messages)) {
echo '<ul>';
foreach ($messages as $message) {
echo "<li>$message</li>";
}
echo '</ul>';
}
?>
<form method="post" action="">
<p>
<select name="pix" id="pix">
<option value="">Select an image</option>
<?php
$files = new FilesystemIterator('../images/');
$images = new RegexIterator($files, '/\.(?:jpg|png|gif)$/i');
foreach ($images as $image) {
$filename = $image->getFilename();
?>
<option value="<?= $folder . $filename; ?>"><?= $filename; ?></option>
<?php } ?>
</select>
</p>
<p>
<input type="submit" name="create" value="Create Thumbnail">
</p>
</form>
</body>
</html>
The custom thumbnail class is lengthy and for the sake of brevity I'm not posting it here unless requested, as it works fine.
So here's the problem:
I decided to take the image path and image filename information from an upload page I've been working on and store them in session variables that could be taken to the thumbnail generation page. The code in the thumbnail generation page was modified as shown:
<?php
require_once('includes/session_admin.php');
$folder = $_SESSION['image_path'];
use ClassFiles\Image\Thumbnail;
$getSize = getimagesize($_SESSION['image_path'] . $_SESSION['image_filename']);
$imagePath = $_SESSION['image_path'];
$imageFilename = $_SESSION['image_filename'];
if ($getSize[0] > 400) {
require_once('ClassFiles/Image/Thumbnail.php');
try {
$thumb = new Thumbnail($imageFilename);
$thumb->setDestination($imagePath);
$thumb->setMaxSize(400);
$thumb->create();
$messages = $thumb->getMessages();
} catch (Exception $e) {
echo $e->getMessage();
}
} else {
echo "Image is " . $getSize[0] . "px wide and is OK!";
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Thumb</title>
</head>
<body>
<?php
if (isset($messages) && !empty($messages)) {
echo '<ul>';
foreach ($messages as $message) {
echo "<li>$message</li>";
}
echo '</ul>';
}
// this was just to test that the session variables were correct
echo $_SESSION['image_path'] . $_SESSION['image_filename'];
echo '<br>';
print_r(getimagesize($_SESSION['image_path'] . $_SESSION['image_filename']));
?>
<!--
Removed the form...
-->
</body>
</html>
Now, instead of the conditional statement checking to see if $_POST was submitted, the code (I thought) would automatically check to see if the image, given the full path and filename, is wider than 400px, and if so, resize the image using the custom thumbnail class.
But, this throws errors from the thumbnail class, the same class that works just fine with the original thumbnail generation page code from the tutorial.
This works in the original tutorial code:
$thumb = new Thumbnail($_POST['pix']);
but not when modified to take a session variable instead:
$thumb = new Thumbnail($imageFilename);
I've looked and looked for any suggestion that $_POST was required here, I checked that the session variables were passing along the proper information, and they are. But making the switch from $_POST to using a session variable prevents this from working.
As you'll see, I'm still learning php and this is one of those hurdles that has held me up all day. Perhaps the answer is glaringly obvious, but I'm certainly at a standstill.
All input is appreciated, thanks!
Try this before set the object of your class
$_POST['pix']=$_SESSION['image_filename'];
So you set the POST variable manually and use it a The thumbnail class suppose it

How to use a select form to change language with PHP $_GET and $_POST?

I have to apologize if this answer has already been answered before, I've looked for it and found something partially useful but nothing that answered my needs.
I'm new to PHP and I want to make a simple website with multilingual support. Translations are provided by specific arrays according to the page they are in. I will use a foreach loop to get the translation. User is allowed to change the default language with a select html tag. I am partially able to achieve this goal in this way:
Firstly, with a simple function I look for the browser language and set it as language fall-back:
function browser_lang() {
$rawLang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
if($rawLang == 'it') {
$browserLang = 'it';
} else {
$browserLang = 'en';
}
return $browserLang;
}
In the index.php file I set the fall-back language in this way:
<?php
// Include the browser_lang() and other functions
if(isset($_POST['set_language'])) {
$lang = strip_bad_chars($_GET['lang']);
} else {
$lang = browser_lang();
}
?>
<html lang="<?php echo $lang; ?>">
Later in the html I added a form with some select tag that allows to select languages:
<form action="" method="post">
<select name="set_language" id="custom-lang">
<option value="it">Italiano</option>
<option value="en">English</option>
</select>
<input type="submit" name="input_language" value="Set Language">
</form>
When I load the page for the first time, the script is able to retrieve the browser language, but when I select a custom language, it is not able to change it.
How can I add ?lang=en or ?lang=it at the end of the url in order to use $_GET['lang'] and loop through translations with the $lang variable set with that select form?
The entire index.php, included the external resources, is:
<?php
function browser_lang() {
$rawLang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
if($rawLang == 'it') {
$browserLang = 'it';
} else {
$browserLang = 'en';
}
return $browserLang;
}
function strip_bad_chars( $input ) {
$output = preg_replace( "/[^a-zA-Z0-9_-]/", "",$input);
return $output;
}
if(isset($_POST['set_language'])) {
$lang = strip_bad_chars($_GET['lang']);
} else {
$lang = browser_lang();
}
?>
<!DOCTYPE html>
<html lang="<?php echo $lang; ?>">
<head>
<title>HOME</title>
</head>
<body>
<form action="" method="post">
<select name="set_language" id="custom-lang">
<option value="it">Italiano</option>
<option value="en">English</option>
</select>
<input type="submit" name="input_language" value="Set Language">
</form>
</body>
</html>
If you want the lang parameter in the URL (which I think makes sense) you can just change your form a bit:
<form action="" method="get"><!-- use get instead of post-->
<select name="lang" id="custom-lang"><!-- change name to lang-->
... etc.
This way, when the form is submitted, you will have ?lang=en or ?lang=it in the URL, and you can use
if (isset($_GET['lang'])) {
$lang = strip_bad_chars($_GET['lang']);
} else {
$lang = browser_lang();
}
to set your language.
You seem to have several problems:
You're mixing the submission methods (Using both POST and GET)
You check for $_POST['set_language'] but expect $_GET['lang']
The <select> menu is named differently to the variable you wish to use in the <html> tag's lang attribute.
What I'd do is settle on a method; POST or GET then change all ref's to GET/POST respectively, and then use either "set_language" or "lang" as your superglobal ($_GET/$_POST) array key.
Try this
<?php
// Include the browser_lang() and other functions
if(isset($_POST['input_language'])) {
$lang1 = $_POST['set_language'];
if ($lang1 == "Italiano") {
$lang = "it"
} else {
echo "en";
}
}
?>
<html lang="<?php echo $lang; ?>">

Use php to create a dynamic menu without a database using only folders in the directory?

I would like to thank anyone who is able to help me in any way possible, I am extremely new to php/coding in general so I am not even sure if I am on the right path.
I wanted to know if it was possible to create 2 step or dynamic drop down menu using only php and html that populates the first drop down menu with folders from a directory.
So far I have
<?php
// Set the path of the dir you want displayed...
$path="./track";
$handle=opendir($path);
while ($file=readdir($handle))
{
echo "\t<option value='".$file."'>".$file."</option>\n";
}
?>
This lets me grab the the folders from a directory, how would I proceed to create a second drop down menu that would let you choose any of the files from whichever folder you selected in the first drop down menu, and then display it on the website?
An example picture of what I am trying to achieve is as follows:
http://postimg.org/image/im03tjh0d/
<?php
/**
* Check if we have submit the folder
* Check if we have submit the file
*/
$post_folder = isset($_POST['folder']) ? $_POST['folder']: null;
$post_file = isset($_POST['file_name']) ? $_POST['file_name'] : null;
/**
* Built out the Folder submission form
*/
// Set the path of the dir you want displayed...
$path="./";
echo '<form method="POST" action="', $_SERVER['PHP_SELF'],'">';
echo '<select name="folder">';
foreach (new DirectoryIterator($path) as $asset){
if($asset->isDot()) continue;
if($asset->isDir()){
/**
* If we've posted which folder we want to view the contents of
* then automatically make that selected in the dropdown on page load
*/
$selected = (isset($post_folder) && $post_folder == $asset->getFileName()) ? 'selected' : '';
echo "\t<option value='".$asset->getFilename()."' $selected>".$asset->getFilename()."</option>\n";
}
}
echo '</select>';
if(isset($post_folder)){
echo '<select name="file_name">';
$folder_to_iterate = $path.$post_folder;
foreach (new DirectoryIterator($folder_to_iterate) as $asset){
if($asset->isFile()){
/**
* If we've posted which folder we want to view the contents of
* then automatically make that selected in the dropdown on page load
*/
$selected = (isset($post_file) && $post_file == $asset->getFileName()) ? 'selected' : '';
echo "\t<option value='".$asset->getFilename()."' $selected>".$asset->getFilename()."</option>\n";
}
}
echo '</select>';
}
$btn_text = isset($post_folder) ? 'Show File Contents' : 'Show Folder Contents';
echo '<input type="submit" value="', $btn_text ,'"/>';
echo '</form>';
if(isset($post_file)){
$file_to_read = $path.$post_folder.'/'.$post_file;
echo '<pre>';
echo htmlentities(file_get_contents($file_to_read));
echo '</pre>';
}
Use ajax and the file system functions.

PHP replacing 'editable' areas in html files

I'm working on a tool to replace tagged areas in a html document. I've had a look at a few php template systems, but they are not really what I am looking for, so here is what I am after as the "engine" of the system. The template itself has no php and I'm searching the file for the keyword 'editable' to set the areas that are updatable. I don't want to use a database to store anything, instead read everything from the html file itself.
It still has a few areas to fix, but most importantly, I need the part where it iterates over the array of 'editable' regions and updates the template file.
Here is test.html (template file for testing purposes):
<html>
<font class="editable">
This is editable section 1
</font>
<br><br><hr><br>
<font class="editable">
This is editable section 2
</font>
</html>
I'd like to be able the update the 'editable' sections via a set of form textareas. This still needs a bit of work, but here is as far as I've got:
<?php
function g($string,$start,$end){
preg_match_all('/' . preg_quote($start, '/') . '(.*?)'. preg_quote($end, '/').'/i', $string, $m);
$out = array();
foreach($m[1] as $key => $value){
$type = explode('::',$value);
if(sizeof($type)>1){
if(!is_array($out[$type[0]]))
$out[$type[0]] = array();
$out[$type[0]][] = $type[1];
} else {
$out[] = $value;
}
}
return $out;
};
// GET FILES IN DIR
$directory="Templates/";
// create a handler to the directory
$dirhandler = opendir($directory);
// read all the files from directory
$i=0;
while ($file = readdir($dirhandler)) {
// if $file isn't this directory or its parent
//add to the $files array
if ($file != '.' && $file != '..')
{
$files[$i]=$file;
//echo $files[$i]."<br>";
$i++;
}
};
//echo $files[0];
?>
<div style="float:left; width:300px; height:100%; background-color:#252525; color:#cccccc;">
<form method="post" id="Form">
Choose a template:
<select>
<?php
// Dropdown of files in directory
foreach ($files as $file) {
echo "<option>".$file."</option>"; // do somemething to make this $file on selection. Refresh page and populate fields below with the editable areas of the $file html
};
?>
</select>
<br>
<hr>
Update these editable areas:<br>
<?php
$file = 'test.html'; // make this fed from form dropdown (list of files in $folder directory)
$html = file_get_contents($file);
$start = 'class="editable">';
$end = '<';
$oldText = g($html,$start,$end);
$i = 0;
foreach($oldText as $value){
echo '<textarea value="" style="width: 60px; height:20px;">'.$oldText[$i].'</textarea>'; // create a <textarea> that will update the editable area with changes
// something here
$i++;
};
// On submit, update all $oldText values in test.html with new values.
?>
<br><hr>
<input type="submit" name="save" value="Save"/>
</div>
<div style="float:left; width:300px;">
<?php include $file; // preview the file from dropdown. The editable areas should update when <textareas> are updated ?>
</div>
<div style="clear:both;"></div>
I know this answer is a little more involved, but I'd really appreciate any help.
Not sure if i correctly understand what you want to achieve. But it seems I would do that in jquery.
You can get all html elements that has the "editable" class like this :
$(".editable")
You can iterate on them with :
$(".editable").each(function(index){
alert($(this).text()); // or .html()
// etc... do your stuff
});
If you have all your data in a php array. You just need to pass it to the client using json. Use php print inside a javascript tag.
<?php
print "var phparray = " . json_encode($myphparray);
?>
I think it would be better to put the work on the client side (javascript). It will lower the server work load (PHP).
But as I said, I don't think I've grasped everything you wanted to achive.

Categories