Creating dirs, copying file, writing content into the files - php

There are some posts here, but they don't work for me. My need is described in the comments. As a poor beginner, I read many possible online manuals, but can't find the solution.
<?php
// BASIC STRUCTURE //
// ./core/
// ./core/index.gen
// ./data/
// ./data/<dir_name>
// ./data/<dir_name>/<file_name>
// ./data/<dir_name>/index.php - for <dir_name> listing
// ./data/index.php - for ./data/ listing
// BASIC OPERATION
// 1. create a subdirectory in ./data/
// 2. copy the ./core/index.gen to new created subdirectory
// 3. create new file in new created directory in ./data/
$base_dir = './data';
$dir_name = '';
$file_name = '';
$data_dir = $_GET['data_dir'];
//Check if the directory with the name already exists
if (!is_dir($base_dir.$data_dir)) {
//Create our directory if it does not exist
mkdir($base_dir.'/'.$data_dir);
$msg = 'SUCCESS';
touch($base_dir.'/'.$data_dir.'/'.$_GET['file_name'].'.html');
// copy index.gen from ./core/ to new created dir
copy($base_dir.'dir_index.php',$base_dir.'/'.$data_dir.'.index.php');
}else{
$msg = 'ERROR';
}
// read directory content
function getFiles(){
$items=array();
if($dir=opendir('.')){
while($item=readdir($dir)){
if($item!='.'
&& $item!='..'
&& $item!=basename(__FILE__)
&& $item != "index.php"
&& $item != "core"
){
$items[]=$item;
}
}
closedir($dir);
}
natsort($items); //sort
return $items;
}
?>
<!-- in HTML bobdy -->
...
<div class="msg"><?php echo $msg;?></div>
<div class="frames">
<div id="dirs" class="frame">
<div class="frame-title">Directories</div>
<!-- generated dirs-list-links targeted to #files -->
<iframe name="dirs" src="<?php echo $base_dir.'/index.php';?>"></iframe>
</div>
<div id="files" class="frame">
<div class="frame-title">Files</div>
<!-- generated files-list-links targeted to #file_preview -->
<iframe name="files" src="<?php echo $data_dir.'/index.php';?>"></iframe>
</div>
<div id="file_preview" class="frame">
<div class="frame-title">Preview</div>
<iframe name="file_preview"><file.html></iframe>
</div>
</div>
The directories and files are created correctly. But the "index" file is not copoied. Please, hint.

