How to detect if a folder is having a WordPress installation or not ?
WP-CLI does that and gives the error This does not seem to be a WP installation, and detects correctly if the directory has a WP install even if it is in any of the subfolders (wp-includes/images or wp-includes/js ) .
I went through the code and it searches for index.php and compares content with the original index.php . One more thing it does is to check for the presence of wp-includes/version.php . Got the idea but how it works on subfolders like those mentioned above is still not clear . Do anybody have any idea on how to do this ? Thanks in advance .
Look for the wp-config.php file. If you find it, require it, then try to use its constants DB_HOST, DB_USER, DB_PASSWORD and DB_NAME to connect to the WordPress database associated with the WordPress instance. If that works, you very likely have a working WordPress instance.
If your current working directory doesn't have wp-config.php look at parent directories recursively until you (a) find it or (b) come to the top level directory.
wp-cli does more elaborate things. But this should work for you.
So i have scribbled a script that detects a WP install . It works as expected inside a wp install folder , but if it is not inside a WordPress install it executes an infinite loop . Can somebody guide on how to stop at top level directory as mentioned by #O.Jones ? Here is my code .
<?php
function get_wp_index($dir=null) {
if(is_null($dir)){
$dir = getcwd();
}
echo "Currently Looking \n";
echo $dir;
$name = $dir.DIRECTORY_SEPARATOR."index.php";
if ( file_exists( $name ) ) {
$index_code = (file_get_contents($name));
if ( preg_match( '|^\s*require\s*\(?\s*(.+?)/wp-blog-header\.php([\'"])|m', $index_code, $matches ) ) {
echo "Is a WP Install";
return;
} else {
echo "Has index File but not one with wp-blog-header";
echo "\n\n";
//Go one directory up
$up_path = realpath($dir. DIRECTORY_SEPARATOR . '..');
get_wp_index($up_path);
}
} else {
echo 'No Index File Found';
echo "\n\n";
//Go one directory up
$up_path = realpath($dir. DIRECTORY_SEPARATOR . '..');
echo $up_path;
get_wp_index($up_path);
}
}
get_wp_index();
?>
Related
What I'm trying to do:
Use PHP ftp_nlist to retrieve the contents of a directory on the FTP server
The problem:
For directories that contain a lot of files (the one I encountered the problem on has nearly 40 thousand files, and no subfolders), the ftp_nlist function is returning false. For directories that are not as large, the ftp_nlist function returns an array of filenames as expected.
What I've tried:
Enabling passive mode (it already was enabled, but I see it as a common suggestion)
Adding ftp_set_option($conn_id, FTP_USEPASVADDRESS, false); after my ftp_login
using ftp_chdir, although my folder names never have spaces anyways
echoing error_get_last() after ftp_nlist returns false. The error show seems unrelated, but is shown below.
My code:
In case it is useful, here is the function I have created. What it is supposed to do is...
take in $fm (filemaker, unrelated to this problem)
take in $FTPConnectionID (the ftp connection I established in the prior to the function call)
take in $FolderPath (the path of the folder on the FTP server for which I want to list files/subfolders recursively - ex: "SomeFolder/Testing")
take in $TextFile (I am writing the paths of every file found on the FTP server to a text file, which was created prior to calling the function)
function createAuditFile($fm, $FTPConnectionID, $FolderPath, $TextFile) {
echo "createAuditFile called for " . $FolderPath . "\n";
//Get the contents of the given path. Will include files and folders.
$FolderContents = ftp_nlist($FTPConnectionID, $FolderPath);
if($FolderContents == false) {
echo "Couldn't get " . $FolderPath . "\n";
echo "ERROR: " . print_r(error_get_last()) . "\n";
} else {
print_r($FolderContents);
}
//Loop through the array, call this function recursively if a folder is found.
if(is_array($FolderContents)) {
foreach($FolderContents as $Content) {
//Create a varaible for the folder path
$ContentPath = $FolderPath . "/" . $Content;
//Call the function recursively if a folder is found
if(pathinfo($Content, PATHINFO_EXTENSION) == "") {
createAuditFile($fm, $FTPConnectionID, $ContentPath, $TextFile);
echo "Recursive call for " . $ContentPath . "\n";
//If a file is found, add the file ftp path to our array
} else {
echo "Writing to file: " . $ContentPath . "\n";
fwrite($TextFile, $ContentPath . "\n");
}
}
}
}
I can provide other code if needed, but I think my question is less of a coding issue, and more of an understanding ftp_nlist issue. I've been stuck on this for hours, so any help is appreciated. And like I said, this function works just fine for most folder paths passed to it, the problem is when there are tens of thousands of files within the folder. Thank you!
<?php
if (isset($_POST['filename']) && isset($_POST['editorpassword']) && isset($_POST['roomname'])) {
$dir = $_POST['filename']; // This must match the "name" of your input
$path = "evo/" . $dir;
if (!file_exists($path)) {
mkdir($path, 0755, true);
}
}
?>
I have this script where I'm trying to create a new folder. The script itself is ran inside of a folder called /evo and by using this code, it creates the folder in there. Where it needs to go is ../../creative however even if I try and use
$path = "./rooms/creative/" . $dir;
or something to that effect it creates it with the base folder as evo so it appears at:
../evo/rooms/creative (creating the folders that don't exist there with it as it should)
I'm just unsure what to write in for the path on where I need it created to find the right location.
Simplest solution is to remove the "evo" in $path = "evo/" . $dir;
I'm attempting to try and debug the following code with the file_exists function. I've ran a var_dump on the avatar directory and it always returns as bool(false). I'm not sure why. I tested the code below and it gets to the file exists but it proves the if statement false everytime. Any thoughts? I have looked and the image is in the directory correctly.
$default_avatar = 'default.jpg';
$avatar_directory = base_url() . 'assets/globals/images/avatars/';
if (!is_null($user_data->avatar))
{
$avatar = $avatar_directory . $user_data->avatar;
if (file_exists($avatar))
{
$user_data->avatar = $avatar_directory . $user_data->avatar;
}
else
{
$user_data->avatar = $avatar_directory . $default_avatar;
}
}
else
{
$user_data->avatar = $default_avatar;
}
$default_avatar = 'default.jpg';
$avatar_directory = 'assets/globals/images/avatars/';
if (!is_null($user_data->avatar))
{
$avatar = $avatar_directory . $user_data->avatar;
if (file_exists(FCPATH . $avatar))
{
$user_data->avatar = base_url() . $avatar_directory . $user_data->avatar;
}
else
{
$user_data->avatar = base_url() . $avatar_directory . $default_avatar;
}
}
else
{
$user_data->avatar = $default_avatar;
}
from the name base_url seems like a function that will get a url like http://www.mysite.com, which will not work for doing local directory functions.
you need something like getcwd, or a full path
getcwd will get the current working directory (the directory where the initial script was executed from):
//If say script.php was exectued from /home/mysite/www
$avatar_directory = getcwd() . '/assets/globals/images/avatars/';
//$avatar_directory would be
/home/mysite/www/assets/globals/images/avatars/
Well this works both CLI and via Apache etc...:
$avatar_directory = substr(str_replace(pathinfo(__FILE__, PATHINFO_BASENAME), '', __FILE__), 0, -1) . '/assets/globals/images/avatars/'
The did returned is the one that the php file itself is in, not the root.
assuming you meant base_url() to point to the root of your project -
$file = __DIR__ . "/path/to/file.ext";
if (file_exists($file)) {
//...
}
Or some variation thereof. This also works:
__DIR__ . "/.."
it resolves to the parent directory of __DIR__.
see PHP's magic constants:
http://php.net/manual/en/language.constants.predefined.php
If you are looking for a remote resource - a file not located on your local filesystem - you have to change your php.ini to permit that. And it's probably not a good idea, this is not usually considered safe or secure. At all.
http://php.net/manual/en/features.remote-files.php
And note:
"This function returns FALSE for files inaccessible due to safe mode restrictions. However these files still can be included if they are located in safe_mode_include_dir."
-- from http://php.net/manual/en/function.file-exists.php
-- edited to add relevant information based on a comment from OP.
I'm making a Wordpress theme, basically for portfolios.
Making plugins into the theme is bad, since changing themes can become a problem for the user and yourself if you do so. So I'm cooking up some script, that takes a plugins folder I made in my theme, which has the plugins that I would have built into the theme, but I'm making them install themselves when you select my theme. So these plugins will be updatable through the dashboard, and auto installed (if not already installed), into the site. Good idea no? (I got it from a forums post, but I dont think its been done as far as I know).
So I have a plugins folder in my theme, which has the plugins I want to auto install. I want to copy the plugins(single files or directories) into the wp-content/plugins folder and then install/activate them.
The problem is when I try to copy, it gives an error
Warning: copy(http://127.0.0.1/inside-theme/wordpress/wp-content/plugins): failed to open stream: HTTP wrapper does not support writeable connections in C:\**path-to-www-**\www\inside-theme\wordpress\wp-content\themes\Inside Theme\header.php on line 105
If you're wondering about why it's in header.php, I'm just doing this for testing purposes to see if it copies. I will put it in a hook after.
Here is my code I'm using to copy the plugins,
$dir = get_template_directory() . '/plugins/'; // the plugins folder in the theme
$plugins_in_theme = scandir($dir); // $dir's contents
$plugins_dir = plugins_url(); // url to the wp-content/plugins/
print_r($plugins_in_theme); // just to check the output, not important
foreach ($plugins_in_theme as $plugin) {
if ($plugin != '.' || '..') {
if (!file_exists($plugins_dir . $plugin)) {
if (is_dir($plugin)) {
recurse_copy($dir . $plugin, $plugins_dir);
} else {
copy($dir . $plugin, $plugins_dir);
}
}
}
}
recurse_copy() is a function I picked up off another stackoverflow question for copying directories since copy() only copies files, not folders. Also note that, it gives multiple errors, with the functions.php of my theme mentioned in most errors, which is where I put the recursive_copy() function. (Is that ok? It's my first theme..)
function recurse_copy($src,$dst) { //for copying directories
$dir = opendir($src);
#mkdir($dst);
while(false !== ( $file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
if ( is_dir($src . '/' . $file) ) {
recurse_copy($src . '/' . $file,$dst . '/' . $file);
}
else {
copy($src . '/' . $file,$dst . '/' . $file);
}
}
}
closedir($dir);
}
So how can I remove this error and get it to work?
Extra details,
I'm using windows xp and I'm using the 'handcrafted wp' parent theme, I AM RUNNING THIS LOCALLY. (on local host)
Hope I was clear.
You are using $plugins_dir = plugins_url(); in the code which returns http://yoursite/wp-content/plugins/ However, copy function works with directories not URLs, so it's better to use, ABSPATH, dirname( __FILE__ ) . '/blablabla.php' and other functions returning directories not URLs. Click here to learn more about PHP copy function
I am looking for a way to list the names of every folder in a directory and their path in PHP
Thank you
What you are referring to is not a page from WAMPP, it is a default setting to show files and folders on any (if not most) web servers... This is usually switched off by the web server config, or .htaccess files
You are looking for some PHP code to do a similar thing, the following PHP functions are what you will need to look into, read the pages and view the examples to understand how to use them... Do not ignore "Warning" or "Important" messages on these pages from php.net:
opendir - Creates a handle to a directory for reading
readdir - Reads files/folders inside a dir
rmdir - Deletes a folder (must be empty)
mkdir - Creates a folder
Here is an example:
<?php
$folder = "myfolder";
if ($dhandle = opendir($folder)) {
while ($file = readdir($dhandle)) {
// Ignore . and ..
if ($file<>'.' && $file<>'..')
// if it's a folder, echo [F]
if (is_dir("$folder/$file")) echo "[F] $file<br>"; else
echo "$file<br>";
}
closedir($dhandle);
}
?>
Important
Remember that on a linux OS, your Apache/PHP must have access to the folder in question before it can write/delete files and folders... Read up on chmod, chown and chgrp
use the following function to get the path of the files/folders
<?php
function getDirectory( $path = '.', $level = 0 ){
$ignore = array( 'cgi-bin', '.', '..' );
// Directories to ignore when listing output. Many hosts
// will deny PHP access to the cgi-bin.
$dh = #opendir( $path );
// Open the directory to the handle $dh
while( false !== ( $file = readdir( $dh ) ) ){
// Loop through the directory
if( !in_array( $file, $ignore ) ){
// Check that this file is not to be ignored
$spaces = str_repeat( ' ', ( $level * 4 ) );
// Just to add spacing to the list, to better
// show the directory tree.
if( is_dir( "$path/$file" ) ){
// Its a directory, so we need to keep reading down...
echo "<strong>$spaces $file</strong><br />";
getDirectory( "$path/$file", ($level+1) );
// Re-call this same function but on a new directory.
// this is what makes function recursive.
} else {
echo "$spaces $file<br />";
// Just print out the filename
}
}
}
closedir( $dh );
// Close the directory handle
}
getDirectory( "." );
?>
There is an simple solution to this problem :(if you are using linux only )
you want list the names of every folder in a directory and their path in PHP .
you can use
find
command in conjuction with PHP's
exec();
function
the following snippet shows this
<?php
$startdir = "Some Directory" ; // the start directory whose sub directories along with path is needed
exec("find " . $startdir . " -type d " , $directories); // executes the command and stores the result in array $directory line by line
while(list($index,$dir) = each($directories) ) {
echo $dir."<br/>"; //lists directories one by one
}
?>
foot notes:
command ,
find dirname -type d
lists all the directories and subdirectories under folder startdir
This is a php code save this as index.php and put it in your web root directory.
<?php
$pngFolder = <<< EOFILE
iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAA3NCSVQICAjb4U/gAAABhlBMVEX//v7//v3///7//fr//fj+/v3//fb+/fT+/Pf//PX+/Pb+/PP+/PL+/PH+/PD+++/+++7++u/9+vL9+vH79+r79+n79uj89tj89Nf889D88sj78sz78sr58N3u7u7u7ev777j67bL67Kv46sHt6uP26cns6d356aP56aD56Jv45pT45pP45ZD45I324av344r344T14J734oT34YD13pD24Hv03af13pP233X025303JL23nX23nHz2pX23Gvn2a7122fz2I3122T12mLz14Xv1JPy1YD12Vz02Fvy1H7v04T011Py03j011b01k7v0n/x0nHz1Ejv0Hnuz3Xx0Gvz00buzofz00Pxz2juz3Hy0TrmznzmzoHy0Djqy2vtymnxzS3xzi/kyG3jyG7wyyXkwJjpwHLiw2Liw2HhwmDdvlXevVPduVThsX7btDrbsj/gq3DbsDzbrT7brDvaqzjapjrbpTraojnboTrbmzrbmjrbl0Tbljrakz3ajzzZjTfZijLZiTJdVmhqAAAAgnRSTlP///////////////////////////////////////8A////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////9XzUpQAAAAlwSFlzAAALEgAACxIB0t1+/AAAAB90RVh0U29mdHdhcmUATWFjcm9tZWRpYSBGaXJld29ya3MgOLVo0ngAAACqSURBVBiVY5BDAwxECGRlpgNBtpoKCMjLM8jnsYKASFJycnJ0tD1QRT6HromhHj8YMOcABYqEzc3d4uO9vIKCIkULgQIlYq5haao8YMBUDBQoZWIBAnFtAwsHD4kyoEA5l5SCkqa+qZ27X7hkBVCgUkhRXcvI2sk3MCpRugooUCOooWNs4+wdGpuQIlMDFKiWNbO0dXTx9AwICVGuBQqkFtQ1wEB9LhGeAwDSdzMEmZfC0wAAAABJRU5ErkJggg==
EOFILE;
if (isset($_GET['img']))
{
header("Content-type: image/png");
echo base64_decode($pngFolder);
exit();
}
$projectsListIgnore = array ('.','..');
$handle=opendir(".");
$projectContents = '';
while ($file = readdir($handle))
{
if (is_dir($file) && !in_array($file,$projectsListIgnore))
{
$projectContents .= '<li>'.$file.'</li>';
}
}
closedir($handle);
?>
<ul class="projects">
<?php $projectContents ?>
</ul>