Reputation: 3111
I am uploading a file using Codeigniter's File Uploading Library and trying to insert the URL into the database. Codeigniter only supplies the server_path when using $this->upload->data()
, which isn't usable for displaying the image to users.
I could normally just do something like base_url('uploads) . '/' . $data['file_name']
but I am storing the images in a folder for each post.
For example, I am getting C:/xampp/htdocs/site/uploads/32/image.jpg
as the full_path, how can I convert this to http://mysite.com/uploads/32/image.jpg
The only thing that comes to mind is using a regular expression, but I feel like there has to be PHP function or Codeigniter function to help with this?
How can I convert the server path into the correct URL?
Upvotes: 0
Views: 3581
Reputation: 7773
In CodeIgniter
you should use $config['base_url']
You can use the ENVIRONMENT
to setup different base_url
, for example:
switch(ENVIRONMENT)
{
case 'development':
$config['base_url'] = 'http://localhost/';
break;
case 'testing':
$config['base_url'] = 'http://testing.server.com/';
break;
default:
$config['base_url'] = 'http://liveserver.com/';
}
See config.php
Now simply replace your local path with the base_url
, str_replace
should do the job (documentation here)
$newpath = str_replace("C:/xampp/htdocs/site/", $config['base_url'], $localpath);
Also, if you're interested in getting parts of the path, you could use explode
(documented here) with /
to create an array with every "section" of your path
$pathElements = explode('/', $localpath);
In this case, $pathElements[0]
is C:
, $pathElements[1]
is xampp
, etc...
Upvotes: 0
Reputation: 1698
you only need to save the filename to the database and just use the post id and filename:
$url = "http://mysite.com/uploads/" . $postID . "/" . $fileName;
to get the file name use: How to get file name from full path with PHP?
<?php
$path = "C:/xampp/htdocs/site/uploads/32/image.jpg";
$file = basename($path); // $file is set to "image.jpg"
$file = basename($path, ".jpg"); // $file is set to "image"
?>
Upvotes: 0
Reputation: 152
You can use $_SERVER['HTTP_HOST']; to get the url. Using the ID for your post, you can construct your path like so:
$url = "http://" . $_SERVER['HTTP_HOST'] . "/" . $id . "/" . basename($data['file_name']);
the basename() function returns everything after the last / in your path.
Upvotes: 2