php script that gives md5 of a online file - php

hi i'm looking for a script that gives me the md5 of a file by link
i have all ready a script that gives the md5 of the files that are in the folder but now i wanna add a script where you paste the link to the file and it prints out the md5
if some one knows how to make this plz let me know
code that i have :
<?php
$cwd = $_SERVER['REQUEST_URI'];
$cwd = substr($cwd, 0, strrpos($cwd, '/' + 1));
function paintUndersideOfFox($c) {
global $cwd;
echo('<ul class="dirlist">');
$d = opendir($c);
while($f = readdir($d)) {
if(strpos($f, '.') === 0) continue;
$ff = $c . '/' . $f;
echo 'MD5 file hash of ' . $ff . ': ' . md5_file($ff);
echo('<li>' . $ff . '</li><br />');
if(is_dir($ff)) paintUndersideOfFox($ff);
}
echo('</ul>');
}
paintUndersideOfFox('.');
?>

Most filesystem functions apply to streams, including HTTP. Did you try this
md5_file("http://remotelocation/file")

Downloading files can be done via file_get_contents() or more securely with CURL

Related

PHP in Windows: add an environment variable for User or Machine

I am trying to update the Path environment variable in Windows with a PHP script, but if I use putenv() it doesn't change. I can get the paths list in the Path variable but I am not able to update it.
Another problem is that if I use getenv('Path') to get the paths list, I have a unique string with all paths merged from the Path variable of User and of the Machine.
I'm wondering if there is a better way to do that, maybe acting directly in the registry key to update User Path variable.
UPDATE
I think I found out a half-solution, but it doesn't work as expected.
What do I want to do?
I just want to make a script that allow me to switch from a PHP version to another changing the Path variable.
I made the script, it seems to work and the Path variable is successfully updated, but even if I close and reopen the cmd prompt if I type php -v it doesn't seems to get the updated var. If I open the Environment Variables windows, then open the "Path" variable and click on Ok and Ok again, then the refresh is got but the cmd prompt.
This is very strange to me, and if I have to do this everytime, then script loose its benefit...
I recorded a video, I hope it explain the problem better than my English...
https://1drv.ms/v/s!Ao2s4w8xSxBSh7RY4y5pB8u1g_QFSQ
This is the code of the script:
// Load PHP available versions
$laragon_php_paths = 'D:\www-servers\laragon\bin\php';
$php_paths = scandir($laragon_php_paths);
$path_var_name = "Path";
// Backup before doing a disaster
$date = new DateTime();
exec('REG EXPORT HKCU\Environment BackupUserEnvironment_' . $date->format('YmdHisv') . '.reg');
// Load registry key of user's Path environment variable
exec('REG QUERY HKCU\Environment /v ' . $path_var_name, $output, $result);
$path = explode(' ', $output[2]);
$path_array = explode(';', $path[count($path) - 1]);
// Get the current PHP Version and get the key of the item of the PHP bin path
foreach ($path_array as $key => $path_item) {
if (strpos($path_item, $laragon_php_paths) !== false) {
$the_key = $key;
$current_php_version = substr($path_item, strrpos($path_item, '\\') + 1);
}
}
echo 'Available PHP versions:' . PHP_EOL . PHP_EOL;
$i = 0;
foreach ($php_paths as $dir) {
if ($dir === '.' || $dir === '..') continue;
echo ' [' . ++$i . '] ' . $dir;
if ($dir === $current_php_version) {
echo ' [Current version]';
}
echo PHP_EOL;
}
// Get file descriptor for stdin
echo PHP_EOL;
echo 'Select a PHP version: ';
$fd = fopen('php://stdin', 'r');
$choice = (int) fgets($fd);
echo PHP_EOL;
// Check if choice is between 1 and number of choices
if ($choice > 0 && $choice <= $i) {
// Change the original php version with the new one
$new_php_version = $php_paths[$choice + 1];
$path_array[$the_key] = $laragon_php_paths . '\\' . $new_php_version;
echo 'PHP version changed to: ' . $new_php_version . PHP_EOL;
} else {
echo 'No allowed choice, nothing changed.';
echo PHP_EOL;
}
// Escape some chars for cmd
$new_path_var = str_replace(['%', ' '], ['^%', '" "'], implode(';', $path_array));
$cmd = 'REG ADD HKCU\Environment /f /t REG_EXPAND_SZ /v ' . $path_var_name . ' /d ' . $new_path_var;
// Execute
exec($cmd);

