Get URL from server path - php

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?

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.

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"
?>

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

Related

Delete images where image path is saved with path in database

I am uploading an image and while saving to the database I am adding path to the location along with the filename.
eg : product/name/L4I84qXltYvCCDsAeQzi7fzZfKF3WTRa1LPOPGxj.jpeg
Why adding location where I can call them through asset()?
The table is also used by API application where it requires the url format like this.
My Controller Cdde
//! Product Image
if ($request->hasFile('product_image')) {
$product_image = $request->file('product_image');
$product_image_extension = $product_image->getClientOriginalExtension();
$product_image_filename = Str::slug($request->input('product_code')) . '.' . Str::random(3) . "." . $product_image_extension;
$product_image_location = public_path('assets/products/' . $product_image_filename);
Image::make($product_image)->resize(300, 300)->save($product_image_location);
}
Products::create([
//Other Fields
'image' => 'assets/products/' . $product_image_filename
]);
I am wondering how do I remove the image and add a new image
For comparison, I need the image file name. Since I am using the path, I am getting the path prefixed to the Image Name.
use Illuminate\Support\Facades\File
$image_path = "/images/filename.ext"; // Value is not URL but directory file path
if(File::exists($image_path)) {
File::delete($image_path);
}
use File;
#unlink(public_path() . 'uploads/documents/' . $users->document1);

Php generated wrong format url file path after upload to server

Below is the code for me to generate a unique file Url of each image uploaded and store it to database.
//create unique image file name based on micro time and date
$now = DateTime::createFromFormat('U.u', microtime(true));
$id = $now->format('YmdHisu');
// Path to move uploaded files
$target_path = "uploads";
//the file name
$path = "$target_path/$id.jpeg";
// getting server ip address
$server_ip = gethostbyname(gethostname());
// final file url that is being uploaded
$file_upload_url = 'http://'. $server_ip . '/' . 'abc' . '/' .$path;
What I expect for this code should generate the url in json_encode as below:
http://111.111.11.1/abc/uploads/20170226041004809200.jpeg
But now the problem is it generate the Url but in json_encode result is like below
http:\/\/111.111.11.1\/abc\/uploads\/20170226041004809200.jpeg
What I tried so far,
$file_upload_url = 'http:'. $server_ip . 'abc' .$path;
But it not what I want,it become this
http:111.111.11.1.1abcuploads\/20170226041515563600.jpeg
Can somebody have any idea how to solve this?Or have a better suggestion?
If you are working on same server then why don't you try to upload file with code snippet-
$file_upload_url = realpath($_SERVER["DOCUMENT_ROOT"]). '/abc' . '/' .$path;
// you can manage url by -
$base_url = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
$base_url.=$_SERVER['SERVER_ADDR'];
$base_url.='/abc/'.$path
// now print your url-
echo $base_url;
Use str_replace to replace the \
<?php
$file_upload_url = "http:\/\/111.111.11.1\/abc\/uploads\/20170226041004809200.jpeg";
$upload_path = str_replace('\\','',$file_upload_url);
echo $upload_path;
?>

Image Class Function not working correctly due to path

