First, sorry for my english.
I am developing a web application that works on wordpress. I have a folder called GSC, and inside it is my application.
The problem I have, is when I have to control access to users to that directory since all that part will be private, only for registered users.
I have tried with some plugin as wishlist member and only protects the main folder and has no control in subfolders so the application fails since it can not load all the necessary.
So I've searched everywhere and I can not find any more plugin, or I do not know if I should be by programming in each php file controlling if there is a user session, or if wordpress has something else to control access to folders, even look if it you can configure htaccess so that it depends on wordpress users but I do not know if you can.
If someone can give me some idea.
Thank you
Update:
My htaccess
RewriteEngine on
RewriteCond %{REQUEST_URI} ^.*gsc/formulario-clientes/.*
RewriteRule ^(.*)$ /wp-private.php?file=$1 [QSA,L]
Wp-private.php
<?php
/*
* dl-file.php
*
* Protect uploaded files with login.
*
* #link http://wordpress.stackexchange.com/questions/37144/protect-wordpress-uploads-if-user-is-not-logged-in
*
* #author hakre <http://hakre.wordpress.com/>
* #license GPL-3.0+
* #registry SPDX
*/
require_once('wp-load.php');
require_once ABSPATH . WPINC . '/formatting.php';
require_once ABSPATH . WPINC . '/capabilities.php';
require_once ABSPATH . WPINC . '/user.php';
require_once ABSPATH . WPINC . '/meta.php';
require_once ABSPATH . WPINC . '/post.php';
require_once ABSPATH . WPINC . '/pluggable.php';
require_once ABSPATH . 'wp-admin/includes/file.php';
$path = get_home_path()."gsc" ;
is_user_logged_in() || auth_redirect();
//list($basedir) = array_values(array_intersect_key(wp_upload_dir(), array('basedir' => 1)))+array(NULL);
$basedir = $path;
$file = rtrim($basedir,'/').'/'.str_replace('..', '', isset($_GET[ 'file' ])?'formulario-clientes/'.$_GET[ 'file' ]:'');
if (!$basedir || !is_file($file)) {
status_header(404);
// wp_redirect(home_url());
die('404 — File not found.'.$file);
exit();
}
$mime = wp_check_filetype($file);
if( false === $mime[ 'type' ] && function_exists( 'mime_content_type' ) )
$mime[ 'type' ] = mime_content_type( $file );
if( $mime[ 'type' ] )
$mimetype = $mime[ 'type' ];
else
$mimetype = 'image/' . substr( $file, strrpos( $file, '.' ) + 1 );
header( 'Content-Type: ' . $mimetype ); // always send this
if ( false === strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS' ) )
header( 'Content-Length: ' . filesize( $file ) );
$last_modified = gmdate( 'D, d M Y H:i:s', filemtime( $file ) );
$etag = '"' . md5( $last_modified ) . '"';
header( "Last-Modified: $last_modified GMT" );
header( 'ETag: ' . $etag );
header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', time() + 100000000 ) . ' GMT' );
// Support for Conditional GET
$client_etag = isset( $_SERVER['HTTP_IF_NONE_MATCH'] ) ? stripslashes( $_SERVER['HTTP_IF_NONE_MATCH'] ) : false;
if( ! isset( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) )
$_SERVER['HTTP_IF_MODIFIED_SINCE'] = false;
$client_last_modified = trim( $_SERVER['HTTP_IF_MODIFIED_SINCE'] );
// If string is empty, return 0. If not, attempt to parse into a timestamp
$client_modified_timestamp = $client_last_modified ? strtotime( $client_last_modified ) : 0;
// Make a timestamp for our most recent modification...
$modified_timestamp = strtotime($last_modified);
if ( ( $client_last_modified && $client_etag )
? ( ( $client_modified_timestamp >= $modified_timestamp) && ( $client_etag == $etag ) )
: ( ( $client_modified_timestamp >= $modified_timestamp) || ( $client_etag == $etag ) )
) {
status_header( 304 );
exit;
}
// If we made it this far, just serve the file
readfile( $file );
It works and it allows me to access by wordpress user, except that a that I have in the code appears as and I do not know why.
any idea?
Possible dublicate of How to Protect Uploads, if User is not Logged In?
TL;DR:
So what you can do is make a redirect to a php file, and check if a user is logged in or not.
So if you want to protect the upload folder, put this in .htaccess:
RewriteCond %{REQUEST_FILENAME} -s
RewriteRule ^wp-content/uploads/(.*)$ check-auth.php?file=$1 [QSA,L]
Example of file to use, to check for auth is found here.
Related
If I register a script or style (using wp_register_script() or wp_register_style()), is there a way I can get the URL of that script/style?
(If you must know why, I'm trying to put those URL's into another function that generates prefetch link tags so I can prefetch certain scripts/styles for a performance boost in my site.)
Just in case someone is still looking for this:
<?php
function invdr_get_script_uri_by_handler( $handler ){
//Get an instance of WP_Scripts or create new;
$wp_scripts = wp_scripts();
//Get the script by registered handler name
$script = $wp_scripts->registered[ $handler ];
if ( file_exists( ABSPATH . $script->src ) ){
return ABSPATH . $script->src;
}
return false;
}
add_action( 'wp_enqueue_scripts', 'invdr_get_script_uri_by_handler', PHP_INT_MAX );
Tested in wordpress 5.0
You can use wp_scripts() to get the instance of the WP_Scripts class which contains the registered scripts (this class extends WP_Dependencies).
Basically, try looking in:
$wp_scripts = wp_scripts();
var_dump( $wp_scripts->registered );
var_dump( $wp_scripts );
Here's how I've accomplished this in a self-authored plugin to help me enhance dependencies within WordPress:
// Convert relative URL to absolute?
$absolute = true;
$handle = 'your_stylesheet_handle';
$helper = wp_styles();
$object = $helper->registered[ $handle ];
$src = $object->src;
if (
$absolute
&& $helper->in_default_dir( $src )
) {
$src = $helper->base_url . $src;
}
$ver = $object->ver;
if ( ! is_null( $ver ) && empty( $ver ) ) {
$ver = $helper->default_version;
}
if ( isset( $helper->args[ $handle ] ) ) {
$ver = $ver ? $ver . '&' : '';
$ver .= $helper->args[ $handle ];
}
$src = add_query_arg( 'ver', $ver, $src );
$stylesheet_url = urldecode_deep( $src );
Note that the absolute URL conversion is directed towards handling assets registered by WordPress core, as they're typically relative URLs.
Hi I am really bad and a total newbie to PHP. Need some help.
I am trying to define a few constants in my site:
Code 1
define('SITE_ROOT',$_SERVER['DOCUMENT_ROOT'] . '/');
// Check if CORE_PATH is already defined else define here
defined('CORE_PATH') or define('CORE_ROOT', SITE_ROOT . '/CORE');
define('INC_PATH', IAO_ROOT . '/inc/');
define('LAYOUTS_PATH', IAO_ROOT . 'layouts/');
define('BLOCKS_PATH', SECTIONS_PATH . 'blocks/');
define('STATIC_PATH', BLOCKS_PATH . 'static/');
Apart from the above example I have another 10-15 more constants to define. I want to know is it correct to define each constant in one line each or can I do something like below:
Code 2
define (
$constant = array (
'SITE_ROOT',
'CORE_PATH',
'INC_PATH' ,
'LAYOUTS_PATH',
'BLOCKS_PATH',
'STATIC_PATH'
),
$path = array(
$_SERVER['DOCUMENT_ROOT'] . '/',
SITE_ROOT . '/CORE',
CORE_PATH . '/inc',
CORE_PATH . '/layout',
CORE_PATH . '/blocks',
CORE_PATH . '/static'
)
);
define ( $constant, $path);
While Code 1 is working fine on my site, Code 2 is not working for me.
Kindly advise me what is the correct way.
UPDATE:
Updated this question as per #LasVegasCoder. does not work.
<?php
//Create array of paths --example from your path ***use right paths***;
$path = array(
'SITE_ROOT . ' => $_SERVER['DOCUMENT_ROOT'],
'CORE_PATH' => SITE_ROOT . '/core',
'INCLUDE_PATH' => SITE_ROOT . '/inc',
'LAYOUT_PATH' => SITE_ROOT . '/layout',
'BLOCK_PATH' => SITE_ROOT . '/blocks',
'STATIC_PATH' => SITE_ROOT . '/static'
);
//usage:
createPath( $path );
//Testiing
echo SITE_ROOT; ?></br>
<?php echo CORE_PATH; ?></br>
<?php echo INCLUDE_PATH; ?></br>
<?php echo LAYOUT_PATH; ?></br>
<?php echo BLOCK_PATH; ?></br>
<?php echo STATIC_PATH; ?></br>
<?php
function createPath( $path )
{
if( empty( $path ) )
{
die("Array of path required!");
}
foreach( $path as $constant => $path )
{
if(!defined( strtoupper($constant) ) )
{
define( strtoupper($constant), $path . '/');
}
}
}
Well still it does not work. Any idea and solutions?
Create Paths Dynamically
With this tiny function, you can create your paths as array of key => value, pass it to the function to create the paths for your application.
Create array of paths
using example in this question -- use right paths
$path = array(
'SITE_ROOT' => $_SERVER['DOCUMENT_ROOT'],
'CORE_PATH' => '/core',
'INCLUDE_PATH' => '/inc',
'LAYOUT_PATH' => '/layout',
'BLOCK_PATH' => '/blocks',
'STATIC_PATH' => '/static'
);
usage create paths using the function:
createPath( $path );
Testing path
echo CORE_PATH;
OUTPUT
/core/
Create a function to handle paths.
function createPath( $path )
{
if( empty( $path ) )
{
die("Array of path required!");
}
foreach( $path as $constant => $path )
{
if(!defined( strtoupper($constant) ) )
{
// define( strtoupper($constant), $path . '/');
define( strtoupper($constant), realpath( dirname( __FILE__) ) . $path . '/');
}
}
}
youpage.php
<?php
/**Create array of paths array of $constant to $path;
* i.e $path = array( 'THIS_CONSTANT' => '/this/path', 'WEB_ROOT' => '/path/to/webroot' );
* usage:
* `createPath( $path );`
* Test: `echo WEB_ROOT;` OUTPUT: '/path/to/webroot/'
*
* - How to Include another scripts:
* require_once CORE_PATH . 'Config.php';
* require_once INCLUDE_PATH . 'Database.php';
* require_once LAYOUT_PATH 'Header.php';
* require_once LAYOUT_PATH 'Body.php';
* require_once LAYOUT_PATH 'Footer.php';
*/
$path = array(
'SITE_ROOT' => $_SERVER['DOCUMENT_ROOT'],
'CORE_PATH' => '/core',
'INCLUDE_PATH' => '/inc',
'LAYOUT_PATH' => '/layout',
'BLOCK_PATH' => '/blocks',
'STATIC_PATH' => '/static'
);
//usage:
createPath( $path );
// Test. You can echo path, include | require e.g:
echo STATIC_PATH;
function createPath( $path )
{
if( empty( $path ) )
{
die("Array of path required!");
}
foreach( $path as $constant => $path )
{
if(!defined( strtoupper($constant) ) )
{
// define( strtoupper($constant), $path . '/');
define( strtoupper($constant), realpath( dirname( __FILE__) ) . $path . '/');
}
}
}
Test a DEMO Version online
Hope this helps!
I have this plugin im making and in the file upload system i have this:
$mimes = array('image/jpeg','image/jpg','image/gif','image/png','application/pdf');
if(in_array($_FILES['attach']['type'], $mimes)){
$error = 0;
}
else {
$error = 1;
}
Then, along with other error checking i have this to upload the files to a custom folder
if($error == 0) {
$folder = PLUGIN_DIR . '/uploads/';
if(is_dir($folder)) {
$file = $_FILES["attach"]["tmp_name"];
move_uploaded_file($file, $folder.date('Ymd').'_'.$name);
}
}
This works perfectly. I've tested it but, is it ok to do like this? Or is there a better way to do it?
Thanks in advance!
I think better use this codex.wordpress.org
<?php
// We will check the protection of nonce and that the user can edit this post.
if (
isset( $_POST['my_image_upload_nonce'], $_POST['post_id'] )
&& wp_verify_nonce( $_POST['my_image_upload_nonce'], 'my_image_upload' )
&& current_user_can( 'edit_post', $_POST['post_id'] )
) {
// all OK! We continue.
// These files must be connected to the front end (front end).
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
// Let WordPress catch the download.
// Do not forget to specify the attribute name field input - 'my_image_upload'
$attachment_id = media_handle_upload( 'my_image_upload', $_POST['post_id'] );
if ( is_wp_error( $attachment_id ) ) {
echo "Error loading media file.";
} else {
echo "The media file has been successfully uploaded!";
}
} else {
echo "Verification failed. Unable to load file.";
}
?>
check whether free space availability. I had the same issue I have checked every thing and done more but the issue was with my file storage
I am trying to list the contents of a directory by passing a folder name as a URL parameter to invoke a php function. I followed some other examples provided on stackoverflow and have been able to get the php function invoked and am certain I am reaching the code inside because of the echo statements that are output.
The url seems to be encoded correctly because when I display the path info inside the php function all the paths check out.
www.mysite.com/php/genListing.php?function=genListing&folder=wp-content/uploads/myfiles
The check on is_readable() appears to be failing. I have checked the file permissions for that directory and all users have read access. Anybody have any idea of what the problem might be?
genListing.php
if ( ! empty( $_GET['function'] ) && function_exists( $_GET['function'] ) ) {
if ( $_GET['function'] == 'genListing')
{
$atts = $_POST;
genListing( $atts );
}
}
function genListing( $atts ) {
$folder = $_GET[ 'folder' ];
if ( ! empty( $_GET['title'] ) ) {
$title = $_GET['title'];
}
else
{
$title = 'Directory Listing';
}
echo "<p>Made it inside genListing(): " . $folder . "</p>";
$fullFolderPath = trailingslashit( WP_INSTANCE_HOME ) . $folder;
echo "<p> Trying: " . $fullFolderPath . "</p>";
// bad folder check
if ( empty( $folder ) || ! is_readable( $fullFolderPath ) ) {
echo "<p>The folder selected was not valid.</p>";
return 'The folder selected was not valid.';
}
I have the following php code:
index.php
<?php
spl_autoload_extensions(".php");
spl_autoload_register();
use modules\standard as std;
$handler = new std\handler();
$handler->delegate();
?>
modules\standard\handler.php
<?php
namespace modules\standard {
class handler {
function delegate(){
echo 'Hello from delegation!';
}
}
}
?>
Under Windows 7, running WAMP, the code produces the message "Hello from Delegation!" however under Linux, I get the following:
Fatal error: spl_autoload(): Class modules\standard\handler could not be loaded in /var/www/index.php on line 15
Windows is running PHP 5.3.0 under WAMP, and Linux is running the 5.3.2 dotdeb package under Ubuntu 9.10.
Is this a configuration issue on my linux box, or just a difference in the way namespaces and autoloading is handled on the different operating systems
The SPL autoloader is extremely primitive - it has no knowledge of namespaces, so it tries to load a file with \ in it's name while on Linux/Unix the path separator is / not .
Herman Radtke says he has submitted a patch :
http://www.hermanradtke.com/blog/hidden-features-with-spl_autoload-and-namespaces/
:s
I'm hoping it'll be implemented soon.
For now I use this workaround :
<?php
set_include_path( './classes/' . PATH_SEPARATOR . get_include_path() );
spl_autoload_extensions( '.php , .class.php' );
spl_autoload_register();
function linux_namespaces_autoload ( $class_name )
{
/* use if you need to lowercase first char *
$class_name = implode( DIRECTORY_SEPARATOR , array_map( 'lcfirst' , explode( '\\' , $class_name ) ) );/* else just use the following : */
$class_name = implode( DIRECTORY_SEPARATOR , explode( '\\' , $class_name ) );
static $extensions = array();
if ( empty($extensions ) )
{
$extensions = array_map( 'trim' , explode( ',' , spl_autoload_extensions() ) );
}
static $include_paths = array();
if ( empty( $include_paths ) )
{
$include_paths = explode( PATH_SEPARATOR , get_include_path() );
}
foreach ( $include_paths as $path )
{
$path .= ( DIRECTORY_SEPARATOR !== $path[ strlen( $path ) - 1 ] ) ? DIRECTORY_SEPARATOR : '';
foreach ( $extensions as $extension )
{
$file = $path . $class_name . $extension;
if ( file_exists( $file ) && is_readable( $file ) )
{
require $file;
return;
}
}
}
throw new Exception( _( 'class ' . $class_name . ' could not be found.' ) );
}
spl_autoload_register( 'linux_namespaces_autoload' , TRUE , FALSE );
?>
function __autoload($class_name) {
$paths[] = dirname(__FILE__) . "/../libs/misc/";
$paths[] = dirname(__FILE__) . "/../../libs/misc/";
$paths[] = dirname(__FILE__) . "/../../libs/helpers/";
$paths[] = dirname(__FILE__) . "/../../libs/simpleimage/";
foreach($paths as $path)
{
if(file_exists($path.strtolower($class_name).'.class.php')){
require_once($path.strtolower($class_name).'.class.php');
}
}
}
function __autoload($class_name)
{
$class_name = strtolower(str_replace('\\', DIRECTORY_SEPARATOR, $class_name));
include $class_name . '.php';
}
The srttolower is needed on Apache because it is (contrary to IIS) case sentive.
This is a common problem occurs when autoloading. The fix is to use DIRECTORY_SEPARATOR constant in the autoload function.
So your autoload function will look like following
<?php
spl_autoload_register(function($className) {
$className = str_replace("\", DIRECTORY_SEPARATOR, $className);
include_once $_SERVER['DOCUMENT_ROOT'] . '/class/' . $className . '.php';
});
If you need to learn more on namespace/class autoloading visit here
Thanks.