looping in file_get_content php and output the content of each file with filename

I m using this code to output content of files in a directory but I have two problems
first is that this directory contains sub-dir and this code doesn't output
files content in these sub-dir
Second problem
I want this code to output like
Filename:"name of the file"
Content :"content of the file"
so that I can parse this
$dir = new DirectoryIterator('./Chemistry');
foreach($dir as $file)
{
if(!$file->isDot() && $file->isFile() && strpos($file->getFilename(), '.md') !== false)
{
$content = file_get_contents($file->getPathname());
echo $content
}
}
?>
If I understand correct you want to output:
echo 'Filename: ' . $file->getFilename() . ' Content: ' . $content;
If this is not your intention I will require a more thorough explanation.
* edit *
For dir iteration use http://php.net/manual/en/function.scandir.php
From the top of my head it goes a little something like this (hit it)...
function loopDir($path) {
$allFilesAndFoldersInCurrentFolder = scandir($path);
foreach($allFilesAndFoldersInCurrentFolder as item) {
if(is_dir($item)) {
loopDir($path.'/'.$item);
}
else {
echo 'Filename: ' . $file->getFilename() . ' Content: ' . $content;
}
}
}

Creating SYMLINK with PHP on Hostgator jailed shell - Get Perm Denied error

so I come to you with this problem:
GIVENS:
I have Hostgator as the ISP.
I'm using PHP 5.5
The LINUX box is CENTOS
Shared Hosting Environment
I am a professional coder and experienced with LAMP for many years
PROBLEMS:
I'm NOT familiar with Jailed Shell but have an idea
I've tried the script and have been searching for an answer
Still Stuck...
Here's my current code:
function getMyFakeDir($myfile) {
$target = "";
$link = 'content/purchased-items/link';
symlink($target, $link);
echo "READ LINK: ". readlink($link);
return readlink($link);
}
Here's the called to the function:
$linkText = getMyFakeDir('SomePDFThatTheUserCanDownload.pdf');
Then I pass that "$linkText" var to PHPMailer and wala!!! The user clicks to download through the Symlink and I've written a code to make it expire after 24 hours. Yeah, I got that from PHP.net.
So, basically that's my problem....
Here's the error:
Warning: symlink(): Permission denied in /homeSomewhere/someMasterDir/public_html/webServices/somePHPFile.php on line 654
This is link 654 from above:
symlink($target, $link);
Thanks...
Figured it out.... Simple LOGIC!
First I had the PATHS all wrong. Here's the CORRECTED CODE:
//Generate Symbolic Link that blows away a fake directory each time
//A symbolic Link is created to "THIS" file below
$filename = $myfile;
//This is ANY directory on the server...
//A randomly named directory is created here...STEP 1
$downloaddir = "/home/someHostDir/public_html/sldktrulwiu2555ivd0fjvdfgdfgdfgdf/";
//Any directory NOT accessible by a browser - This is one level up
$safedir = "/home/someHostDir/content/purchased-items/";
//This is the equivalent of the $downloaddir and the browser is REDIRECTED here and the download begins
$downloadURL = "http://www.theSomeDomain.com/sldktrulwiu2555ivd0fjvdfgdfgdfgdf/"; //THIS IS THE FAKE DIRECTORY (Which I simply type gobbligook and created that mess above)
$letters = 'abcdefghijklmnopqrstuvwxyz';
srand((double) microtime() * 1000000);
$string = '';
for ($i = 1; $i <= rand(4, 12); $i++) {
$q = rand(1, 24);
$string = $string . $letters[$q];
}
$handle = opendir($downloaddir);
while ($dir = readdir($handle)) {
if (is_dir($downloaddir . $dir)) {
if ($dir != "." && $dir != "..") {
#unlink($downloaddir . $dir . "/" . $filename);
#rmdir($downloaddir . $dir);
}
}
}
closedir($handle);
mkdir($downloaddir . $string, 0777);
symlink($safedir . $filename, $downloaddir . $string . "/" . $filename);
//Header("Location: " . $downloadURL . $string . "/" . $filename);
That just about does it.
The result is a Dynamic directory inside the "/sldktrulwiu2555ivd0fjvdfgdfgdfgdf/" directory like this: "dfsgss/" and a "shortcut" to the REAL LOCATION where the files are. THEN when the file is downloaded, and the page returns to the INDEX.HTML, the code BLOWS OUT the FAKE directory Never more to be seen again. Thus, if the user wants to go back, they get the horrible 404 PAGE error that the file / has been moved or deleted. BUMMER.
That's it folks. Thanks for your assistance, it was you all the helped me release my error. TEAM WORK!

