i wanna try this
link : How to check using PHP FTP functionality if folder exists on server or not?
tell me if my code is right;
i cant seem to find the folder and it echoes the failed
sample ftp account is
user: admin#mywebsite.com
pass: name#pasword
ftp file root is : /home/mywebsite/public_html/admin
path folder i want to find is: public_html/admin/userfiles
i set the path ftp account path on the admin from cpanel
if(is_dir('ftp://admin#mywebsite.com:name#pasw0rd#mywebsite.com/userfiles'))
{
echo 'found';
}
else
{
echo 'failed';
}
There are some prerequisites to using 'ftp://` this way:
The PHP directive allow_url_fopen must be set to true;
The target server must support passive ftp
Assuming both of those things, your URL must be accurate. The convention is ftp://name:password#server.example.com/folder. Your URL appears to have a spurious :name# in it.
ftp://admin#mywebsite.com:name#pasw0rd#mywebsite.com/userfiles'
^^^^^^
FTP function checks if a directory exists
<?php
function ftp_is_dir( $dir ) {
global $ftpcon;
// get current directory
$original_directory = ftp_pwd( $ftpcon );
// test if you can change directory to $dir
// suppress errors in case $dir is not a file or not a directory
if ( #ftp_chdir( $ftpcon, $dir ) ) {
// If it is a directory, then change the directory back to the original directory
ftp_chdir( $ftpcon, $original_directory );
return true;
}
else {
return false;
}
}
?>
Related
I've created a basic page where people "sign up" to upload/delete files in their own isolated folder.
The uploading/deleting of files are secure, however I would also like to allow admins to "deny" files.
The code alone works, except if anyone changes the URL to somewhere else on the server, they can "deny" any file on the system putting it at risk. I am looking to create a system function of which detects if the file they are targeting exists anywhere in the directory tree.
Here's the code that I am using of which I'd like to create a function that returns either true/false.
<?php
if(isset($_GET['deny'])) {
$tree_start = "Uploads";
$targeted_file = $_GET['deny'];
$safe_to_delete = in_directory_tree($tree_start, $targeted_file); <-- Looking for this
if( $safe_to_delete == false ) {die("This file does not exist in the directory tree");}
rename($_GET['deny'], "./Uploads/#Denied/". basename($_GET['deny']) );
}
?>
My Directory tree:
.htaccess <-- Prevent downloading of the database
admin.php <-- Problematic file browser script
index.php <-- User File management script
Users.db <-- Names and hashed passwords
Uploads:
[FILE] htaccess <-- Prevent script execution (layer 2).
[DIR] #Accepted: Notes.png, Video.mp4, etc...
[DIR] #Denied: Project.png, new_timetable.txt, etc...
[DIR] Admin: Proj1.txt, Proj1.png, etc...
[DIR] User1: Task1.txt, Task2.txt, etc...
[DIR] User2: Video1.txt, date.txt, etc...
give this code a try:
function in_directory_tree($dir,$file_to_search){
$filesList = new RecursiveDirectoryIterator("uploads");
$targetFile = "contact.php" ;
foreach(new RecursiveIteratorIterator($filesList) as $file)
{
$contents = explode("\\",$file);
if (in_array($targetFile, $contents))
return true;
}
return false;
}
This code will load the directory and start searching recursively, if it reaches the end without finding the file it will return false, otherwise it will return true.
I used RecursiveDirectoryIterator as it will help us get inside directories to list them
I have solved this problem by preventing path traversal instead of checking if the file exists in this folder. This code works for me (returns true only when a file in /uploads exists (and blocks going back using C:/, ../, etc), and returns true only when the file does exist. Here is the finished code:
<?php
// Code used for the deny button:
// <button onclick="location.href='?deny=SmilerRyan/Project.png';">Deny</button>
if(isset($_GET['deny'])) {
$userpath = $_GET['deny'];
$basepath = 'Uploads/';
$realBase = realpath($basepath);
$userpath = $basepath . $userpath;
$realUserPath = realpath($userpath);
if ($realUserPath === false || strpos($realUserPath, $realBase) !== 0) {
die("Invalid path - Possible Attack Blocked");
} else {
rename($userpath, "./Uploads/#Denied/" . basename($userpath) );
}
}
?>
I have a AWS EC2 server with phpMyAdmin to manage it.
Everything is working correctly but I would like to be able to create another folder in the /var/www/html directory to add files..
This is my code but it just keeps returning the error to me! any ideas??
// STEP 2.2 Create a folder in server to store posts'pictures
$folder = "/var/www/html/bloggerFiles/Posts/" . $id;
if(!file_exists($folder)){
if (!mkdir($folder, 0777, true)) {//0777
die('Failed to create folders...');
}
}
I would normally create that folder in the terminal by using sudo mkdir, but when I add sudo Nothing works!
Any help is appreciated!
Thanks in advance.
Make sure the folder(s) you are accessing are set to read and write folder permissions, then use this function:
function newFolder($path, $perms)
$path = str_replace(' ', '-', $path);
$oldumask = umask(0);
mkdir($path, $perms); // or even 01777 so you get the sticky bit set (0777)
umask($oldumask);
return true;
}
This fixed it for me.
You can create new folder doing this: newFolder('PathToFolder/here', 0777);
EDIT: Please have a look at: https://www.youtube.com/watch?v=7mx2XOFBp8M
EDIT: Also have a look at http://php.net/manual/en/function.mkdir.php#1207
EDIT: Storing functions in classes and safely use the function
class name_here
{
public function newFolder($path, $perms, $deny_if_folder_exists){
$path = 'PATH_TO_POSTS/'.$path; // This is for setting the root to PATH TO POSTS
$path = str_replace('../', '', $path); // Deny the path to go out of var/www/html/PATH_TO_POSTS/$path
if( $deny_if_folder_exists === true ){
if(file_exists($path)){return false;}
$old_umask = umask(0);
mkdir($path, $perms);
umask($old_umask);
}elseif( $deny_if_folder_exists === false ){
$old_umask = umask(0);
mkdir($path, $perms);
umask($old_umask);
}else{
return false; // Unknown
}
}
}
/* Call the function by doing this: */
$manage = new name_here;
$manage->newFolder('test', 777, true); // Test will appear in /var/www/html/PATH_TO_POSTS/$path, but if the folder exists it will return false and not create the folder.
EDIT: If this file is called from html it will re create the path, so I will it has to be called from /html/
EDIT: How to use the name_here class
/*
How to call the function?
$manage = new name_here; Creates a variable to an object (The class)
$manage->newFolder('FolderName', 0777, true); // Will create a folder to the path,
but this fill needs to be called from the html the root directory is set to the
"PATH_TO_POSTS/" basicly means you cannot do this function from "html/somewhere/form.php",
UNLESS the "PATH_TO_POSTS" is in the same directory as form.php
*/
I have created one process to read information from files and save into database, everything works fine in my desenv environment, but when I have put files in my php host (production environment) the process fail when read files.
to execute my process, I have created one cron job on cpanel, whith the command bellow:
php -q /home/<hostfolder>/batch/index.php
When my process is executed by cron, the output say that don't have files. Bellow part of my code:
private $sourceFilesFolder = "/home/<host folder>/public_html/batch/arquivos";
private $destFilesFolder = "/home/<host folder>/public_html/batch/processados";
private $log;
private $trataException;
function __construct($log, $trataException) {
$this->log = $log;
$this->trataException = $trataException;
}
/**
* Read the source folder and select only files
* #return array - Array of valid files
*/
function selectFiles() {
// Save the first read of ftp folder
$listSourceFolder = scandir ( $this->sourceFilesFolder );
// Array tho save only valid files
$listFiles = array ();
// read the array with ftp content and save in listFiles only files
foreach ( $listSourceFolder as $file ) {
$verifica = $this->sourceFilesFolder . "\\" . $file;
// if is a file type, try save in listFiles array
if (($file != ".") && ($file != "..") && (!is_dir ( $verifica ))) {
// verifiy if the file exists
if (file_exists ( $verifica )) {
$this->log->gravaLog ( $file . " -> ADDED TO PROCESS" );
//verificaArquivoEmUso ( $verifica );
array_push ( $listFiles, $verifica );
} else
$this->log->gravaLog ( $file . "-> do not exist." );
} else
$this->log->gravaLog ( $file . "-> not is a file." );
}
return $listFiles;
}
In my folder I have two txt files and this appear in the $listSourceFolder variable, but when I check this files with file_exists, always return false.
First, I have put my code files in a bacth folder in /home/
In the second test, I move the files in ftp folder and put inside the bacth folder (same of my code).
In the third test, I moved all batch folder (with codes and txt files) to public_html folder.
Nothing work, always the same error, file not exists.
I tryed remove ths file_exists if, but occur erros on the next step of algoritm.
I have checked the file permissions, and all permissions are ok.
What is I can do???
You can try three things.
1 - chmod 777 (Give permission so php can read and write files)
2 - I know its practically impossible that your server has a lower version of php. Scandir only works php 5 above. So you might wanna check that.
3 - There's a module called "mod_speling", try put that on.
;)
It appears that you are using the incorrect path delimiter for *nix.
You might change your code to be the following instead:
$verifica = $this->sourceFilesFolder . "/" . $file;
I am trying to install a Magento package, but I get No file was uploaded
Its coming from this code because $_FILES is an empty array in /downloader/Maged/Controller.php
/**
* Install uploaded package
*/
public function connectInstallPackageUploadAction()
{
if (!$_FILES) {
echo "No file was uploaded";
return;
}
if(empty($_FILES['file'])) {
echo "No file was uploaded";
return;
}
$info =& $_FILES['file'];
if(0 !== intval($info['error'])) {
echo "File upload problem";
return;
}
$target = $this->_mageDir . DS . "var/" . uniqid() . $info['name'];
$res = move_uploaded_file($info['tmp_name'], $target);
if(false === $res) {
echo "Error moving uploaded file";
return;
}
$this->model('connect', true)->installUploadedPackage($target);
#unlink($target);
}
It might be worth noting that product uploads work fine.
The only log output I get is
2014-07-03T18:44:15+00:00 ERR (3): Warning: array_key_exists() expects parameter 2 to be array, null given in /var/www/vhosts/example.com/httpdocs/app/code/core/Mage/Captcha/Model/Observer.php on line 166
exception.log was empty
Make sure that your var folder in magento installation is fully writable. 777 permission. All folders and files.
You can try uploading a small dummy file first to check if the error stays the same.
There is a file upload limit which might be reached.
File upload often fails due to upload_max_filesize or post_max_size being too small as mentioned in Common Pitfalls section of the PHP documentation.
Use firebug in firefox to check if your form does has enctype="multipart/form-data".
Check the user group it was created with,
To explain, recently I had some file saving issues. Turned out I had created the folder using the Root user for the server, and the CPanel user ( the one php was running under ) didn't have permission to write in folders owned by the Root account, even when setting the permissions to 777.
Just a thought.
First check if your installation is configured properly
see#http://php.net/manual/en/features.file-upload.common-pitfalls.php
Also, if you upload with PUT/xhr the file is on the input stream
$in = fopen('php://input','r');
see#http://php.net/manual/en/features.file-upload.put-method.php and https://stackoverflow.com/a/11771857/2645347,
this would explain the empty $FILES array, in case all else is ok and the upload works via xhr/PUT.
$_FILES is an associative array of items uploaded to the current script via the HTTP POST method. All uploaded files are stored in $HTTP_POST_FILES contains the same initial information, but is not a superglobal. So, ... be sure that method is POST
Always check that your form contains correct enctype:
<form ... enctype="multipart/form-data"> ... </form>
Sometimes happens that when someone upload multiples file, $_FILES return empty. This could happen when I select files that exceed some size. The problem can be in the POST_MAX_SIZE configuration.
On
app/code/core/mage/captcha/model/observer.php
change
public function checkUserLoginBackend($observer)
{
$formId = 'backend_login';
$captchaModel = Mage::helper('captcha')->getCaptcha($formId);
$loginParams = Mage::app()->getRequest()->getPost('login');
$login = array_key_exists('username', $loginParams) ? $loginParams['username'] : null;
if ($captchaModel->isRequired($login)) {
if (!$captchaModel->isCorrect($this->_getCaptchaString(Mage::app()->getRequest(), $formId))) {
$captchaModel->logAttempt($login);
Mage::throwException(Mage::helper('captcha')->__('Incorrect CAPTCHA.'));
}
}
$captchaModel->logAttempt($login);
return $this;
}
to
public function checkUserLoginBackend($observer)
{
$formId = 'backend_login';
$captchaModel = Mage::helper('captcha')->getCaptcha($formId);
$login = Mage::app()->getRequest()->getPost('username');
if ($captchaModel->isRequired($login)) {
if (!$captchaModel->isCorrect($this->_getCaptchaString(Mage::app()->getRequest(), $formId))) {
$captchaModel->logAttempt($login);
Mage::throwException(Mage::helper('captcha')->__('Incorrect CAPTCHA.'));
}
}
$captchaModel->logAttempt($login);
return $this;
}
Your issue is:
"Captcha Observer throws an error if login in RSS feed" issue #208
or if you wish you could only replace the variable $login to be like this:
$login = array_key_exists('username', array($loginParams)) ? $loginParams['username'] : null;
You may try out below points.
Use Magento Varien File Uploaded Classes to Upload the files.
Magento File Uploader
1) Check enctype="multipart/form-data" in your form.
2) Use Magento Form Key in your form.
3) Use Varien file uploader to upload your files using below links answers.
in php how do I determine whether or not I can create a file in the same path as the script trying to create a file
Unfortunately, all of the answers so far are wrong or incomplete.
is_writable
Returns TRUE if the filename exists and is writable
This means that:
is_writable(__DIR__.'/file.txt');
Will return false even if the script has write permissions to the directory, this is because file.txt does not yet exist.
Assuming the file does not yet exist, the correct answer is simply:
is_writable(__DIR__);
Here's a real world example, containing logic that works whether or not the file already exists:
function isFileWritable($path)
{
$writable_file = (file_exists($path) && is_writable($path));
$writable_directory = (!file_exists($path) && is_writable(dirname($path)));
if ($writable_file || $writable_directory) {
return true;
}
return false;
}
Have you tries the is_writable() function ?
Documentation
http://www.php.net/manual/en/function.is-writable.php
Example:
$filename = 'test.txt';
if (is_writable($filename)) {
echo 'The file is writable';
} else {
echo 'The file is not writable';
}
The is_writable function is good stuff. However, the OP asked about creating a file in the same directory as the script. Blatantly stealing from vlad b, do this:
$filename = __DIR__ . '/test.txt';
if (is_writable($filename)) {
echo 'The file is writable';
} else {
echo 'The file is not writable';
}
See the php manual for predefined constants for the details on __DIR__. Without it, you're going to create a file in the current working directory, which is probably more or less undefined for your purposes.
Use is_writable PHP function, documentation and example source code of this you can find at http://pl2.php.net/manual/en/function.is-writable.php