0

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?

Motive
  • 3,071
  • 9
  • 40
  • 63

3 Answers3

2

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.

0

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...

emartel
  • 7,712
  • 1
  • 30
  • 58
  • You should look into the `Environments` section on the [Config Class Documentation](http://ellislab.com/codeigniter/user-guide/libraries/config.html) which seems like a more pratcial solution to what you are trying achieve. The environment is specified in `index.php` – Malachi Nov 29 '12 at 14:45
  • @Malachi that's what I use for database settings but for a simple base_url I prefer keeping everything in the same file – emartel Nov 29 '12 at 15:30
0

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"
?>
Community
  • 1
  • 1
Ardavan Kalhori
  • 1,664
  • 1
  • 18
  • 32