Selenium2 firefox: use the default profile

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.

PHP Delete File script

I have a basic PHP script that displays the file contents of a directory. Here is the script:
<?php
$Dept = "deptTemplate";
if(isset($_REQUEST['dir'])) {
$current_dir = $_REQUEST['dir'];
} else {
$current_dir = 'docs';
}
if ($handle = opendir($current_dir)) {
while (false !== ($file_or_dir = readdir($handle))) {
if(in_array($file_or_dir, array('.', '..'))) continue;
$path = $current_dir.'/'.$file_or_dir;
if(is_file($path)) {
echo '`'.$file_or_dir.' - [Delete button/link]<br/>`';
} else {
echo '``'.$file_or_dir."\n`` - [Delete button/link]`<br/>`";
}
}
closedir($handle);
}
?>
I am trying to create a delete link/button that displays next to each file and when clicked, the corresponding file will be deleted. Would you know how to do this?
Use the built-in unlink($filepath) function.
Sure, you'd have to use unlink() and rmdir(), and you'd need a recursive directory removal function because rmdir() doesn't work on directories with files in them. You'd also want to make sure that the deletion script is really secure to stop people from just deleting everything.
Something like this for the recursive function:
function Remove_Dir($dir)
{
$error = array();
if(is_dir($dir))
{
$files = scandir($dir); //scandir() returns an array of all files/directories in the directory
foreach($files as $file)
{
$fullpath = $dir . "/" . $file;
if($file == '..' || $file == '.')
{
continue; //Skip if ".." or "."
}
elseif(is_dir($fullpath))
{
Remove_Dir($fullpath); //recursively remove nested directories if directory
}
elseif(is_file($fullpath))
{
unlink($fullpath); //Delete file otherwise
}
else
{
$error[] = 'Error on ' . $fullpath . '. Not Directory or File.' //Should be impossible error, because everything in a directory should be a file or directory, or . or .., and thus should be covered.
}
}
$files = scandir($dir); //Check directory again
if(count($files) > 2) //if $files contains more than . and ..
{
Remove_Dir($dir);
}
else
{
rmdir($dir); //Remove directory once all files/directories are removed from within it.
}
if(count($error) != 0)
{return $error;}
else
{return true;}
}
}
Then you just need to pass the file or directory to be deleted through GET or something to the script, probably require urlencode() or something for that, make sure that it's an authorized user with permissions to delete trying to delete the stuff, and unlink() if it's a file, and Remove_Dir() if it's a directory.
You should have to prepend the full path to the directory or file to the directory/file in the script before removing the directory/file.
Some things you'll want for security is firstly making sure that the deletion is taking place in the place it's supposed to, so someone can't do ?dir=/ or something and attempt to delete the entire filesystem from root, which can probably be circumvented by prepending the appropriate path onto the input with something like $dir = '/home/user/public_html/directories/' . $_GET['dir'];, of course then they can potentially delete everything in that path, which means that you need to make sure that the user is authorized to do so.
Need to keep periodic backups of files just in case.
Something like this? Not tested...
<?php
echo '`'.$file_or_dir.' - [Delete button/link]<br/>`';
?>
<?php
if ($_GET['del'] == 1 && isset($_GET['file_or_dir']){
unlink ("path/".$_GET['file_or_dir']);
}
?>
I've worked it out:
I added this delete link on the end of each listed file in the original script:
- < a href="delete.php?file='.$file_or_dir.'&dir=' . $dir . '"> Delete< /a>< br/>';
This link takes me to the download script page, which looked like this:
<?php
ob_start();
$file = $_GET["file"];
$getDir = $_GET["dir"];
$dir = 'docs/' . $getDir . '';
$isFile = ($dir == "") ? 'docs/' . $file . '' : '' . $dir . '/' . $file . '';
if (is_file($isFile)){
if ($dir == "")
unlink('docs/' . $file . '');
else
unlink('' . $dir . '/' . $file . '');
echo '' . $file . ' deleted';
echo ' from ' . $dir . '';
}
else{
rmdir('' . $dir . '/' . $file . '');
echo '' . $dir . '/' . $file . ' deleted';}
header("Location: indexer.php?p=" . $getDir . "");
ob_flush();
?>
It all works brilliantly now, thank you all for your help and suggestions :)

Categories