php dynamically creating a file on form submit - php

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.

Related

Simultaneous file upload to the same directory

For part of my web app, I'm attempting to upload 1 file under 2 different names. The first name is the original file name that the user specified. This is to be used for reference later on in my app. The second name is an altered name (simply adding in a counter variable). For uploading a single file using move_uploaded_file($name, $path), it works like a charm. When I attempted to call one move_uploaded_file(...) after the other, only the first function would upload a file. The second function would not return an error message.
After looking online, it seemed that this could be accomplished with a loop. I placed the names and the paths in an array, loop through it with a foreach loop but only the first file is uploaded.
Below are the files and their relevant portions as some are lengthy.
mainPage.php applies a header across all of my pages.
verifyFile.php is the file that does the uploading as well as verifying the bulk processing to check that the file is valid.
workPage.php
<?php
session_start();
require("mainPage.php");
?>
<link rel = "stylesheet" type = "text/css" href = "CSS/workpageCSS.css" />
<div id = "pageContainer">
<form enctype = "multipart/form-data" action = "verifyFile.php" method = "post">
<table border = "0" cellpadding = "2" cellspacing = "5">
<tr>
<td>
<label for = "fileName">Select file to upload</label>
</td>
<td>
<input type = "file" name = "file" id = "fileName" placeholder = "Choose file path" autofocus = "autofocus" required = "required" />
</td>
</tr>
<tr>
<td></td>
<td><input type = "submit" value = "Load file" /></td>
</tr>
</table>
</form>
</div>
Portion of verifyFile.php that uploads the file.
Attempt 1:
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', '1');
$dupFile = appendFileName(basename($_FILES['file']['name']));
$origToUpload = basename($_FILES['file']['name']);
$targetPath = ("uploads/".$dupFile);
$origTargetPath = "uploads/".$origToUpload;
if(move_uploaded_file($_FILES['file']['tmp_name'], $targetPath)) {
#echo("Successfully uploaded ".basename($_FILES['file']['name']));
} else {
echo("Failed 1<br />");
}
/*move_uploaded_file($_FILES['file']['tmp_name'], $origTargetPath); Does not upload but no errors are generated */
?>
Attempt 2
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', '1')
$filesToUpload = array($targetPath, $origTargetPath);
foreach($filesToUpload as $toUpload) {
if(move_uploaded_file($_FILES['file']['tmp_name'], $toUpload)) {
echo("worked!"); /* first time is successful and $targetPath is loaded onto my server */
} else {
echo("neg"); /* nothing is uploaded and returns neg */
}
}
?>
$origTargetPath and $targetPath are both valid since if I reverse them in my array, only the first file is correctly uploaded.
For additional information, I'm using Apache via XAMPP.
When you call move_upload_file, php will move the file from the file temporary location, to the one you specified. So you can't move the file twice.
What you are looking for is the copy function. In your case (first attempt):
copy($targetPath, $origTargetPath);
You could also consider symlink

PHP link to include header

I have php reading a text file that contains all the names of images in a directory, it then strips the file extension and displays the file name without the .jpg extension as a link to let the user click on then name, what I am looking for is a easy way to have the link that is clicked be transferred to a variable or find a easier solution so the link once it is clicks opens a page that contains the default header and the image they selected without making hundreds of HTML files for each image in the directory.
my code is below I am a newbie at PHP so forgive my lack of knowledge.
thank you in advance. also I would like a apple device to read this so I want to say away from java script.
<html>
<head>
<title>Pictures</title>
</head>
<body>
<p>
<?php
// create an array to set page-level variables
$page = array();
$page['title'] = ' PHP';
/* once the file is imported, the variables set above will become available to it */
// include the page header
include('header.php');
?>
<center>
<?php
// loads page links
$x="0";
// readfile
// set file to read
$file = '\filelist.txt' or die('Could not open file!');
// read file into array
$data = file($file) or die('Could not read file!');
// loop through array and print each line
foreach ($data as $line) {
$page[$x]=$line;
$x++;
}
$x--;
for ($i = 0; $i <= $x; $i++)
{
$str=strlen($page[$i]);
$str=bcsub($str,6);
$strr=substr($page[$i],0,$str);
$link[$i]= "<a href=".$page[$i]."jpg>".$strr."</a>";
echo "<td>".$link[$i]."<br/";
}
?>
</P></center>
<?php
// include the page footer
include('/footer.php');
?>
</body>
</html>
add the filename to the url that you want to use as a landing page, and catch it using $_GET to build the link.
<a href='landingpage.php?file=<?php echo $filename; ?>'><?php echo $filename; ?></a>
Then for the image link on the landing page
<img src='path/to/file/<?php echo $_GET['file'] ?>.jpg' />

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.

PHP change data on click

I have a php page that creates page data from two .txt files (one for info, and one for slideshow images), and creates pagination based on this data. I have a few different categories though - so I don't want all the work sharing the same pagination. I would like the user to be able to select different categories from a menu, and the page data txt files will change.
I was wondering if there is a script which can simply change the name of the .txts file when a link in the menu is clicked, and go to the first page of that?
Here is my current setup, at start of document:
<?php
$data=file("brief.txt");
$pages=0;
foreach($data as $temp){
$x=explode("|",$temp);
if($x[0]>0){
$pages=$pages+1;
}
}
if($_GET['p']){
$page=$_GET['p'];
}
if($_GET['i']){
$index=$_GET['i'];
}
if($index == "p"){
$page=$page-1;
}
if($index == "n"){
$page=$page+1;
}
if($page < 1){
$page=1;
}
if($page > $pages){
$page=$pages;
}
$line=$data[$page-1];
$fields=explode("|",$line);
?>
Slideshow images (from work.txt)
<?php
echo"
<div id='portfolioslider'>
<div class='slider'>
";
$photos=file("work.txt");
foreach($photos as $image){
$item=explode("|",$image);
if($item[0]==$fields[0]){
$photo=trim($item[1]);
echo"<div><img src='images/work/$photo' alt='' /></div>\n";
}
}
echo"
</div>
</div>
"?>
Information (from brief.txt)
<?php
echo"
<div id='overview'>
<h3>{$fields[1]}</h3> </br></br>
<h3>Project Overview:</h3> {$fields[2]}</div>";
echo"
<div id='skills'><h3>Skills:</h3><ul>{$fields[3]}</ul></div>
";
?>
I'm not sure if I understand exactly what you're asking, but to rename on a click, you could have html like so:
Then on page.php, have a script that renames the txt file:
<?php
if(isset($_GET('file'))) rename("/blank.txt", "/" . $_GET('file') . ".txt");
?>
Then to go to that page, I guess you could have a header function to go to another page, or you could just open the txt file on page.php:
<?php
if(isset($_GET('file'))) {
$data=file("/" . $_GET('file') . ".txt");
foreach($data as $temp){
echo $temp;
}
}
?>
The header function could go to a dynamic page that pulls the filename with $_GET:
<?php
if(isset($_GET('file'))) header("Location: http://www.example.com/dynamic?page=" . $_GET('file'));
?>
And that page could run the foreach loop.

Dropdown list with New folder option in 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

Categories