Ok i have 2 files - index.php that has and if statement that is as follows:
$sub = array_shift(explode(".",$_SERVER['HTTP_HOST']));
if ($sub == 'localhost') include 'home.php';
if ($sub == 'whateversubdomain') include 'correspondingphpfile .php';
I also have a text file that has:
subdomain = subdomain.php
nextsub = nextsub.php
.... and so on
The question being how would I make it so that when I add a new line to the text file say nextsub, and someone visits nextsub.sitename.com that they are directed to the correct php file.
I was thinking of opening the text file and creating a variable in the index.php file then saying if $sub == $newVar include $subName . .php .
is this possible - something like -
//open file
$fp = #fopen ($some_file, "r");
if ($fp) {
//for each line in file
while(!feof($fp)) {
//push lines into array
$this_line = fgets($fp);
array_push($some_array,$this_line);
}
//close file
fclose($fp);
}
(you have to handle non-existing manually)
For example, a directory "subdomains":
$sub = array_shift(explode(".",$_SERVER['HTTP_HOST']));
include 'subdomains/'.basename($sub).'.php';
I don't know, what's the point in additional writing into file.
If you are insisting on having subdomains with pages that don’t have an easy to parse name scheme the best bet is the following:
// Create an array that maps subdomains to pages.
$sub_page_map = array();
$sub_page_map['localhost'] = 'home.php';
$sub_page_map['whateversubdomain'] = 'correspondingphpfile.php';
// Get the subdomain.
$sub = array_shift(explode(".",$_SERVER['HTTP_HOST']));
// If the `$sub` exists in `$sub_page_map` then include the corresponding file.
if (array_key_exists($sub, $sub_page_map)) {
include $sub_page_map[$sub];
}
else {
include 'default.php';
}
If you want to store it in an external text file, just adapt your file parsing code to generate the values in $sub_page_map. But to me the biggest flaw in your setup is the lack of a default page, which is why I included an else to load a proposed `default.php.
Related
I have a task to do in which i have to list the directories with it's files which i did, but i don't understand how to delete file or edit specific file in the directories any help will be appreciated Thanks.
<?php
error_reporting(0);
if(isset($_GET['dir']))
{
// /$path = 'E:\xampp\\'.$_GET['dir'];
$path = $_GET['dir'];
}
else
{
$path = 'E:\xampp\\';
}
if(is_dir($path))
{
$arrDir = scandir($path);
echo "<ul>";
foreach ($arrDir as $key => $value)
{
echo "<a href='http://localhost/vishrut/FileUpload/filelist.php?
dir=".$path.'/'.$value."'>".$value.'</a><br>';
}
echo "</ul>";
}
else
{
echo "<textarea>";
echo file_get_contents($path);
echo "</textarea>"."<br>";
}
?>
There are lots of PHP's functions to handle files: https://www.php.net/manual/en/ref.filesystem.php
For your needs see these:
file_get_contents to read the entire file contents
file_put_contents to write the content in a file
unlink to delete a file
So, the steps to modify a file may be:
get the complete contents with file_get_contents:
$contents = file_get_contents($filePath);
apply your edits to the $contents content:
$newContents = ...
overwrite the file content:
file_put_contents($filePath, $newContents);
To delete a file is simple:
unlink($filePath);
It's important to note that your code is subjected to injection because you don't check the user data passed with $_GET.
If your script will be used only by you it's ok, instead you must check all user input: the first rule of Web programming is NEVER TRUST YOUR USERS! Also trusted users may write wrong characters in the url and that may have unexpected results (e.g. delete the wrong file!)
Read https://www.php.net/manual/en/mongodb.security.script_injection.php
I'm working on a mini web project for a local business. I used PHP includes and plain PHP templates for this as I found CMSs too big for the task.
I'm trying to generate all .php files in the project dir to static .html using ob_start(), ob_get_contents() like:
ob_start();
$page = ob_get_contents();
ob_end_clean();
$out = "pages/page-1";
$file = $out.'/'. "filename.html";
#chmod($file,0755);
$fw = fopen($file, "w");
fputs($fw,$page, strlen($page));
fclose($fw);
This generates the current page (where the code is written) but I'm stuck with doing this manually for all .php files instead of adding it to every page.
UPDATE:
Here is the basic structure:
- index.php
- /about
--- about-us.php
--- our-story.php
- /products
--- interior/
--- some-product.php
--- exterior/
--- some-product.php
--- some-other-product.php
- /contact
--- contact.php
--- quote.php
- /includes (config,base.php,header.tpl,footer.tpl,...templates)
- /css/js/images/assets...
I will put the script in the same folder and it shouldn't render itself, the html output will go to the /out folder.
This is a bare-bones implementation of a script that:
Looks for .php files in a directory
Runs each .php file
Dumps the output to a .html file with the same name
This is not recursive, but I don't have enough information about the structure of your site to make too many assumptions.
If you update your question I can update my answer - you can use RecursiveDirectoryIterator and the aptly-named RecursiveRecursiveIterator to recurse through a file structure.
In any case, this should provide a starting point:
<?php
$iterator = new DirectoryIterator(__DIR__);
function isValidFile(SplFileInfo $fileInfo)
{
return $fileInfo->isFile()
&& 'php' === $fileInfo->getExtension()
&& basename(__FILE__) !== $fileInfo->getBasename();
}
function parseFile(SplFileInfo $fileInfo)
{
ob_start();
require_once $fileInfo->getBasename();
$data = ob_get_contents();
ob_end_clean();
return $data;
}
foreach ($iterator as $fileInfo) {
if (isValidFile($fileInfo)) {
$data = parseFile($fileInfo);
$file = $fileInfo->getBasename('.php') . '.html';
file_put_contents($file, $data);
}
}
Given a file structure like this:
You should end up with the following (assuming that dir is writable):
Hope this helps :)
I'm making a function on WordPress to get the content of the robots.txt file. If the file doesn't exist, create it with default content. I will use it for my options page. Well, this is my code, it should work almost creating the file, but it doesn't:
function get_robots($robots_file) {
$robots_file = get_home_path() . 'robots.txt'; //The robots file.
$dir = get_home_path(); //The root directory
if(is_file($robots_file)){
$handle = fopen($robots_file, "r");
$robots_content = fread($handle, filesize($robots_file));
fclose($handle);
} else {
$default_content = "User-agent: *\nDisallow:";
chmod($dir, 0777);
$handle = fopen($robots_file, "w+");
$robots_content = fwrite($handle, $default_content);
fclose($handle);
}
chmod($dir, 0744);
return $robots_content;
}
I'm not sure if the problem is is_file, or the fopen($robots_file, "w+" (should it be "r"?) after the else. And I'm not sure about the permissions. Is the 777 needed? Is the 744 the default for the root directory of WordPress?
And I use the return to use it as variable later; I suppose the fopen is already creating the file. Am I right?
Thanks in advance.
The first thing, I would use completely different functions, you have file_put_contents() and file_get_contents() for such simple operations.
So possible simpler solution is:
function get_robots() {
$robots_file = get_home_path() . 'robots.txt'; //The robots file.
if(file_exists($robots_file)){
return file_get_contents($robots_file);
} else {
$default_content = "User-agent: *\nDisallow:";
file_put_contents($robots_file, $default_content);
return $default_content;
}
}
I don't see any point to pass $robots_file as function argument so I removed it. You should check if this code simple works.
I also don't see any reason to change $dir permissions as you showed in your code. It should be rather set manually and you definitely shouldn't change your root directory permission in such function.
EDIT
Because this function uses get_home_path() and this one is available probably only on admin panel you have to do it in different way. You may add the following code to the end of your index.php file:
function get_robots($path)
{
$robots_file = $path . DIRECTORY_SEPARATOR . 'robots.txt'; //The robots file.
if(file_exists($robots_file)){
return file_get_contents($robots_file);
} else {
$default_content = "User-agent: *\nDisallow:";
file_put_contents($robots_file, $default_content);
return $default_content;
}
}
get_robots(getcwd());
(Of course if you want, you may move get_robots() function to some other files.
However you should consider if this is the best approach. You will run this function each time your site will be viewed and it's tiny waste (in fact you will probably want to create robots.txt file just once). You could for example create robots.php file and if you want to run it you can run http://yourwordpressurl/robots.php. It's of course your call.
I have a question and it's probably a simple one. What I would like to do is be able to place a unique name at the top of each .php file in a folder in the php code area. I would then like a script on the index.php file to look in that folder, pull out the unique names of each .php file found at the top of each page in the php code, and display them in a list on the index.php page.
Would I have to do something like this at the top of the page:
< ?
{{{{{uniquenamehere}}}}}
? >
And If so, what would the code look like for grabbing uniquenamehere and displaying in on the index.php page?
Thanks in advance, let me know if I need to be any more clear in my question. Sorry if it's a really simple question, I'm stumped!
EDIT
Getting this warning when using answer below:
Warning: file_get_contents(test.php) [function.file-get-contents]: failed to open stream: No such file or directory in /path/index.php
Here's the code I am using,
<?php
// Scan directory for files
$dir = "path/";
$files = scandir($dir);
// Iterate through the list of files
foreach($files as $file)
{
// Determine info about the file
$parts = pathinfo($file);
// If the file extension == php
if ( $parts['extension'] === "php" )
{
// Read the contents of the file
$contents = file_get_contents($file);
// Find first occurrence of opening template tag
$from = strpos($contents, "{{{{{");
// Find first occurrence of ending template tag
$to = strpos($contents,"}}}}}");
// Pull out the unique name from between the template tags
$uniqueName = substr($contents, $from+5, $to);
// Print out the unique name
echo $uniqueName ."<br/>";
}
}
?>
Not tested, but it should be roughly something like this.
<?php
// Scan directory for files
$fileInfo = pathinfo(__FILE__);
$dir = $fileInfo['dirname'];
$files = scandir($dir);
// Iterate through the list of files
foreach($files as file)
{
// Determine info about the file
$parts = pathinfo($file);
// If the file extension == php
if ( $parts['extension'] == "php" )
{
// Read the contents of the file
$contents = file_get_contents($file);
// Find first occurrenceof opening template tag
$from = strpos($contents, "{{{{{");
// Find first occurrenceof ending template tag
$to = strpos($contents,"}}}}}");
// Pull out the unique name from between the template tags
$uniqueName = substr($contents, $from+5, $to);
// Print out the unique name
echo $uniqueName ."<br/>";
}
}
The script below takes a named file that resides in the "myplugin" folder (the folder that the script itself resides in) and runs file_get_contents() on it to load the contents into memory, then does some preprocessing on the contents before finally inserting it as a post into the WordPress database via the wp_insert_post method.
$my_post3 = array();
$my_post3['post_title'] = 'Privacy Policy';
if(file_exists(ABSPATH.'/wp-content/plugins/myplugin/pages/privacy_policy.txt'))
{
$my_privacy_policy = file_get_contents(ABSPATH.'/wp-content/plugins/myplugin/pages/privacy_policy.txt');
}
else
{
$my_privacy_policy = "";
}
$my_post3['post_content'] = addslashes($my_post3_replace);
$my_post3['post_type'] = 'page';
$my_post3['post_status'] = 'publish';
wp_insert_post($my_post3);
This method works pretty good. However, this method forces me to write a different routine for every file I want to use as the basis of a new page.
What I would like to do instead, is create a folder called "pages" and place my .txt files in that, then run a for loop on the contents of the folder, creating a new page for each file in the folder. I'd like to use the file name (minus the .txt extension) as the name of the page.
For example, the pages folder may have these files:
About Us.txt
Contact Us.txt
And the routine would result in the creation of two new pages in WordPress site, one called "About Us" containing the content found in that file. The other page would of course be "Contact Us" with the contents of that file.
In this way, I can just drop an unlimited number of named and prepopulated .txt files into that folder and when I activate my plugin, it creates those pages.
I just need some help with the for loop and how to reference the folder and files.
I will also have a folder called "posts", which will do the same for posts that this routine does for pages.
Thanks in advance for your help and suggestions.
Update based on #clientbucket answer:
DEFINE ('PAGES', './pages/');
$directory_pages = new DirectoryIterator(PAGES);
foreach ($directory_pages as $files) {
if ($files_pages->isFile()) {
$file_name_page = $files_pages->getFilename();
$my_page_content = file_get_contents(PAGES. $file_name_page);
$my_page['post_content'] = addslashes($my_page_content);
$my_page['post_title'] = $file_name_page;
$my_page['post_type'] = 'page';
$my_page['post_status'] = 'publish';
wp_insert_post($my_page);
}
}
DEFINE ('POSTS', './posts/');
$directory_posts = new DirectoryIterator(POSTS);
foreach ($directory_posts as $files_posts) {
if ($files_posts->isFile()) {
$file_name_post = $files_posts->getFilename();
$my_post_content = file_get_contents(POSTS. $file_name_post);
$my_post['post_content'] = addslashes($my_post_content);
$my_post['post_title'] = $file_name_post;
$my_post['post_type'] = 'post';
$my_post['post_status'] = 'publish';
$post_id = wp_insert_post($my_post);
stick_post($post_id);
}
}
Fatal error: Uncaught exception 'UnexpectedValueException' with message 'DirectoryIterator::__construct(./pages/) [directoryiterator.--construct]: failed to open dir: No such file or directory' in C:\xampplite\htdocs\mytestsite\wp-content\plugins\myplugindirectory\myplugin.php:339
Line 339 is here > $directory_pages = new DirectoryIterator(PAGES);
Here is another way you could try.
DEFINE ('PAGES', './pages/'); //Define the directory path
$directory = new DirectoryIterator(PAGES); //Get all the contents in the directory
foreach ($directory as $files) { //Check that the contents of the directory are each files and then do what you want with them after you have the name of the file.
if ($files->isFile()) {
$file_name = $files->getFilename();
$my_page = file_get_contents(PAGES. $file_name); //Collect the content of the file.
} else {
//Insert nothing into the $my_privacy_policy variable.
}
echo $my_page; // Do what you want with the contents of the file.
}
From the PHP manual here:
http://php.net/manual/en/function.glob.php
They provide this solution for finding all text files in a directory:
<?php
foreach (glob("*.txt") as $filename) {
echo $filename . "\n";
}
?>
Given this example, your actual request is to be able to create a file based on the name in another directory. I'll leave the hard work to you - but this is a simple implementation:
<?php
$source_dir = "/your/directory/with/textfiles";
$target_dir = "/directory/to/create/files/in";
foreach (glob($source_dir . DIRECTORY_SEPARATOR . "*.txt") as $filename) {
$filepart = explode('.',$filename);
file_put_contents($target_dir . DIRECTORY_SEPARATOR . $filepart[0] . ".php");
}
?>