This should be so simple but I'm a bit stumped as to the best way to approach this.
I am building a PHP plugin so I can't hard code any paths. I also need to consider http protocols (http / https). I use GD Lib to create and save an image. My directory structure looks like this:
public_html > php_plugin > php_classes > php_class.php
public_html > php_plugin > saved_images
The plugin is installed in public_html. I run code to save the image in php_class.php. Here I save the image like so: '../saved_images/imagename.jpg'. This works fine and the image is saved in the correct directory.
I then return this path via AJAX to display the image. And, obviously this path fails to resolve and I get a broken image link: http://www.website.com/saved_images/imagename.jpg
It should look like: http://www.website.com/php_plugin/saved_images/imagename.jpg
So in my PHP class where I set up the save path how do I build up a path that I can return with AJAX, bearing in mind this is a plugin and could be used on many different sites.
EDIT:
For the record I know I can use $_SERVER['SERVER_NAME'] and $_SERVER['SERVER_PROTOCOL'] but based on these SO questions (PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly? and PHP Get Site URL Protocol - http vs https) I think this approach will be quite unreliable as the server configs where the plugin will be hosted will be an unknown.
You are conflating two different types of path; the server filesystem path and the URL path. In your case they are similar, but depending on the server configuration these might be wildly different.
Since you write that you return a path to the image via AJAX, presumably your AJAX code must know the URL to the PHP script to be able to call it (something like http://example.com/php_plugin/index.php?). In this case you could just have PHP return only the filename and provide the rest of the path in your javascript.
Related
So i was browsing through the web and found a video, upon inspecting the video source i found out that it had a get variable in the url, it looked like this:
http://www.blablabla.com/stream/2017/09/2a5ef169.mp4?expires=1302948611&token=1290239327
this part got my interest:
2a5ef169.mp4?expires=1302948611&token=1290239327
Its a MP4 file but accepts get variables. if those variables do not match a certain function i am not able to view the video so i think its linked to a php file.
I do know how GET and POST works in PHP but how do i apply this to a MP4 file or any other file.
Just because the extension ends in mp4, it doesn't mean "there is an mp4 file somewhere".
consider .htaccess can change extensions and using mod_rewrite or similar, people can redirect a given "clean" url to any php program.
So there may be a php interpreter behind the mp4 requests, and apache may have a modified httpd.conf or .htaccess file which routes /(.*).mp4 requests into a serve_video.php program (or whatever the name is).
This means in general, extensions don't mean anything.
by using HTTP header()s, the server might be responding dynamically (example: https://gist.github.com/ranacseruet/9826293) to each request (potentially in order to log the video's view count or something similar, like checking the HTTP REFERER in order to avoid hotlinking)
Hope that helps!
how can I delete a file using an url path ?
I have
$file_with_path = "http://www.myweb.com/uploads/audio.mp3";
if (file_exists($file_with_path)) {
unlink($file_with_path);
}
I don't use "/uploads/audio.mp3" or similar directory paths due some reasons.
thanks in advance !!
unlink tells the operating system to delete a given file. The OS identifies files by file system path - it does not interact with URLs in any way. URLs are translated to file system paths by the web server, which is an entirely different piece of software. While theoretically there is a way to tell a web server to delete the file (by sending a HTTP DELETE request), no web server is going to honor that - it would be way too insecure. It is relatively easy to control who can access the file system; it is very hard to control who can send requests to the web server.
In short, you will have to figure out what the file system path for the file is, and use unlink (and file_exists) with that path.
In the JavaScript file containing the Ajax request what is the URL relative to? I've got the www directory containing the directories alpha and bravo. The JavaScript file in alpha and the HTML file that includes it and the PHP that processes the request in bravo.
In the JavaScript file I have xmlhttp.open("GET", "CheckServer.php?name="+name,true); but I don't think CheckServer.php is right. I've tried ../bravo/CheckServer.php but it doesn't work.
I'm not using JQuery and I am using WAMP.
Plus, is there any trouble shooting tools I can use to see if the PHP page for processing the request is being accessed in the first place?
EDIT: I opened the console and it says the function I'm calling in the JavaScript file is not defined. This only happens when I moved the .js file to a different directory. (I modified the <script> tag appropiratly: <script type="text/javascript" src="../alpha/Check.js">.
EDIT 2: I think there is a problem with WAMP because I copy the exact same files/folders to the desktop and everything works.
It is relative based on the current location of the page it is called on. It has nothing to do with where the JavaScript is loaded from.
Open up the console and look at the Ajax request [console or net tab], you will see the path that it is requesting.
It's an URL, those have nothing to do with directories per se. They might be mapped to directories on the server and often are but the client can never know it for sure and doesn't care. The URL is relative to the current URL (what you see in your browser address bar).
So, the question is not "where is CheckServer.php located on the server", but "how can I access it from the client".
If it's like:
http://example.com/alpha/index.html
http://example.com/bravo/CheckServer.php
fine. Use the relative URL.
But if it's like:
http://alpha.example.com/index.html
http://bravo.example.com/CheckServer.php
then it gets complicated. You will have to look into CORS (Cross-Origin Resource Sharing) because AJAX usually does not work across different domains.
Oh, and if CheckServer.php is not accessible at all... you probably can imagine the answer.
I am looking for some input on something I have been thinking about for a long time. It is a very general problem, maybe there are solutions out there I haven't thought of yet.
I have a PHP-based CMS.
For each page created in the CMS, the user can upload assets (Files to download, Images, etc.)
Those assets are stored in a directory, let's call it "/myproject/assets", on a per-page basis (1 subdirectory = 1 page, e.g. "/myproject/assets/page19283")
The user can "un-publish" (hide) pages in the CMS. When a page is hidden, and somebody tries to access it because they have memorized the URL or they come from Google or something, they get a "Not found" message.
However, the assets are still available. I want to protect those as well, so that when the user un-publishes a page, they can trust it is completely gone. (Very important on judicial troubles like court orders to take content down ... Things like that can happen).
The most obvious way is to store all assets in a secure directory (= not accessible by the web server), and use a PHP "front gate" that passes the files through after checking. When a project needs to be watertight this is the way I currently go, but I don't like it because the PHP interpreter runs for every tiny image, script, and stylesheet on the site. I would like have a faster way.
.htaccess protection (Deny from all or similar) is not perfect because the CMS is supposed to be portable and able to run in a shared environment. I would like it to even run on IIS and other web servers.
The best way I can think of right now is moving the particular page's asset directory to a secure location when it is un-published, and move it back when it's published. However, the admin user needs to be able to see the page even when it's un-published, so I would have to work around the fact that I have to serve those assets from the secure directory.
Can anybody think of a way that allows direct Apache access to the files (=no passing through a PHP script) but still controlling access using PHP? I can't.
I would also consider a simple .htaccess solution that is likely to run on most shared environments.
Anything sensitive should be stored in a secure area like you suggested.
if your website is located at /var/www/public_html
You put the assets outside the web accessible area in /var/www/assets
PHP can call for a download or you can feed the files through PHP depending on your need.
If you kept the HTML in the CMS DB, that would leave only non-sensitive images & CSS.
If you absolutely have to turn on and off all access to all materials, I think your best bet might be symlinks. Keep -everything- in a non-web-accessible area, and sym link each folder of assets into the web area. This way, if you need to lock people out completely, just remove the symlink rather than removing all files.
I don't like it, but it is the only thing I can think of that fits your crtieria.
I'd just prevent hotlinking of any non-HTML file, so all the "assets" stuff is accessible only from the HTML page. Removing (or protecting) the page just removes everything without having to mess up the whole file system.
Use X-Sendfile
The best and most efficient way is using X-Sendfile. However, before using X-Sendfile you will need to install and configure it on your webserver.
The method on how to do this will depend on the web server you are using, so look up instructions for your specific server. It should only be a few steps to implement. Once implemented don't forget to restart your web server.
Once X-Sendfile has been installed, your PHP script will simply need to check for a logged in user and then supply the file. A very simple example using Sessions can be seen below:
session_start();
if (empty($_SESSION['user_id'])){
exit;
}
$file = "/path/to/secret/file.zip";
$download_name = basename($file);
header("X-Sendfile: $file");
header("Content-type: application/octet-stream");
header('Content-Disposition: attachment; filename="' . $download_name . '"');
Important note:
If you are wanting to serve the file from another webpage such as an image src value you will need to make sure you sanitize your filename. You do not want anyone overriding your script and using ".." etc. to access any file on your system.
Therefore, if you have code that looks like this:
<img src="myscript.php?file=myfile.jpg">
Then you will want to do something like this:
session_start();
if (empty($_SESSION['user_id'])){
exit;
}
$file = preg_replace('/[^-a-zA-Z0-9_\.]/', '', $_GET['file']);
$download_name = basename($file);
header("X-Sendfile: $file");
header("Content-type: application/octet-stream");
header('Content-Disposition: attachment; filename="' . $download_name . '"');
EDIT: How about a hybrid for the administrative interface? In the ACP you could access via the PHP method to, basically, send all file requests to the PHP authing file, but for public, you can use HTTP AUTH/htaccess to determine the availability of the result. this gives you the performance on the public side, but the protection on the ACP side.
OLD MESSAGE:
.htaccess is compatible with most Apache and IIS<7 environments (using various ISAPI modules) when using mod_rewrite type operations. The only exception is IIS7 + the new Rewrite module which uses the web.config file. HOWEVER, I'd be willing to be that you could efficiently generate/alter the web.config file for this instance instead of using .htaccess.
Given that, you could set up redirects using the rewrite method and redirect to your custom 404 Page (that hopefully sends the proper 404 header). It is not 100% appropriate because the actual asset should be the one giving a 403 header, but... it works.
This is the route I would go unless you want to properly create HTTP AUTH setups for every server platform. Plus, if you do it right, you could make your system extendable to allow other types in the future by you or your users (including a php based option if they wanted to do it).
I'm assuming the 'page' is being generated by PHP and the 'assets' should not require PHP. (Let me know if I got that wrong.)
You can rename the assets folder. For example, rename '/myproject/assets/page19283' to '/myproject/assets/page19283-hidden'. This will break all old, memorized links. When you generate the page for admin users that can see it, you just write the urls using the new folder name. After all, you know whether the page is 'hidden' or not. The assets can be accessed directly if you know the 'secret' url.
For additional security, rename the folder with a bunch of random text and store that in your page table (wherever you store the hidden flag): '/myproject/assets/page19283-78dbf76B&76daz1920bfisd6g&dsag'. This will make it much harder to guess at the hidden url.
Just prepend or append a GUID to the page name in the database and the resource directory in the filesystem. The admin will still be able to view it from the admin interface because the link will be updated but the GUID effectively makes the page undiscoverable by an outside user or search engine.
Store your information in a directory outside the web root (i.e.: one directory outside of public_html or htdocs). Then, use the readfile operator in a php script to proxy the files out when requested. readfile(...) basically takes a single parameter--the path to a file--and prints the contents of that file.
This way, you can create a barrier where if a visitor requests information that's hidden behind the proxy, even if they "memorized" the URL, you can turn them down with a 404 or a 403.
I would go with implementing a gateway. You set a .htaccess file to the /assets/ URL pointing to a gateway.php script that will deny if both the credentials are not valid and this particular file is not published or show it.
I'm a little confused. Do you need to protect also the stylesheet files and images? Perhaps moving this folder is the best alternative.
I am trying to secure my PHP Image upload script and the last hurdle I have to jump is making it so that users cannot directly excecute the images, but the server can still serve them in web pages. I tried changing ownership and permissions of the folders to no avail, so I am trying to store the images above public_html and display them in pages that are stored in public_html.
My File Structure:
- userimages
image.jpg
image2.jpg
- public_html
filetoserveimage.html
I tried linking to an image in the userimages folder like this:
<img src="../userimages/image.jpg">
But it does not work. Is there something I am missing here? If you have any better suggestions please let me know. I am trying to keep public users from executing potentially dangerous files they may have uploaded. Just as an extra security measure. Thanks!
You want something that's basically impossible.
The way a browser loads a page (in a very basic sense) is this:
Step 1: Download the page.
Step 2: Parse the page.
Step 3: Download anything referenced in the content of the page (images, stylesheets, javascripts, etc)
Each "Download" event is atomic.
It seems like you want to only serve images to people who have just downloaded a page that references those images.
As PHP Jedi illustrated, you can pass the files through PHP. You could expand on his code, and check the HTTP_REFERER on the request to ensure that people aren't grabbing "just" the image.
Now, serving every image through a PHP passthru script is not efficient, but it could work.
The most common reason people want to do this is to avoid "hotlinking" -- when people create image tags on other sites that reference the image on your server. When they do that, you expend resources handling requests that get presented on someone else's page.
If that's what you're really trying to avoid, you can use mod_rewrite to check the referer.
A decent-looking discussion of hotlinking/anti-hotlinking can be found here
Use an image relay script!
To serve a imagefile that is outside the public_html folder you would have to do it by a php script. E.g make a image-relay.php that reads the image that is outside the public html...
<?php
header('Content-Type: image/jpeg');
$_file = 'myimage.jpg'; // or $_GET['img']
echo file_get_contents('/myimages/'.$_file);
?>
Now, $_file could be a $_GET parameter, but its absolutley important to validate the input parameter...
now you can make an <img src="image-relay.php?img=flower.jpg"> to access a flower.jpg image that is located in /myimage/flower.jpg ...
Well, a web browser will only be able to access files and folders inside public_html.
If the public_html directory is the root of the server for your users, Apache cannot serve anything that is not inside/below that dorectory.
If you want a file to be served by Apache directly, you'll have to put it in/below public_html.
I think your misunderstanding is in the fact that if you include an image in an <img> tag, your browser will send the exact same request to the webserver to fetch it, that will be sent to the webserver if you try to open the src url of the image in your browser directly.
Therefore, either both things work, or neither.
There are hacks around, involving a (php or other) script to make sure that an IP that has requested the image has also requested the html page within the last few seconds (which will not work if the user is behind a proxy that rotates outgoing IPs) or by checking the referer (which does not work with HTTPs and also not if the user has referer disabled).
If you want to make sure that only some users can see the image (both via <img> tag and directly), you can put the image outside public_html and have a (php or other) script that verifies the user's credentials before serving the image.
If you are using Apache or lighttpd you can use the X-Sendfile header to send files that are not in the web root(provided you haven't changed the configuration of mod_xsendfile).
To learn more about X-sendfile see this site.
This solution is giving you the best possible performance as PHP doesn't send the file but the server does and therefore PHP can be exited while the files are being served.
Hope that helps.