So, I have a sidebar.php that is included in the index.php. Under a certain condition, I want sidebar.php to stop running, so I thought of putting exit in sidebar.php, but that actually exits all the code beneath it meaning everything beneath include('sidebar.php'); in index.php all the code would be skipped as well. Is there a way to have exit only skip the code in the sidebar.php?
Just use return;
Do also be aware that it is possible to actually return something to a calling script in this way.
if your parent script has $somevar = include("myscript.php"); and then in myscript.php you do say... return true; you will get that value in $somevar
Yes, you just use return;. Your sidebar.php file might look something like this:
<?php
if($certain_condition) {
return;
} else {
// Do your stuff here
}
?>
I know this is a really old question, but I've recently taken over the code base of another developer who used exit religiously, meaning that the parent file that included various files had to be designed in such a way that the include of the module files were done at the end so it didn't cut off the page. I wrote a small PHP script to replace all occurrences of "exit;" with "return;".
if($handle = opendir("path/to/directory/of/files")) {
while(false !== ($file = readdir($handle))) {
if("." === $file) continue;
if(".." === $file) continue;
$pageContents = file_get_contents($file);
$pageContents = str_replace("exit;", "return;", $pageContents);
file_put_contents($file, $pageContents);
echo $file . " updated<br />";
}
}
I hope this helps someone.
Related
So, if i have a file that when its empty it requires a specific function, but if the file is NOT empty it will proceed to show (else) something else. This is currently the format I am using. I have tired several different manners and variations of doing so (from PHP Manual examples to StackOverFlow Q/A). What it is doing is showing me the else not the if, since the file is actually empty...
<?
$file = 'config/config2.php';
if(!empty($file))
{
some code here!
}
else
{
some other code here!
}
?>
<?
$file = 'config/config2.php';
if(filesize($file)!=0)// NB:an empty 'looking' file could have a file size above 0
{
some code here!
}
else
{
some other code here!
}
?>
The problem seems to be that you are not actually loading the file before you check if it is empty.
You are only setting the variable $file to the string 'config/config2.php' not actually loading the file.
Before running your if statement do this:
$file = file_get_contents('config/config2.php');
or look into this: http://php.net/manual/en/function.fopen.php
I'm trying to write some PHP that runs through a folder grabbing each sub directory name and assigning it to a variable. Then, open a URL with that variable.
For example, D:Folder contains a number of sub folders named 1-??.
The PHP would first open www.url.com/run_batch.php?q=1 and sleep for 30 seconds, then www.url.com/run_batch.php?q=2, etc... for each sub directory in the main directory.
I'm currently in the process of trying to write this. I don't have much code yet, but thought one of you geniuses could help me speed up this process.
UPDATED
Ok, here is what I have so far, it runs without any errors, but it appears to be running all of them at once without sleeping? Not sure, the page just stays busy.
<?php
if ($handle = opendir('D:\HTTP\pic\')) {
$blacklist = array('.', '..', 'bu');
while (false !== ($file = readdir($handle))) {
if (!in_array($file, $blacklist)) {
echo "<iframe width='800' height='600' src='http://www.url.com/run_batch.php?q=" . "$file" . "'></iframe>";
sleep(100);
}
}
closedir($handle);
}
?>
When you make a sleep in PHP code, the HTML is not sent to the browser, that is why it looks busy.
You have to call flush() on each pass.
<?php
if ($handle = opendir('D:\HTTP\pic\')) {
$blacklist = array('.', '..', 'bu');
while (false !== ($file = readdir($handle))) {
if (!in_array($file, $blacklist)) {
echo "<iframe width='800' height='600' src='http://www.url.com/run_batch.php?q=" . "$file" . "'></iframe>";
//Send content to browser
flush();
sleep(100);
}
}
closedir($handle);
}
?>
I suggest you start with pseudo code; create comments for the steps. From there, look at PHP.net for help with specific tasks. When you have something workable but buggy, paste your code.
Pseudocode:
// get directory list
// loop through directories
// ...
// redirect to next page
I have a couple of PHP scripts for deleting error_log, .DS_Store etc files from all folders on my entire server. I simply have these scripts uploaded to my root (public_html) and visit them periodically when I want to do a little cleanup. When I visit the URL of where the scripts are loaded it automatically gets to work. That's all perfect and how I'd like to continue using it.
However, I'd love to consolidate this automation into just one script where I can list an array of the undesirable files like so:
$unwanted_filenames = array(
'.DS_Store',
'.localized',
'Thumbs.db',
'error_log'
);
And simply run through all folders and delete all the files of which I've listed in the array.
The scripts I use now are overkill, listing out every individual file and how much it's freed up etc. I'm a minimalist and would love the simplest script with the least amount of code to just get the job done.
So when I visit the page it automatically get's to work, a white screen of nothing is fine and then maybe a simple "Done. Freed up 3MB." message. That's it.
OK - here's the shortest but of PHP I can think of that'll do it:
$unwanted_filenames = array(
'.DS_Store',
'.localized',
'Thumbs.db',
'error_log'
);
$it = new RecursiveDirectoryIterator("/"); // Set starting directory here
foreach(new RecursiveIteratorIterator($it) as $file) {
if (in_array(basename($file), $unwanted_filenames)) {
#unlink($file); // THe # hides errors, remove if you want to see them
}
}
Hopefully self-explanatory - and yes, it does subdirectories (that's the "recursive" bit).
And you said minamalistic, so I didn't include the freed space, but just add a $FreedSpace += filesize($file) before the unlink if you want to add that in.
I'm using this, you can do it like this:
<?php
$dir = "/var/www/vhosts/"; //Write your dirname here
$rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
$total_thumbs = 0;
$total_ds = 0;
foreach ($rii as $file) {
if ($file->isDir()){
continue;
}
$parcala = explode('.', $file->getFilename());
$uzanti = end($parcala);
if ($file->getFilename() == 'Thumbs.db') {
unlink($file->getPathname());
$total_thumbs++;
}
if ($uzanti == '.DS_Store' || $file->getFilename() == 'DS_Store' || $file->getFilename() == '.DS_Store') {
unlink($file->getPathname());
$total_ds++;
}
}
echo $total_thumbs . ' Thumbs.db file and ' . $total_ds . ' DS_Store file deleted!';
And if you want automation you can use Cronjob
I have a virus that has infected thousands of files on one of my client's server.
Fortunately, I have dealt with a lot of other malware on this guy's server and this one looks easy to do simple regex on (he put all his websites on the same account :( but I'm working with him to resolve that).
Basically though, unlike most malware I have seen where it injects php BEFORE the closing ?> of the GOOD code (making it very hard to determine whats good code/bad code), this current malware ALWAYS adds a new <?php ... malware ... ?>.
So basically, say there's good code here:
<?php
require('./wp-blog-header.php');
?>
Instead of adding some kind of base64_decode eval immediately after the require statement but before the ?> (which can make removal difficult when the page happens to end in a conditional/complex statement), this will always add the following code with a NEW <?php ... ?> like so:
<?php
require('./wp-blog-header.php');
?><?php ... malware ...?>
I don't want to put any malicious code up here but, this is how the malicious code always starts:
<?php #error_reporting(0); if (!isset($eva1fYlbakBcVSir)) {$eva1fYlbakBcVSir = "tons and tons of characters";$eva1tYlbakBcVSir = "\x6335\1443\3x6f\1534\x70\170\x65";$SNIPSNIPSNIPSNIP;} ?>
I'd like to search every file for <?php #error_reporting(0); if (!isset and if it's the last PHP statement on the page, then delete everything within the
Here is how you clean the entire project with pure php.
In no respect shall I incur any liability for any damages, including,
but limited to, direct, indirect, special, or consequential damages
arising out of, resulting from, or any way connected to the use of the
code provided, whether or not based upon warranty, contract, tort, or
otherwise; whether or not injury was sustained by persons or property
or otherwise; and whether or not loss was sustained from, or arose out
of, the results of, the use if this code. ;p
<?php
//Enter it as it is and escape any single quotes
$find='<?php #error_reporting(0); if (!isset($eva1fYlbakBcVSir)) {$eva1fYlbakBcVSir =\'\';?>';
echo findString('./',$find);
function findString($path,$find){
$return='';
ob_start();
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if(is_dir($path.'/'.$file)){
$sub=findString($path.'/'.$file,$find);
if(isset($sub)){
echo $sub.PHP_EOL;
}
}else{
$ext=substr(strtolower($file),-3);
if($ext=='php'){
$filesource=file_get_contents($path.'/'.$file);
$pos = strpos($filesource, $find);
if ($pos === false) {
continue;
} else {
//The cleaning bit
echo "The string '".htmlentities($find)."' was found in the file '$path/$file and exists at position $pos and has been removed from the source file.<br />";
$clean_source = str_replace($find,'',$filesource);
file_put_contents($path.'/'.$file,$clean_source);
}
}else{
continue;
}
}
}
}
closedir($handle);
}
$return = ob_get_contents();
ob_end_clean();
return $return;
}
?>
Good Luck.
UPDATE (With Regex):
<?php
error_reporting(E_ALL);
$find='<\?php #error_reporting\(0\); if \(!isset\((.*?)\?>';
echo findString('./',$find);
function findString($path,$find){
$return='';
ob_start();
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if(is_dir($path.'/'.$file)){
$sub=findString($path.'/'.$file,$find);
if(isset($sub)){
echo $sub.PHP_EOL;
}
}else{
$ext=substr(strtolower($file),-3);
if($ext=='php'){
$filesource=file_get_contents($path.'/'.$file);
//The cleaning bit
echo "The string '".htmlentities($find)."' was found in the file '$path/$file and has been removed from the source file.<br />";
$clean_source = preg_replace('#'.$find.'#','',$filesource);
// $clean_source = str_replace($find,'',$filesource);
file_put_contents($path.'/'.$file,$clean_source);
}else{
continue;
}
}
}
}
closedir($handle);
}
$return = ob_get_contents();
ob_end_clean();
return $return;
}
?>
So far this is the closest (thank you mvds)
sed -e "s/<?php #error_reporting.*?>//g" --in-place=_cleaned *
although --in-place=_cleaned is giving the error sed: illegal option -- -
I use php files in my website and in those file I include my html to show whatever i want the user to view. However i've ran into a problem. I need to show a list of available downloads from a specific folder from my website. The uploading downloadables from my website works. The reading files from directory works, this is done using php code. Now the thing is how can I show this in my html, how to I show this to my user in a fashion that i like most, like for example how Dropbox shows their file listing something like that.
The thing is to pass those files found within the PHP file and pass them to the html to be able to work with them however I want.
I hope i am clear, in case please just tell me so I can elaborate more.
Thanks.
Some code as requested, this is how I am supposedly extracting my files from my website's directory...
Ahh something like this, i get the idea, but here is my problem...
my code looks like this...
$directory_mine;
if ($directory_mine = opendir('/path/to/files')) {
//This is for testing.
echo "Directory: ". $directory_mine . "\n";
echo "Entries:\n";
while (false !== ($entry = readdir($directory_mine))) {
//should be writing each file name into the html here. at least thats my thinking.
}
closedir($directory_mine);
}
include("overall_header.html");
include("mobiledownloadview.html");
include("overall_footer.html");
See here is the problem, how can i add the data extracted by my php file to the mobiledownloadview.html???
I believe this is one way to do it, but if this is terrible please tell me. is there a better way to acomplish my goal?
From the manual on readdir:
<?php
if ($handle = opendir('/path/to/files')) {
echo "Directory handle: $handle\n";
echo "Entries:\n";
/* This is the correct way to loop over the directory. */
while (false !== ($entry = readdir($handle))) {
echo "$entry\n";
}
/* This is the WRONG way to loop over the directory. */
while ($entry = readdir($handle)) {
echo "$entry\n";
}
closedir($handle);
}
?>
If you want to style it, wrap it in an (un-) ordered list and use css for that.
while ($entry = readdir($directory_mine)) !== false) {
echo "Entry: $entry ; filetype: " . filetype($directory_mine . $entry) . "\n";
}
If you're using PHP 5.3+, the PHP SPL class FilesystemIterator could be useful in this case, it easily allows iterating over a certain path and retrieving files as objects, including metadata.
http://www.php.net/manual/en/class.filesystemiterator.php
Example:
<?php
$it = new FilesystemIterator($directory_mine);
echo '<ul class="file_list">'
foreach ($it as $fileinfo) {
echo '<li>' . $fileinfo->getFilename() . '</li>' . PHP_EOL;
}
echo '</ul>'
You can add CSS to the page to style the unordered list how you want it to appear.