I believe you're looking for file_put_contents
read the index file you want to create into a variable
$current = file_get_contents($file);
then write the index file:
$targetIndexFile = '/newDirectory/index.html';
file_put_contents($targetIndexFile,$current;
That should allow you to effectively move a file from one directory to another.

You must add a slash before dir_index.php:
copy($base_dir . '/' . 'dir_index.php',$base_dir.'/'.$data_dir.'.index.php');

Related

Set backgroung image in .php file

I downloaded this code:
$image = ImageClass::getImage('bg.jpeg','myTitle');
$bg_img = explode(" ",$image);
$src = substr(strpos('"',$bg_img),strlen($bg_image)-1);
echo "<div style='background-image: url(".$src.");' ></div>
<?php
/*
*** OPTIONS ***/
// TITLE OF PAGE
$title = "ARQUIVOS PROPAR";
// STYLING (light or dark)
$color = "dark";
// ADD SPECIFIC FILES YOU WANT TO IGNORE HERE
$ignore_file_list = array( ".htaccess", "Thumbs.db", ".DS_Store", "index.php", "flat.png", "error_log" );
// ADD SPECIFIC FILE EXTENSIONS YOU WANT TO IGNORE HERE, EXAMPLE: array('psd','jpg','jpeg')
$ignore_ext_list = array( );
// SORT BY
$sort_by = "name_asc"; // options: name_asc, name_desc, date_asc, date_desc
// ICON URL
//$icon_url = "https://www.dropbox.com/s/lzxi5abx2gaj84q/flat.png?dl=0"; // DIRECT LINK
$icon_url = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA+gAAAAyCAYAAADP7vEwAAAgAElEQVR4nOy9d5hdV3nv";
// TOGGLE SUB FOLDERS, SET TO false IF YOU WANT OFF
$toggle_sub_folders = true;
// FORCE DOWNLOAD ATTRIBUTE
$force_download = true;
// IGNORE EMPTY FOLDERS
$ignore_empty_folders = false;
// SET TITLE BASED ON FOLDER NAME, IF NOT SET ABOVE
if( !$title ) { $title = clean_title(basename(dirname(__FILE__))); }
?>
Th full code can be download here: https://github.com/halgatewood/file-directory-list/blob/master/index.php
I'm having problem with the start:
$image = ImageClass::getImage('bg.jpeg','myTitle');
$bg_img = explode(" ",$image);
$src = substr(strpos('"',$bg_img),strlen($bg_image)-1);
echo "<div style='background-image: url(".$src.");' ></div>
I want to put a picture as background, but it isn't happening. What's wrong?
Changed with the answer:
<?php
echo "<div style='background-image: url('/bg.jpeg');' ></div>";
?>
<?php
/*
*** OPTIONS ***/
// TITLE OF PAGE
$title = "ARQUIVOS PROPAR";
// STYLING (light or dark)
$color = "dark";
etc..
No need for all that,
What you desire to achieve is much simpler.
Assuming this code is inside index.php and your server's directory structure:
/some-folder/
/index.php
/bg.jpeg
Simply link it as its done in plain html —
<?php
echo "<div style=\"background-image: url('/bg.jpeg');\" ></div>";
?>
If you wan't it do be dynamic, i.e, image files's name is inside a variable then,
<?php
$my_image = 'bg.jpeg';
echo "<div style='background-image: url($my_image);' ></div>";
?>
Update:
Important Tip: All programming languages are executed line-by-line, this tip applies not only to PHP, but also HTML Learn More
Assume for example, your page's html structure returned to the browser is as provide below and you want to apply background to body tag
<html>
<head><head>
<body>
<nav>Some dummy navigation</nav>
<div>welcome to my website</div>
<footer>Copyright</footer>
</body>
</html>
Simply copying and pasting my code to the top of page will result in
<div style="background-image: url('bg.jpeg');" ></div>
<html>
<head><head>
<body>
<nav>Some dummy navigation</nav>
<div>welcome to my website</div>
<footer>Copyright</footer>
</body>
</html>
But that created a empty div tag at the top of html output, i wanted it to apply background to by body tag instead !!!?
— This happened because echo is used to send output to the browser as soon as it is executed. So since you copied my code to the top of your script the html output is also at the top.
But why did it echo <div style="background-image: url('bg.jpeg');" ></div> when i wanted it to apply to my page's body?
— Because the echo statements reads "<div style=\"background-image: url('bg.jpeg');\" ></div>"; as its output.
Ok, but how to apply the background-image to body then??
As mentioned earlier code is executed line-by-line, so in order to apply the style to pages's body tag you'll need to call it near your body tag and also modify it to not output the div it currently does.
So assuming your index.php is:
<?php
$my_image = 'bg.jpeg';
echo "<div style='background-image: url($my_image);' ></div>";
?>
<html>
<head><head>
<body>
<nav>Some dummy navigation</nav>
<div>welcome to my website</div>
<footer>Copyright</footer>
</body>
</html>
You'll need to change it to —
<?php
$my_image = 'bg.jpeg';
// don't echo any thing here
?>
<html>
<head><head>
<body style="background-image: url('<?php echo $my_image; ?>')">
<!-- apply the style to body -->
<nav>Some dummy navigation</nav>
<div>welcome to my website</div>
<footer>Copyright</footer>
</body>
</html>
Hopefully i explained it well :)

How pass angularjs array value into php function as a variable?

