Active PHP code using JavaScript and URL - javascript

I have a self destruct PHP code that would delete all files and folders in my domain's directory.
<?Php
$dir = 'C:\wamp64\www\FileDirectory' . DIRECTORY_SEPARATOR . 'Files';
$it = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
$files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
foreach($files as $file) {
if ($file->isDir()){
rmdir($file->getRealPath());
} else {
unlink($file->getRealPath());
}
}
rmdir($dir);
$filename = 'C:\wamp64\www\FileDirectory\Files';
if (file_exists($filename)) {
echo "The Directory has not been deleted";
} else {
echo "All Files And Folders Are Deleted";
}
?>
I need a way to only activate this code when I type in extra code to the end of my URL. I thought you could do that with JavaScript but I'm not too certain. Please let me know if I can do this. If I have to use a different code to do so, it's not a big deal.

Use $_GET['parameter'] to get parameter from get method:
http://example.com/index.php?doClean=1
if (isset($_GET['doClean'])) {
// Your code goes here
}

Related

Working solution to get file names inside server folder

I've used multiple solutions here on Stackoverflow but I can't make any of them work properly (Nodejs is not accepted).
I have a path filled with mp3 files and I want to return the file names.
The lasted thing I tried was this:
in the getFiles folder of my server, I have a PHP file named files.php and a JS file named scripts.js and index.html
PHP code:
<?php
$dir = 'mysite/folderOf/audio/';
// Store the scandir results in a variable
$files = scandir($dir);
// Encode the array in JSON and echo it
echo json_encode($files);
?>
Javascript:
$.get( "files.php", function( data ) {
console.log(data);
});
The directory where the mp3 files exist is: mysite/folderOf/audio/
The result of the code above is:
I need to return an array with filenames of mysite/folderOf/audio/ directory.
try this if it works
<?php
// open this directory
$Directory = opendir('mysite/folderOf/audio');
// get each entry
while($entryName = readdir($Directory)) {
$fileArray[] = $entryName;
}
// close directory
closedir($Directory);
// count elements in array
sort($fileArray);
$indexCount = count($fileArray);
// loop through the array of files and print them all in a list
for($index=0; $index < $indexCount; $index++) {
$extension = substr($fileArray[$index], -3);
if ($extension == 'mp3'){
echo '<a class="iconMP3" href="mysite/folderOf/audio/' . $fileArray[$index] . '"/>' . $fileArray[$index] . '</a>';
}
}
?>

PHP - Create a directory listing of specified folder

I've got small piece of code which I'm using to scan a certain directory on my server for all the files and folders inside. But there's a catch... It can only scan the specified folder, and no sub-directories. Let's say share/ is the root directory for this scan, if there are files in any sub-directory like share/folder/file.png they won't be listed, where the entire purpose of my project is to create an HTML file explorer.
This is the code I'm using to receive the list of files from the server to later display it in the browser using JavaScript:
<?php
$listFiles = array();
if ($handle = opendir('./share')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
$listFiles[] = $entry;
}
}
closedir($handle);
}
$FS_files = json_encode($listFiles);
?>
And then I "push" it rude to my actual JavaScript code like this:
let FS_files = <?php echo $FS_files ?>
The code I above basically generates an array of file names from scanned directory. What I wanna know is how can I get an entire JSON tree of files in this directory and all folders inside it, or possibly change my code so it works that way?
<?php
function scanFolder($dir) {
$result = array();
$cdir = scandir($dir);
foreach ($cdir as $key => $value) {
if (!in_array($value,array(".",".."))) {
if (is_dir($dir . DIRECTORY_SEPARATOR . $value)) {
$result[$value] = scanFolder($dir . DIRECTORY_SEPARATOR . $value);
} else {
$result[] = $value;
}
}
}
return $result;
}
$FS_files = json_encode(scanFolder("./share"));
?>
The function scans the folder and checks each entry with is_dir. If its true, this folder is scanned with the same function.

Codeigniter: write_file() returns false

public function ExportCSV()
{
// THIS PART IS WORKING
$this->load->dbutil();
$this->load->helper('file');
$delimiter = ',';
$newline = "\n";
$enclosure = '"';
$filename = "tamp.csv";
$query = "SELECT politician.id, politician.ident, party.abbr, politician.id_image, politician.name, politician.surname, politician.personal_birth, politician.home_city, politician.political_function
FROM politician
INNER JOIN party
WHERE party.id = politician.id_party
LIMIT 10000";
$result = $this->db->query($query);
$data = $this->dbutil->csv_from_result($result, $delimiter, $newline, $enclosure);
// data IS CORRECT
// THIS PART NOT WORKING: write_file() returns false
if ( ! write_file(APPPATH."/assets/media/upload/tamp.csv", $data, 'r+'))
{
echo 'Unable to write the file';
}
else
{
echo 'File written!';
}
}
The variable $data contains the correct output but the write_file() returns false.
The directory /assets/ is in the main directory of the codeigniter project.
My questions are:
Is this function returning false because I don't have the permission to write in this directory?
If yes, what should I do?
In which directory should I write this file as I would like it public?
When creating a file with write_file make sure your folder/directory is there where you would like to create file
Then I would recommend using FCPATH
$data = "Some file data";
if (write_file(FCPATH . '/document/text.txt', $data) == FALSE)
{
echo 'Unable to write the file';
} else {
echo 'File written!';
}
My directory
application
document
system
index.php

