I'm trying to access a page from another domain, I can get all other html from php, but the files like images and audio files have relatives paths making them to be looked inside the local server whereas they're on the other server.
I've allowed cross-domain access though PHP from the other page.
header('Access-Control-Allow-Origin: *');
Then I use AJAX load to load that pages' content.
$('#local_div').load('page_to_load_on_side_B #div_on_that_page');
Now, the path looks like this:
../../user/6/535e55ed00978.jpg
But I want it to be full like.
http//:www.siteB.com/user/6/535e55ed00978.jpg
Correction: I have full access to both sites so I need to get the absolute paths from the site where these files are originating.
For this problem would use one of the following:
Server Side Approach
I would create a parameter in server B named for example abspath. When this param is set to 1 the script would start an output buffer ob_start() then before submiting would get ob contents with ob_get_clean() and finally using regular expressions make a replace of all urls for http//:www.siteB.com/. So, the script on server A would look like follows:
<?php
$abspath=(isset($_REQUEST["abspath"])?$_REQUEST["abspath"]:0);
if($abspath==1) ob_start();
// Do page processing (your actual code here)
if($abspath==1)
{
$html=ob_get_clean();
$html=preg_replace("\.\.\/\.\.\/", "http://siteb.com/");
echo $html;
}
?>
So in client side (site A) your ajax call would be:
$('#local_div').load('page_to_load_on_side_B?abspath=1#div_on_that_page');
So when abspath param is set to 1 site B script would replace relative path (note I guessed all paths as ../..) to absolute path. This approach can be improved a lot.
Client Side Approach
This replace would be done in JavaScript locally avoiding changing Server B scripts, . The replacements in Javascript would be the same. If all relative paths starts with ../.. the regex is very simple, so in site A replace $('#local_div').load('page_to_load_on_side_B #div_on_that_page'); for the following (note that I asume all relatives urls starts with ../..):
$.get('page_to_load_on_side_B #div_on_that_page', function(data) {
data=data.replace(/\.\.\/\.\.\//, 'http://siteb.com/');
$('#local_div').html(data);
});
That will do the replacement before setting html to DIV so images will be loaded from absolute URL.
Ensure full CORS access to site B.
The second approach is clean than the first so I guess would use Javascript to do the replacements, both are the same only changes where the replace is done.
There is a PHP function that can make absolute path from relative one.
realpath()
If you mean URL path, simply replace all occurences of "../" and add domain in front.
Try this one:
function getRelativePath($from, $to)
{
// some compatibility fixes for Windows paths
$from = is_dir($from) ? rtrim($from, '\/') . '/' : $from;
$to = is_dir($to) ? rtrim($to, '\/') . '/' : $to;
$from = str_replace('\\', '/', $from);
$to = str_replace('\\', '/', $to);
$from = explode('/', $from);
$to = explode('/', $to);
$relPath = $to;
foreach($from as $depth => $dir) {
// find first non-matching dir
if($dir === $to[$depth]) {
// ignore this directory
array_shift($relPath);
} else {
// get number of remaining dirs to $from
$remaining = count($from) - $depth;
if($remaining > 1) {
// add traversals up to first matching dir
$padLength = (count($relPath) + $remaining - 1) * -1;
$relPath = array_pad($relPath, $padLength, '..');
break;
} else {
$relPath[0] = './' . $relPath[0];
}
}
}
return implode('/', $relPath);
}
Also you can find below solution:
In general, there are 2 solutions to this problem:
1) Use $_SERVER["DOCUMENT_ROOT"] – We can use this variable to make all our includes relative to the server root directory, instead of the current working directory(script’s directory). Then we would use something like this for all our includes:
include($_SERVER["DOCUMENT_ROOT"] . "/dir/script_name.php");
2) Use dirname(FILE) – The FILE constant contains the full path and filename of the script that it is used in. The function dirname() removes the file name from the path, giving us the absolute path of the directory the file is in regardless of which script included it. Using this gives us the option of using relative paths just as we would with any other language, like C/C++. We would prefix all our relative path like this:
include(dirname(__FILE__) . "/dir/script_name.php");
You may also use basename() together with dirname() to find the included scripts name and not just the name of the currently executing script, like this:
script_name = basename(__FILE__);
I personally prefer the second method over the first one, as it gives me more freedom and a better way to create a modular web application.
Note: Remember that there is a difference between using a backslash “\” and a forward (normal) slash “/” under Unix based systems. If you are testing your application on a windows machine and you use these interchangeably, it will work fine. But once you try to move your script to a Unix server it will cause some problems. Backslashes (“\”) are also used in PHP as in Unix, to indicate that the character that follows is a special character. Therefore, be careful not to use these in your path names.
Related
I'm trying to create a link to a shell script in a Node in Freeplane.
When I monitor the text in the node node.link.text I get execute_:script.sh%20/home/dir/file.ext
Ok, It works, but when my path has special characters link spaces or ( ), it isn't able to open. I already tried to use URLEncoder from java.net:
filePath='/home/user/Books/Author Name/File (231)/Book - Author.pdf'
urlEncoder = new URLEncoder()
def urlEncode(String s) {
urlEncoder.encode(s).replace("+", "%20");
}
fileLink = 'execute:_docreader.sh%20-p%20' + page + '%20' + urlEncode(filePath)
createdNode.link.setText(fileLink)
But I couldn't execute any command with files as arguments whose path have special characters. I even tried to put ' or " in the path manually but it didn't work too.
If filePath are without special characters, like /home/user/Books/AuthorName/file.pdf it works fine.
I look into Freeplane wiki and Freeplane API, looked into the examples but havent found any clue about that.
I wrote a script in groovy to find files java test files recursively in a given directory with certain names, the concerned part of the code is:
def projectRootDirectory = args.length ? new File(args[0]) : new File(System.getProperty("user.dir"))
def srcFilesCount = 0, testFilesCount = 0, srcLinesCount=0, testLinesCount=0
def srcFileSubstringPattern = '.java'
def testFileSubstringPattern = 'Test.java'
projectRootDirectory.eachDirRecurse() { dir ->
dir.eachFile {
if (it.name.endsWith(testFileSubstringPattern) || it.name ==~ /Test.*java/ ||
it.name.endsWith('Tests.java') || it.name.endsWith('TestCase.java')) {
//println "Test file found: " + it.name
testFilesCount++
it.eachLine { testLinesCount++ }
} else if (it.name.contains(srcFileSubstringPattern)) {
srcFilesCount++
it.eachLine { srcLinesCount++ }
}
}
}
It finds already existing files in the repo which was cloned using SVN that match for example someTestCase.java, but when I created some new ones by using the command touch dummyTestCase.java via Cygwin in Windows 7 or via the Windows 7 explorer right click -> New -> Text Document option and rename it to something like TestDummy.java, it doesn't find them. The script also treats copies of the respective files the same way i.e. it finds copies of old files that already existed but not the new ones I create. I even opened up file permissions to fullest on the newly created files, but no change. Whereas the BASH find command via Cygwin always finds all the files without any issue. I have confirmed using diagnostic print statements the the script is looking in the correct directory. I even confirmed this by having the script create some files there and confirmed they got created in the correct place.
Wow, the answer turned out to be amazingly simple. I replaced eachDirRecurse with eachFileRecurse thus also eliminating the nested loop. Thanks a ton to all the comment authors whose help led me to this discovery.
Please modify the above program, so it replaces all the images (e.g. .jpg or .gif images) inside any page with a picture of your choice. When an HTML web page contains images, the browser will identify those image URLs, and send out an URL request for each image. You should be able to see the URLs in your URL rewriting program. You just need to decide whether a URL is trying to fetch an image file of a particular type; if it is, you can replace the URL with another one (of your choice).
use strict;
use warnings;
# Forces a flush after every write or print on the STDOUT
select STDOUT; $| = 1;
# Get the input line by line from the standard input.
# Each line contains an URL and some other information.
while (<>)
{
my #parts = split;
my $url = $parts[0];
# If you copy and paste this code from this PDF file,
# the ˜ (tilde) character may not be copied correctly.
# Remove it, and then type the character manually.
if ($url =˜ /www\.cis\.syr\.edu/) {
# URL Rewriting
print "http://www.yahoo.com\n";
}
else {
# No Rewriting.
print "\n";
}
}
Look at the if block. It's matching on the URL and then performing an action. You just need to do something similar.
Have a look at the perlrequick page for a quick overview of how regular expressions work in Perl.
I'm stuck on a roadblock with the simplest of things. In Drupal 6, I'm trying to take a user-entered path to an image and output that image to the page. Here's a bit of code:
$slogan_image = theme('image', $slogan_image_path);
dpm("\$slogan_image_path = '$slogan_image_path'");
dpm("\$slogan_image = '$slogan_image'");
The devel output reads:
$slogan_image_path = '/sites/default/files/images/Family.jpg'
$slogan_image = ''
There is an image at '/sites/default/files/images/Family.jpg'; if I browse to www.mysite.com/sites/default/files/images/Family.jpg, the image will be displayed.
What am I doing wrong? Thanks.
The problem was that my path began with a slash. Drupal paths don't have that initial slash. Drupal being open source, I could look refer to the Drupal 6 api docs and see the code for theme_image included this line:
$url = (url($path) == $path) ? $path : (base_path() . $path);
showed me that Drupal would prepend my path with the base_path(). Executing that code myself, in an Execute PHP page, allowed me to see that theme_image would wind up using //sites/default/files/images/Family.jpg as the $url, clearly an illegal value.
I thought I'd append this short explanation to my trivial problem to help rank beginners see how I debugged it.
I tried everything possible, but still failed. I thought I got it at the point which I'll post
as my final attempt, but still isn't good [enough].
A script is being passed three arguments. Domain name, username and password.
But the probles is that I need domain separated in "domain" + ".com" format. Two variables.
I tried to split it using name.extension cheat, but it doesn't work quite well.
Check the simple code:
#echo off
echo.
set domain=%~n1
set ext=%~x1
echo %DOMAIN%
echo %EXT%
echo.
When you try it, you get:
D:\Scripts\test>test.bat domain.com
domain
.com
D:\Scripts\test>test.bat domain.co.uk
domain.co
.uk
First obviously does work, but only because I'm able to cheat my way through.
String operations in DOS Shell are a pain in the ass. I might be able to convince
a script writer to pass me 4 arguments instead of 3... but in case that fails... HELP!
Windows ships with the Windows Scripting Host which lets you run javascript.
Change the batch file to:
#echo off
cscript //Nologo test.js %*
Create test.js:
if (WScript.Arguments.Length > 0) {
var arg = WScript.Arguments.Item(0);
var index = arg.indexOf('.');
if (index != -1) {
var domain = arg.substring(0, index);
var ext = arg.substring(index);
WScript.Echo(domain);
WScript.Echo(ext);
} else WScript.Echo("Error: Argument has no dots: " + arg);
} else WScript.Echo("Error: No argument given");
And you can use it:
C:\Documents and Settings\Waqas\Desktop>test.bat domain.com
domain
.com
C:\Documents and Settings\Waqas\Desktop>test.bat domain.co.uk
domain
.co.uk
And that does what I think you wanted.
If you want to automatize something (as stated in another answer), my solution would be to use appropriate tools. Install a Perl runtime or something else you're comfortable with. Or use the Windows power shell
Also, unless you supply your script with a list of valid top level domains, there is NO WAY, in no language, that your script can decide whether test.co.uk should be splitted as text and co.uk or test.co and uk. The only feasible possibility would be to make sure that you get only second-level-domains without sub-domain parts. Simply split at the first dot in that case.
BTW: I'm curious to why you would want to automate website creation in a Windows shell script. You aren't doing anything nasty, are you?