I have the code which return json response but I don't know how pass the that value in php function.
Code:
<div class="container" ng-controller="askbyctrl" >
<div class="row" ng-repeat="q in qa.data" >
<div class="col-md-12 col-xs-12 col.sm.12" >
<div class="artist-data pull-left" style = "background-color:#BEB7B7;">
<div class="artst-pic pull-left">
<?php
function cache_image($id){
//replace with cache directory
$image_path = 'C:\xampp\htdocs\QA_UI\images';
$image_url = 'http://localhost:8000/api/image/' + id;
//get the name of the file
$exploded_image_url = explode("/",$image_url);
$image_filename = 'id.jpg';
$exploded_image_filename = explode(".",$image_filename);
$extension = end($exploded_image_filename);
//make sure its an image
if($extension=="jpg") {
//get the remote image
$image_to_fetch = file_get_contents($image_url);
if($image_to_fetch == '{"error":true,"details":"No image."}') {
echo 'file not found';
} else {
//save it
$local_image_file = fopen($image_path.'/'.$image_filename, 'w+');
chmod($image_path.'/'.$image_filename,0755);
fwrite($local_image_file, $image_to_fetch);
fclose($local_image_file);
echo 'copied';
}
}
//}
?>
<img ng-src="images/{{q.userID}}.jpg" alt="" class="img-responsive" />
</div>
Please see the code how can I pass the {{q.userID}} in php function..
You can't do it that way. PHP code is running on server side and angular-code in client-side, in browser. That is, when server returns compiled html to browser it has already done all php-code in that file.
If you want to check if image exists and then cache it, you can do it from angular for example with $http. Call with $http your backend-script, which does what you want, and then returns if it was success or not.

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.

How to stop Resource #100 folder being created when Joomla component gallery is viewed

I have created a basic component for Joomla that allows users to list an item along with some associated images. When the page containing the gallery is viewed a strange folder is created in the root web directory in the format of Resource id #100, the number varies with each item. I have narrowed down the code that is causing this to the following. My question is can some see what I'm doing to cause this and can anyone offer alternatives to the code I'm using to read the files from a particular directory and return the information.
<p id="sl_gallery">
<?php if( is_file( JPATH_ROOT.'/components/com_eg/images/gallery/'.$this->eg->id.'/main.jpg' ) ) : ?>
<img src="<?php echo JURI::root().'/components/com_eg/images/gallery/'.$this->eg->id.'/main.jpg' ?>" alt="myimage">
<?php else: ?>
<img src="<?php echo JURI::root().'/components/com_eg/images/nolistings.gif'; ?>" alt="myimage" />
<?php endif; ?>
<?php
$TrackDir= opendir(JPATH_ROOT.'/components/com_eg/images/gallery/'.$this->eg->id.'/second/');
$count = 0;
if ( !JFolder::exists($TrackDir) ) { JFolder::create($TrackDir); }
while (($file = readdir($TrackDir)) !== false) {
if ($file == "." || $file == "..") { }
else {
?>
<img src="<?php echo JURI::root().'/components/com_eg/images/gallery/'.$this->eg->id.'/second/'.$file; ?>" alt="myimage" />
<?php
}
}
closedir($TrackDir); ?>
</p>
Change this:
$TrackDir= opendir(JPATH_ROOT.'/components/com_eg/images/gallery/'.$this->eg->id.'/second/');
$count = 0;
if ( !JFolder::exists($TrackDir) ) { JFolder::create($TrackDir); }
...to this:
$TrackDirPath = JPATH_ROOT.'/components/com_eg/images/gallery/'.$this->eg->id.'/second/';
if ( !JFolder::exists($TrackDirPath) ) { JFolder::create($TrackDirPath); }
$TrackDir = opendir($TrackDirPath);
$count = 0;
$TrackDir holds the result of a call to opendir() - this means it will either be a resource or FALSE. When you convert a resource to a string, it results in Resource id # - which you did by (effectively) passing it to mkdir().
I have stored the path as a string in a variable $TrackDirPath, and passed that to JFolder::create() instead. I have also re-ordered the statements, to make sure that the directory exists before you try to open it.

Categories