Alright so everything is being saved properly but how can I get the url of the file I am saving?
$songs = file_get_contents('https://example.com/tracks/'.$id.'/');
file_put_contents('./tmp/' . stripslashes(htmlspecialchars($songTitle)) . '.mp3', $songs);
Without manually having to get every url, please note I am a new developer still learning.. but is there not something I can just echo into an ??
Edit: ' . stripslashes(htmlspecialchars($songTitle)) . ' this is just the name of the file that we're downloading, nothing important about that string.
This depends on your setup, but if your script is in an externally accessible location and you trust $_SERVER client-defined fields, you can use __FILE__ and $_SERVER to accomplish what you want.
The code below assumes:
Your server is not on HTTPS;
Files in the subdirectory tmp can be accessed externally;
You can write to the subdirectory tmp.
$_SERVER['HTTP_HOST'] and $_SERVER['REQUEST_URI'] can be "trusted".
Try this:
// This is the only thing you need to set to your taste.
$dest_rel_path = 'tmp/' . stripslashes(htmlspecialchars($songTitle)) . '.mp3';
// This is the final file path in your filesystem.
// `dirname(__FILE__)` can be replaced with __DIR__ in PHP >= 5.3.0
// and the str_replace() part makes the code portable to Windows.
$filesystem_path = dirname(__FILE__) . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dest_rel_path);
$songs = file_get_contents('https://example.com/tracks/'.$id.'/');
file_put_contents($filesystem_path, $songs);
// This takes the URL that the user requested and replaces the
// part after the last '/' with our new .mp3 location.
$req_uri = $_SERVER['REQUEST_URI'];
$url_path = substr($req_uri, 0, 1 + strrpos($req_uri, '/')) . $dest_rel_path;
$url = 'http://' . $_SERVER['HTTP_HOST'] . $url_path;
echo "This is my link to $songTitle!";
You can't, at least not directly, since it does not work that way: the filesystem does not necessarily translate to an URL.
For instance, in your case, you're saving the file into the tmp directory. I doubt that directory is accessible in any way to the outside world, ie, that it has a public URL than you can access in your browser.
Related
I want to make a path to be used with links and src attributes in my html - how do i achieve this?
my attempts:
Home
or
<img src="' . $_SERVER['DOCUMENT_ROOT'] . '.images/whatever.jpg">
Can anyone expound upon this?
$_SERVER['DOCUMENT_ROOT'] returns that path to the document root on the server, for instance: /var/www/my.website.org/src or C:/wamp/www/my.website.org/src.
You shouldn't use it to make URLs directly, you can use it to make relative paths, for instance:
$root = $_SERVER['DOCUMENT_ROOT'];
$file_path = __FILE__;
$relative_file_path = str_replace($root, "", $file_path); // needs better logic but works in some cases
$base_url = "http://my.website.org/";
$url = $base_url . $relative_file_path; // http://www.mywebsite.org/path/to/file.php
I have been working on a little PHP script that dynamically creates & saves images in a folder tmp (which already exists!) from a base64 string. This is my save.php file.
// get base-64 string from form
$filteredData = substr($_POST['img_val'], strpos($_POST['img_val'], ",")+1);
// decode string
$unencodedData = base64_decode($filteredData);
// create unique filename
$a = uniqid();
// name, location and file extension
$compfile = '/tmp/' . $a . '.png';
// save image
file_put_contents($compfile, $unencodedData);
// print image
echo '<img src="' . $compfile . '" />';
Strangely enough: It will neither create nor render the image on the page, because of the /tmp/ in my $compfile variable. When I remove it, everything works like a charm and the image is being created in the same folder.
Unfortunately, I really want the image to be created in the /tmp/ folder. Before $compfile was a randomly generated filename, and instead was called /tmp/img.png I was able to save to create an image by the name img.png and save it to the tmp.
What am I missing here?
(Thank you for your time.)
Since I guess this was the solution I'll post it as answer.
I think you want "tmp/" . $a . ".png" instead of "/tmp/" . $a . ".png". It's good practice to just always use absolute paths, so: __DIR__ . "/tmp/" . $a . ".png". This takes away any confusion.
I need some help with concepts and terminology regarding website 'root' urls and directories.
Is it possible to determine a website's root, or is that an arbitrary idea, and only the actual server's root can be established?
Let's say I'm writing a PHP plugin that that will be used by different websites in different locations, but needs to determine what the website's base directory is. Using PHP, I will always be able to determine the DOCUMENT_ROOT and SERVER_NAME, that is, the absolute URL and absolute directory path of the server (or virtual server). But I can't know if the website itself is 'installed' at the root directory or in a sub directory. If the website was in a subdirectory, I would need the user to explicitly set an "sub-path" variable. Correct?
Answer to question 1: Yes you need a variable which explicitly sets the root path of the website. It can be done with an htaccess file at the root of each website containing the following line :
SetEnv APP_ROOT_PATH /path/to/app
http://httpd.apache.org/docs/2.0/mod/mod_env.html
And you can access it anywhere in your php script by using :
<?php $appRootPath = getenv('APP_ROOT_PATH'); ?>
http://php.net/manual/en/function.getenv.php
Will $url and $dir always be pointing to the same place?
Yes
<?php
$some_relative_path = "hello";
$server_url = $_SERVER["SERVER_NAME"];
$doc_root = $_SERVER["DOCUMENT_ROOT"];
echo $url = $server_url.'/'. $some_relative_path."<br />";
echo $dir = $doc_root.'/'. $some_relative_path;
Output:
sandbox.phpcode.eu/hello
/data/sandbox//hello
You shouldn't need to ask the user to provide any info.
This snippet will let your code know whether it is running in the root or not:
<?php
// Load the absolute server path to the directory the script is running in
$fileDir = dirname(__FILE__);
// Make sure we end with a slash
if (substr($fileDir, -1) != '/') {
$fileDir .= '/';
}
// Load the absolute server path to the document root
$docRoot = $_SERVER['DOCUMENT_ROOT'];
// Make sure we end with a slash
if (substr($docRoot, -1) != '/') {
$docRoot .= '/';
}
// Remove docRoot string from fileDir string as subPath string
$subPath = preg_replace('~' . $docRoot . '~i', '', $fileDir);
// Add a slash to the beginning of subPath string
$subPath = '/' . $subPath;
// Test subPath string to determine if we are in the web root or not
if ($subPath == '/') {
// if subPath = single slash, docRoot and fileDir strings were the same
echo "We are running in the web foot folder of http://" . $_SERVER['SERVER_NAME'];
} else {
// Anyting else means the file is running in a subdirectory
echo "We are running in the '" . $subPath . "' subdirectory of http://" . $_SERVER['SERVER_NAME'];
}
?>
I have just had the same problem. I wanted to reference links and other files from the root directory of my website structure.
I tried the following but it would never work how I wanted it:
$root = $_SERVER['DOCUMENT_ROOT'];
echo "Link";
echo "Link";
But the obvious solution was just to use the following:
echo "Link";
echo "Link";
I have a localhost Apache/PHP configuration on my computer. I want to be able to
1) check the existence of an image file using an absolute path and
2) display it using the same URL
A simple example of something I want to do:
if(file_exists($url)) {
echo '<img src="' . $url . '" />';
}
if I set...
$url = 'http://' . $_SERVER['HTTP_HOST'] . '/myimg.jpg';
then file_exists will return false, because the URL is a web path (http://localhost/myimg.jpg).
if I set...
$url = $_SERVER['DOCUMENT_ROOT'] . '/myimg.jpg';
it will recognize that the file exists (C:/htdocs/myimg.jpg), but fail to display the image because it cannot access the image source. If I view the source and copy/paste the URL into the web browser's address bar, the image is displayed just fine.
Perhaps I'm missing something in Apache's httpd.conf file, or PHP.ini? Maybe an Alias declaration of some sort. Also, the site will be uploaded to a remote web server (such as bluehost.com) when it is complete, so I need a versatile solution.
allow_url_fopen in PHP.ini is On, and I've been restarting the server every time I make a change in either httpd.conf or PHP.ini. I've been struggling with this for days, so even a point in the right direction would be very appreciated :)
Thanks.
You're confusing server side file access with client side.
$url = 'http://' . $_SERVER['HTTP_HOST'] . '/myimg.jpg';
This produces a URI to be used by the client to fetch your image via HTTP. For example http://example.com/myimg.jpg
$url = $_SERVER['DOCUMENT_ROOT'] . '/myimg.jpg';
This produces a filesystem path to be used by PHP. For example /var/www/htdocs/myimg.jpg
Your solution needs to use both
$img = '/myimg.jpg';
if(file_exists($_SERVER['DOCUMENT_ROOT'] . $img)) {
echo '<img src="', $_SERVER['HTTP_HOST'], $img, '" />';
}
Edit: You could probably replace the echo line with
echo '<img src="', $img, '" />';
as an absolute URL (one beginning with a forward slash) always starts at the document root
An absolute path, which file_exists takes, is completely different from your web path. You'll just need to use separate paths for file_exists and your src attribute in your img tag.
$img = 'myimg.jpg';
if (file_exists($_SERVER['DOCUMENT_ROOT'] . '/' . $img) {
echo '<img src=' . $img . ' />';
}
<?php
$url = "/myimg.jpg";
if( file_exists($_SERVER['DOCUMENT_ROOT'].$url))
echo "<img src='".$url."' />";
?>
This will give you the HTML:
<img src='/myimg.jpg' />
Which is the image since it resolves from the domain name.
I'm building a small class for my zend application (using MVC). This class receive either a folder path or a file path. If its a folder path, i want to list all the files in that folder to make them downloadable. If its a file i want to make a single link to this file to make it downloadable.
The file/folder i'm pointing to is /zendApplicationName/Public/Models/Subfolder/File.
i tried to check using
is_file('pathToFile')
and
is_dir('pathToFolder')
to check the path that i build using
APPLICATION_PATH . '..\public' . $this->_path . 'file.docx'
and
$this->_baseUrl' . $this->_path . 'file.docx' // i took the baseURL from Zend_Controller_Front::getInstance()
I also tried to use the old school php version
$protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https'?'https':'http';
$path = $protocol . '://' . $_SERVER['HTTP_HOST'] . $this->_baseUrl . $this->_path . 'file.docx'
Thanks in advance
EDIT :
The problem is that even if the folder and the file exists, both function return false
Thanks for you comments, both where really useful. They made me recheck my code and the path was wrong
final path output is:
C:\wamp\www\elul\trunk\elul\application/../public/models/feuilleDeRoute/
using :
APPLICATION_PATH . DIRECTORY_SEPARATOR
. '..' . DIRECTORY_SEPARATOR .
'public' . $this->_path;
This way both can be checked, the folder and the file