This is section of code that I have put in /pgen/admin
<h1><b>List of saved text files:</b></h1>
<?php
$directory = "/pgen/saves/";
$phpfiles = glob($directory . "*.html");
$id = 1;
foreach ($phpfiles as $phpfile) {
$date = " last modified/date created: " . date ("F d Y H:i:s.", filemtime($phpfile));
echo $id.". <a href=$phpfile>".basename($phpfile)."</a>" .$date."<br>";
$id ++;
}
?>
The $directory variable is supposed to be the root of the webpage plus /pgen/saves/.
I have tried using $_SERVER["DOCUMENT_ROOT"]."/pgen/saves".
Also, if I browse using a ftp client, it shows this page is located at /public_html/pgen/admin/ because I am using a 3rd party hosting service.
The code is supposed to list the files in the /pgen/saves folder but the code itself is in the /pgen/admin folder. I've searched everywhere and since I'm new at php, I don't know what to do.
You would be better off to add some error checking/validation to your efforts. When using a foreach() method on an array, you must be aware that it is trusting you to pass it a legit array. If the value passed is not an array, it will try to use it and fail.
$directory = "/pgen/saves/";
$phpfiles = glob($directory . "*.html");
$id = 1;
// Error if no files are found
if (!is_array($phpfiles) && count($phpfiles) <= 0) {
die('no files found');
}
// Otherwise, continue on
foreach ($phpfiles as $phpfile) {
$date = " last modified/date created: " . date ("F d Y H:i:s.", filemtime($phpfile));
echo $id.". <a href=$phpfile>".basename($phpfile)."</a>" .$date."<br>";
$id ++;
}
Related
I'm new in php.
Every 17 seconds my php code generates id1.php and id2.php in this folder:"sitename.com/"
So, every 17 seconds i've got this:
sitename.com/master.php
sitename.com/id1.php
sitename.com/id2.php
sitename.com/filebag/id1.php
sitename.com/filebag/id2.php
sitename.com/filebag/id3.php
after script generates id1.php and id2.php i need to copy this files to sitename/filebag/ and if filename exist add +1. so in the end, i must get this situation:
sitename.com/
sitename.com/master.php
sitename.com/filebag/id1.php
sitename.com/filebag/id2.php
sitename.com/filebag/id3.php
sitename.com/filebag/id4.php
sitename.com/filebag/id5.php and so on...
i use master.php to do a replace
<?php
$idname = "id1";
copy ("./id1.php","./filebag/$idname.php");
?>
question is how can i rename file if filename exist in this folder "sitename.com/filebag/"
This code delivers what you want:
<?php
$stringName = "id";
$numName = "1";
$file_orig = './' . $stringName . $numName . '.php';
$file_dest = './filebag/' . $stringName . $numName . '.php';
if(file_exists($file_dest))
{
$count = (int)$numName;
while(file_exists($file_dest))
{
$count = $count + 1;
$file_dest = './filebag/' . $stringName . $count . '.php';
}
}
copy ($file_orig, $file_dest);
?>
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
File creation time
I want to get all the files in a directory along with its date of creation in array.
I saw the scandir function, but it returns even the directory which I don't want. I also figured out that filemtime($filename) function can return the file created date. Just not able to put it together.
in these days of PHP > 5 you should be using the provided classes for this kind of thing. For this particular task you should be using the FilesystemIterator for example:-
$iterator = new FilesystemIterator('D:/dev/');
foreach($iterator as $fileInfo){
if($fileInfo->isFile()){
$cTime = new DateTime();
$cTime->setTimestamp($fileInfo->getCTime());
echo $fileInfo->getFileName() . " file Created " . $cTime->format('Y-m-d h:i:s') . "<br/>\n";
}
if($fileInfo->isDir()){
$cTime = new DateTime();
$cTime->setTimestamp($fileInfo->getMTime());
echo $fileInfo->getFileName() . " dir Modified " . $cTime->format('Y-m-d h:i:s') . "<br/>\n";
}
}
Here $fileInfo is an instance of SplFileInfo which can give you all the information about a file or directory you could ever want.
if ($handle = opendir('/path/to/files')) {
while (false !== ($file = readdir($handle))) {
echo filemtime($file)." ".$file;
}
closedir($handle);
}
Use scandir to get all the files and sub-directory of main directory
then use is_file function of php.
If you want to access specific extensions file please use glob function of php
Here is the example :
How to get only images using scandir in PHP?
I hope this helps.
This script is supposed to write log files using file locks etc to make sure that scripts running at the same time don't have any read/write complications. I got it off someone on php.net. When I tried to run it twice at the same time, I noticed that it completely ignored the lock file. However, when I ran them consecutively, the lock file worked just fine.
That doesn't make any sense whatsoever. The script just checks if a file exists, and acts based on that. Whether another script is running or not, shouldn't influence it at all. I double checked to make sure the lock file was created in both cases; it was.
So I started to do some testing.
First instance started at 11:21:00 outputs:
Started at: 2012-04-12 11:21:00
Checking if weblog/20120412test.txt.1.wlock exists
Got lock: weblog/20120412test.txt.1.wlock
log file not exists, make new
log file was either appended to or create anew
Wrote: 2012-04-12 11:21:00 xx.xx.xx.xxx "testmsg"
1
Second instance started at 11:21:03 outputs:
Started at: 2012-04-12 11:21:00
Checking if weblog/20120412test.txt.1.wlock exists
Got lock: weblog/20120412test.txt.1.wlock
log file not exists, make new
log file was either appended to or create anew
Wrote: 2012-04-12 11:21:00 xx.xx.xx.xxx "testmsg"
1
So there are two things wrong here. The timestamp, and the fact that the script sais the lock file doesn't exist even though it most certainly does.
It's almost as if the second instance of the script simply outputs what the first one did.
<?php
function Weblog_debug($input)
{
echo $input."<br/>";
}
function Weblog($directory, $logfile, $message)
{
// Created 15 september 2010: Mirco Babin
$curtime = time();
$startedat = date('Y-m-d',$curtime) . "\t" . date('H:i:s', $curtime) . "\t";
Weblog_debug("Started at: $startedat");
$logfile = date('Ymd',$curtime) . $logfile;
//Set directory correctly
if (!isset($directory) || $directory === false)
$directory = './';
if (substr($directory,-1) !== '/')
$directory = $directory . '/';
$count = 1;
while(1)
{
//*dir*/*file*.*count*
$logfilename = $directory . $logfile . '.' . $count;
//*dir*/*file*.*count*.lock
$lockfile = $logfilename . '.wlock';
$lockhandle = false;
Weblog_debug("Checking if $lockfile exists");
if (!file_exists($lockfile))
{
$lockhandle = #fopen($lockfile, 'xb'); //lock handle true if lock file opened
Weblog_debug("Got lock: $lockfile");
}
if ($lockhandle !== false) break; //break loop if we got lock
$count++;
if ($count > 100) return false;
}
//log file exists, append
if (file_exists($logfilename))
{
Weblog_debug("log file exists, append");
$created = false;
$loghandle = #fopen($logfilename, 'ab');
}
//log file not exists, make new
else
{
Weblog_debug("log file not exists, make new");
$loghandle = #fopen($logfilename, 'xb');
if ($loghandle !== false) //Did we make it?
{
$created = true;
$str = '#version: 1.0' . "\r\n" .
'#Fields: date time c-ip x-msg' . "\r\n";
fwrite($loghandle,$str);
}
}
//was log file either appended to or create anew?
if ($loghandle !== false)
{
Weblog_debug("log file was either appended to or create anew");
$str = date('Y-m-d',$curtime) . "\t" .
date('H:i:s', $curtime) . "\t" .
(isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '-') . "\t" .
'"' . str_replace('"', '""', $message) . '"' . "\r\n";
fwrite($loghandle,$str);
Weblog_debug("Wrote: $str");
fclose($loghandle);
//Only chmod if new file
if ($created) chmod($logfilename,0644); // Read and write for owner, read for everybody else
$result = true;
}
else
{
Weblog_debug("log file was not appended to or create anew");
$result = false;
}
/**
Sleep & disable unlinking of lock file, both for testing purposes.
*/
//Sleep for 10sec to allow other instance(s) of script to run while this one still in progress.
sleep(10);
//fclose($lockhandle);
//#unlink($lockfile);
return $result;
}
echo Weblog("weblog", "test.txt", "testmsg");
?>
UPDATE:
Here's a simple script that just shows the timestamp. I tried it on a different host so I don't think it's a problem with my server;
<?php
function Weblog_debug($input)
{
echo $input."<br/>";
}
$curtime = time();
$startedat = date('Y-m-d',$curtime) . "\t" . date('H:i:s', $curtime) . "\t";
Weblog_debug("Started at: $startedat");
$timediff = time() - $curtime;
while($timediff < 5)
{
$timediff = time() - $curtime;
}
Weblog_debug("OK");
?>
Again, if I start the second instance of the script while the first is in the while loop, the second script will state it started at the same time as the first.
I can't fricking believe this myself, but it turns out this is just a "feature" in Opera. The script works as intended in Firefox. I kinda wish I tested that before I went all berserk on this but there ya go.
I'm trying to create a bit of code to first check the content of a directory to see if a file exists and if it does, append a number to the filename. Unfortunately I can't get it to work at the moment, the php produces no errors but a new file is not created if one already exists. Here is my code atm:
$Scan_Name_Output = "dirbuster_" . $workload["Scan_Name"] . "_output.txt";
$Check_Output = exec("ls " . $Output_Directory . " | grep -w " . $Scan_Name_Output);
$j = 1;
while (!empty($Check_Output))
{
$Scan_Name_Output = $Scan_Name_Output . $j;
$j++;
If I replace the while loop with an if statement, it works - so it's not the file paths or anything that are causing the problem. I've tried a fair few combinations but can't get it to work.
I have tried using file_exists() but it doesn't work - I think it's because I'm passing it variables that have been put through escapeshellarg(). As a result I think file_exists literally looks for /path/to/dir/'Report1.txt' - obviously 'Report1.txt' doesn't exist, Report1.txt does. This is why I was using exec and ls.
Thanks for any responses
PHP has some nice functions built in to handle files. You should think about using file_exists() for example.
$basename = "dirbuster_" . $workload["Scan_Name"] . "_output.txt";
$Scan_Name_Output = $basename;
$j = 1;
while (file_exists($Scan_Name_Output)){
$Scan_Name_Output = $basename . $j;
$j++;
}
$ourFileHandle = fopen($Scan_Name_Output, 'w') or die("can't open file");
Try this:
$Scan_Name_Output = "dirbuster_" . $workload["Scan_Name"] . "_output.txt";
if (file_exists($Scan_Name_Output))
{
rename($Scan_Name_Output, $Scan_Name_Output . "1");
}
Selenium2, by default, starts firefox with a fresh profile. I like that for a default, but for some good reasons (access to my bookmarks, saved passwords, use my add-ons, etc.) I want to start with my default profile.
There is supposed to be a property controlling this but I think the docs are out of sync with the source, because as far as I can tell webdriver.firefox.bin is the only one that works. E.g. starting selenium with:
java -jar selenium-server-standalone-2.5.0.jar -Dwebdriver.firefox.bin=not-there
works (i.e. it complains). But this has no effect:
java -jar selenium-server-standalone-2.5.0.jar -Dwebdriver.firefox.profile=default
("default" is the name in profiles.ini, but I've also tried with "Profile0" which is the name of the section in profiles.ini).
I'm using PHPWebdriver (which uses JsonWireProtocol) to access:
$webdriver = new WebDriver("localhost", "4444");
$webdriver->connect("firefox");
I tried doing it from the PHP side:
$webdriver->connect("firefox","",array('profile'=>'default') );
or:
$webdriver->connect("firefox","",array('profile'=>'Profile0') );
with no success (firefox starts, but not using my profile).
I also tried the hacker's approach of creating a batch file:
#!/bin/bash
/usr/bin/firefox -P default
And then starting Selenium with:
java -jar selenium-server-standalone-2.5.0.jar -Dwebdriver.firefox.bin="/usr/local/src/selenium/myfirefox"
Firefox starts, but not using by default profile and, worse, everything hangs: selenium does not seem able to communicate with firefox when started this way.
P.S. I saw Selenium - Custom Firefox profile I tried this:
java -jar selenium-server-standalone-2.5.0.jar -firefoxProfileTemplate "not-there"
And it refuses to run! Excited, thinking I might be on to something, I tried:
java -jar selenium-server-standalone-2.5.0.jar -firefoxProfileTemplate /path/to/0abczyxw.default/
This does nothing. I.e. it still starts with a new profile :-(
Simon Stewart answered this on the mailing list for me.
To summarize his reply: you take your firefox profile, zip it up (zip, not tgz), base64-encode it, then send the whole thing as a /session json request (put the base64 string in the firefox_profile key of the Capabilities object).
An example way to do this on Linux:
cd /your/profile
zip -r profile *
base64 profile.zip > profile.zip.b64
And then if you're using PHPWebDriver when connecting do:
$webdriver->connect("firefox", "", array("firefox_profile" => file_get_contents("/your/profile/profile.zip.b64")))
NOTE: It still won't be my real profile, rather a copy of it. So bookmarks won't be remembered, the cache won't be filled, etc.
Here is the Java equivalent. I am sure there is something similar available in php.
ProfilesIni profile = new ProfilesIni();
FirefoxProfile ffprofile = profile.getProfile("default");
WebDriver driver = new FirefoxDriver(ffprofile);
If you want to additonal extensions you can do something like this as well.
ProfilesIni profile = new ProfilesIni();
FirefoxProfile ffprofile = profile.getProfile("default");
ffprofile.addExtension(new File("path/to/my/firebug.xpi"));
WebDriver driver = new FirefoxDriver(ffprofile);
java -jar selenium-server-standalone-2.21.0.jar -Dwebdriver.firefox.profile=default
should work. the bug is fixed.
Just update your selenium-server.
I was curious about this as well and what I got to work was very simple.
I use the command /Applications/Firefox.app/Contents/MacOS/firefox-bin -P to bring up Profile Manager. After I found which profile I needed to use I used the following code to activate the profile browser = Selenium::WebDriver.for :firefox, :profile => "batman".
This pulled all of my bookmarks and plug-ins that were associated with that profile.
Hope this helps.
From my understanding, it is not possible to use the -Dwebdriver.firefox.profile=<name> command line parameter since it will not be taken into account in your use case because of the current code design. Since I faced the same issue and did not want to upload a profile directory every time a new session is created, I've implemented this patch that introduces a new firefox_profile_name parameter that can be used in the JSON capabilities to target a specific Firefox profile on the remote server. Hope this helps.
I did It in Zend like this:
public function indexAction(){
$appdata = 'C:\Users\randomname\AppData\Roaming\Mozilla\Firefox' . "\\";
$temp = 'C:\Temp\\';
$hash = md5(rand(0, 999999999999999999));
if(!isset($this->params['p'])){
shell_exec("\"C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe\" -CreateProfile " . $hash);
}else{
$hash = $this->params['p'];
}
$ini = new Zend_Config_Ini('C:\Users\randomname\AppData\Roaming\Mozilla\Firefox\profiles.ini');
$path = false;
foreach ($ini as $key => $value){
if(isset($value->Name) && $value->Name == $hash){
$path = $value->Path;
break;
}
}
if($path === false){
die('<pre>No profile found with name: ' . $hash);
}
echo "<pre>Profile : $hash \nProfile Path : " . $appdata . "$path \n";
echo "Files: \n";
$filesAndDirs = $this->getAllFiles($appdata . $path);
$files = $filesAndDirs[0];
foreach ($files as $file){
echo " $file\n";
}
echo "Dirs : \n";
$dirs = array_reverse($filesAndDirs[1]);
foreach ($dirs as $dir){
echo " $dir\n";
}
echo 'Zipping : ';
$zip = new ZipArchive();
$zipPath = md5($path) . ".temp.zip";
$zipRet = $zip->open($temp .$zipPath, ZipArchive::CREATE);
echo ($zipRet === true)?"Succes\n":"Error $zipRet\n";
echo "Zip name : $zipPath\n";
foreach ($dirs as $dir){
$zipRet = $zip->addEmptyDir($dir);
if(!($zipRet === true) ){
echo "Error creating folder: $dir\n";
}
}
foreach ($files as $file){
$zipRet = $zip->addFile($appdata . $path ."\\". $file,$file);
if(!($zipRet === true && file_exists($appdata . $path . "\\". $file) && is_readable($appdata . $path . "\\". $file))){
echo "Error zipping file: $appdata$path/$file\n";
}
}
$zipRet = $zip->addFile($appdata . $path ."\\prefs.js",'user.js');
if(!($zipRet === true && file_exists($appdata . $path . "\\". $file) && is_readable($appdata . $path . "\\". $file))){
echo "Error zipping file: $appdata$path/$file\n";
}
$zipRet = $zip->close();
echo "Closing zip : " . (($zipRet === true)?("Succes\n"):("Error:\n"));
if($zipRet !== true){
var_dump($zipRet);
}
echo "Reading zip in string\n";
$zipString = file_get_contents($temp .$zipPath);
echo "Encoding zip\n";
$zipString = base64_encode($zipString);
echo $zipString . "\n";
require 'webdriver.php';
echo "Connecting Selenium\n";
$webDriver = new WebDriver("localhost",'4444');
if(!$webDriver->connect("firefox","",array('firefox_profile'=>$zipString))
{
die('Selenium is not running');
}
}
private function getAllFiles($path,$WithPath = false){
$return = array();
$dirs = array();
if (is_dir($path)) {
if ($dh = opendir($path)) {
while (($file = readdir($dh)) !== false) {
if(!in_array($file, array('.','..'))){
if(is_dir($path . "\\" . $file)){
$returned = $this->getAllFiles($path . "\\" . $file,(($WithPath==false)?'':$WithPath) . $file . "\\");
$return = array_merge($return,$returned[0]);
$dirs = array_merge($dirs,$returned[1]);
$dirs[] = (($WithPath==false)?'':$WithPath) . $file;
}else{
$return[] = (($WithPath==false)?'':$WithPath) . $file;
}
}
}
closedir($dh);
}
}
return array($return,$dirs);
}
The Idea is that you give in the get/post/zend parameters P with the name of the profile if not a random wil be created, and he will zip all the files put it in the temp folder and put it in.