get all images in an array from directory and sub-directories

Currently I've similar to the following tree structure:
+images
+sub-directory
-image1.jpg
-image2.jpg
+sub-directory-2
-image3.jpg
-image4.jpg
-some-image.jpg
-another.jpg
<script>
<?php
//path to directory to scan. i have included a wildcard for a subdirectory
$directory = "images/*/";
//get all image files with a .jpg extension.
$images = glob("" . $directory . "*.jpg");
$imgs = '';
// create array
foreach($images as $image){ $imgs[] = "$image"; }
echo "var allImages = ".$imgs.";\n";
?>
console.log(allImages);
</script>
As I'm extremely new to php, I'm blindly getting logged as Array() in the console.
Also, I've set $directory = "images/*/"; which will get all images inside the subfolders only but not getting images inside parent directory that likely to images/some-image.jpg and I wanted to get this too.
I want all the images in an array like this (when I use console.log(allImages);):
['some-image.jpg','another.jpg','image1.jpg','image2.jpg','image3.jpg','image4.jpg']
I love JSON, keeps things nice and simple:
<?php
$images = glob("images/*/*.jpg");
$imgs = array();
foreach($images as $image){ $imgs[] = $image; }
?>
<script>
var allImages = JSON.parse('<?php echo json_encode($imgs);?>');
console.log( allImages);
</script>
Now you have the php array available in javascript, with the same structure. You can loop them with a for, of if you have jQuery, $.each().
I changed a code more to your style (mixing php and html), but you should try to split those in htmltemplates.
Im not 100% sure about this, but you can regex in your glob, if this works you don't need the foreach, this will return only the filenames:
$images = glob("~(?:images/*/)*\.jpg~");
What about this:
<script>
<?php
$directory = "images/*/";
$images = glob("" . $directory . "*.jpg");
echo "var allImages = ['".implode("', '", $images)."'];\n";
?>
console.log(allImages);
</script>
How about a recursive function?
function loadImages($folder)
{
$files = glob($folder);
foreach( $files as $file )
{
if(is_dir($file))
{
loadImages($file);
} else {
$images[] = $file; // add some file type validation here
}
}
return $images;
}
$images = json_encode(loadImages($startFolderPath));
I'm on an iPad so I can't test it.

Class Not Found Error in PHP

I am a rookie PHP and MongoDB developer.
I have created a PHP web project with an HTML page that contains an 'Add' button. The name of the page is awards.html. The awards.html file contains its counterpart JavaScript file, awards.js. A code is executed in this js file when the Add button is clicked. This code sends an AJAX call to a PHP class elsewhere in the project named, example.php which contains code to execute a function called, clickFunction() in an Awards.php file, which returns a JSON array to the awards.html page.
The source code of my files is given as follows:
Awards.html
<div class = "divbottom">
<div id="divAddAward">
<button class="btn" onclick="onrequest();">Add</button>
</div>
</div>
awards.js
function onrequest() {
$("#divAddAward").load('branding/dataaccess/example.php'); //The full path of the example.php file in the web root
alert('Test');
$.post(
'branding/dataaccess/example.php'
).success(function(resp) {
json = $.parseJSON(resp);
alert(json);
});
}
example.php
<?php
foreach (glob("App/branding/data/*.php") as $filename) {
include $filename;
}
$class = new Awards();
$method = $class->clickFunction();
echo json_encode($method);
Awards.php
<?php
class Awards extends Mongo_db {
//put your code here
public function __construct() {
parent::__construct();
}
public function clickFunction() {
$array = array(
'status' => '1'
);
return $array;
}
}
The problem here is that the program is throwing me an error in example.php, Class 'Awards' not found, despite adding the for loop to include all the files. The Awards.php file is located in App/branding/data/ path and example.php is located in App/branding/dataaccess/ path.
Can anyone please tell me where exactly am I going wrong? Replies at the earliest will be highly appreciated. Thank you in advance.
My guess: as you said, example.php is located in App/branding/dataaccess/, so when you do your loop you're actually searching for files in App/branding/dataccess/App/branding/data which doesn't exist so nothing is included.
Try this:
foreach (glob("../data/*.php") as $filename) {
include $filename;
}
Update example.php to
<?php
foreach (glob('../data/*.{php}', GLOB_BRACE) as $filename) {
//Echo out each included file to make sure it's included
echo $filename . '<br />';
include $filename;
}
$class = new Awards();
$method = $class->clickFunction();
echo json_encode($method);
hmm.. try to use spl_autoload_register(); to include or require all files at once on example.php
spl_autoload_register(function($class){
require_once '../data/' . $class . '.php';
});

Categories