I'm using the below function:
class Image {
static function url($id, $type = 'maps') {
$path = UPLOAD_DIRECTORY . '/' . $type . '/';
$files = glob($path . $id . '.*');
if (count($files)) {
$ext = substr($files[0], strpos($files[0], '.') - strlen($files[5]));
return SERVER_URL . 'img/' . $type . '/' . $id . $ext;
} else {
return '';
}
}
}
It works fine when hosted on WAMP but when using on Unix running on nginx it doesn't display the image correctly because of the file path. It seems to add the physical path of the files in the URL so it thinks the patch of the file is http://localhost/demo/img/maps/20/public_html/demo/img/maps/20.png
On WAMP it displays correctly ie the URL is http://localhost/demo/img/maps/20.png
These are the defined variables:
define('SERVER_URL', 'http://localhost/demo/');
define('UPLOAD_DIRECTORY', dirname(__FILE__) . '/img');
id=20;
Physical location of the images are in /public_html/demo/img/maps/
How can I fix this on a unix OS.
Managed to work out a solution (btw I'm not a programmer).
Basically on the UNIX server the directory where the images were located had a dot in the path whereas on wamp it didn't.
So what I had to do is use the strrpost instead of strpost - this finds the position of the last occurrence of a substring in a string instead of the first occurance.

file_exists() not working codeigniter

I am working with codeigniter. I want to display images but if some image is not exist it should show image-not-found-medium.jpg which is dummy image..
below is my code
<?php
$image_path_medium = site_url('assets/images-products/medium');
$image_not_found_medium = $image_path_medium . "/" . "image-not-found-medium.jpg";
$image_name_with_path = $image_path_medium . "/" . $home_technology[$key]->product_sku . "-" . "a" . "-medium.jpg";
if (file_exists($image_name_with_path)) {
echo $image_name_with_path;
} else {
echo $image_not_found_medium;
}
?>
but it always shows $image_not_found_medium i think there is problem with my if condition.
Please help.
<?php
$image_path_medium = site_url('assets/images-products/medium');
$image_not_found_medium = $image_path_medium . "/" . "image-not-found-medium.jpg";
$image_name_with_path = $image_path_medium . "/" . $home_technology[$key]->product_sku . "-" . "a" . "-medium.jpg";//this is your image url
$image_file_path=FCPATH.'assets/images-products/medium'. $home_technology[$key]->product_sku . "-" . "a" . "-medium.jpg";//this is your file path
if (file_exists($image_file_path)) //file_exists of a url returns false.It should be real file path
{
echo $image_name_with_path;
}
else
{
echo $image_not_found_medium;
}
?>
You are using absolute path for file existence which is wrong. You have to use real path because the file_exists() function checks whether or not a file or directory exists on the current server.
If your assets folder is placed in root then just use getcwd() - Gets the current working directory as
$image_path_medium = getcwd().'assets/images-products/medium';
Otherwise give the proper path to the assets folder like
$image_path_medium = getcwd().'application/views/assets/images-products/medium';
Instead of file_exists() prefer is_file() when checking files, as file_exists() returns true on directories. In addition, you might want to see if getimagesize() returns FALSE to make sure you have an image.
Use like this.
$g = base_url().'upload/image.jpg';
if(file_exists($g) !== null){//your code..}
This is works for me in CI.

Get thumbnail image from the original image path

I store the original image path(included file name) in db when upload an image.
For example:
img/uploaded/photo.jpg
Then I generate its thumbnail and store in below directory NOT in db.
/img/uploaded/thumbs/photo_thumb.jpg
And I have following function but no idea how to get the thumb which belong to the url in db.
//ie: $file is img/uploaded/photo.jpg
public function get_thumb($file)
{
//get the path without filename
$get_path = dirname($file) . "/thumbs/";
//result img/uploaded/thumbs/ (how can i get the photo_thumb.jpg) here?
return $get_path;
}
Edit
basename($file) to get filename from path but how to add _thumb.jpg?
Don't have much experience with PHP but using this as starting point, I get:
$pattern = '/^.*\/(.*)$/'; // match everything after the last slash and store it in $1
$replacement = '$1';
$filename = preg_replace($pattern, $replacement, $file);
$get_path = $file . '/thumbs/' . $filename;
As I said, not much experience with PHP, but this should do it...
A more easy way to do this, could be:
Find the last / in $file
Insert thumbs/ after it or replace it with /thumbs/
Find the last . in the edited $file
Insert _thumb after it
You can find the postitions of / and . with the strrchr function (documented here).
You can do this :
public function get_thumb($file) {
$infos = pathinfo($file);
$path = $infos['dirname'] . '/thumbs/' . $infos['filename'] . '_thumb.' . $infos['extension'];
return $path;
}
Usually, the way I do this is, is to store just the filename in the db. (assuming that they are all in the same directory).
Then query the database and get the filename, store it in:
$filename;
Then I just echo out something like
echo base_url('images/thumbs/' . $filename);
Hope this helps!

Categories