PHP convert '../folder/file.php' into url - php

So I'm working on a website currently on localhost. I'm testing an image uploader, and I have to generate an URL for the image to be displayed..
etc etc..
// move the file to folder <- it works
move_uploaded_file($_FILES["file"]["tmp_name"], '../../common/img/post-uploads/' . $name);
// Generate response.
$response = new StdClass;
$response->link = MAINFOLDER . '/common/img/post-uploads/' . $name; // but I need an URL here..?:/
echo stripslashes(json_encode($response));
As you see, when I move the uploaded file to path, it works like this "../../common/img/post-uploads"
but at the end, I would like to get an URL.. so the final diplayed image would be like
< img src="http://localhost/mysite/common/image/post-uploads/image.jpg">
is it possible somehow? like
$response->link = convertThisToURL('../../common/img/post-uploads/' . $name);
? :/

Since you show two ../ I would think that this item is outside of your domain. There isn't a way to do that unless the full link is inside the domain directory.
Per your comment below then answer then would be a symbolic link.
ln -s /localhost/mysite/common/img/post-uploads /localhost/mysite/images
For example. then just post that nice new url without all that ../ stuff

Related

is it possible to send a zipped folder from server (php) to front end (angular) ? or is there another way to do it

I am using drupal as a back end.
in drupal I get some .pdf files. and then zip them using drupal zip archive. then saving this archive in my server tmp folder, i get the tmp folder using php sys_get_temp_dir()
now...
what should i return to the front end (Angular) so that the user can download this folder..
this is an example code i used for zipping:
$nodesIds = [1024, 1023, 1022]; // those are just some example ids, i get the real ids from the front end post request.
$zipName = $this->generateUniqueName();
$zip = new \ZipArchive;if(!$zip->open(sys_get_temp_dir() . '/' . $zipName, constant("ZipArchive::CREATE"))) {
return new JsonResponse('could not open zip');
}
foreach ($nodesIds as $id) {
$node = \Drupal\node\Entity\Node::load($id);
$uri = $node->filed_file->entity->getFileUri();
$name = $node->field_file->entity->id() . '_'. $node->field_file->entity->getFilename();
$url = $file_system->realpath($uri);
$zip->addFile($url, $name);
}
$zip->close();
i tried returning a link to the zipped folder in the server:
return new JsonResponse(sys_get_temp_dir() . '/' . $zipName);
but i dont know what to do with that from angular.
Also tried to return a stream using symfony:
$stream = new Stream(sys_get_temp_dir() . '/' . $zipName);
$response = new BinaryFileResponse($stream);
a stream and not a file because the user chooses which files to zip.. so they can choose as much as they want.. it might get to even a 100 .pdf files ..
every thing works fine and i get the zipped folder in tmp.. but now what ?
I want to download this zipped folder to the user browser..
but I do not know how!. should I return the zipped folder, then in angular use it as a blob or somehow deal with it and serve it to the user,,
or maybe the right way is to send back the link to its location in the tmp folder,, and in angular i only access that location and somehow get the folder (i dont know if this is even possible due to permissions and security), or is there another better way that I do not know about.
thank you very much.

What is the best way to get the parameters in PHP?

I will completely clarify my question, sorry to everybody.
I have code writed in files from a website that now is not working, the html code is on pages with php extension, in a folder of a Virtual Host in my PC using Wampserever. C:\wamp\1VH\PRU1, when the site was online there was a folder where was a file called image.php. This file was called from other pages inside the site like this: (a little code of a file, C:\wamp\1VH\PRU1\example.php)
"<div><img src="https://www.example.com/img/image.php?f=images&folder=foods&type=salads&desc=green&dim=50&id=23" alt="green salad 23"></div>"
And the result was that the images was showed correctly.
Now, like i have this proyect in local, and i HAVE NOT the code of that image.php file i must to write it myself, this way the images will be showed the same way that when the site was online.
When the site was online and i open a image returned by that image.php file the URL was, following the example, https://example.com/images/foods/salads/green_50/23.png.
Now how the site is only local and i have not that image.php file writed because i'm bot sure how to write it, the images obviously are not showed.
In C:\wamp\1VH\PRU1\example.php the code of files was changed deleting "https://www.example.com/img/image.php?" for a local path "img/image.php?".
And in the same folder there is anothers: "img" folder (here must be allocated the image.php file), and "images" folder, inside it /foods/salads/green_50/23.png, 24.png.25.png..............
So i have exactly the same folder architecture that the online site and i changed the code that i could only, for example replacing with Jquery "https://www.example.com/img/image.php?" for "img/image.php?" but wich i can not do is replace all the code after the image.php file to obtain a image file.
So i think that the easiest way to can obtain the images normally is creating that IMAGE.PHP file that i have not here in my virtual host.
I'd like to know how to obtain the parameters and return the correct URL in the image,php file.
The image of the DIV EXAMPLE must be C:/wamp/1VH/PRU1/images/foods/salads/green_50/23.png
I have in my PC the correct folders and the images, i only need to write the image.php file.
Note that there are "&" and i must to unite the values of "desc=green&dim=50&" being the result: green_50 (a folder in my PC).
TVM.
You probably want something like this.
image.php
$id = intval($_GET['id']);
echo '<div><img src="images/foods/salads/green_50/'.$id.'.png" alt="green salad '.$id.'"></div>';
Then you would call this page
www.example.com/image.php?id=23
So you can see here in the url we have id=23 in the query part of the url. And we access this in PHP using $_GET['id']. Pretty simple. In this case it equals 23 if it was id=52 it would be that number instead.
Now the intval part is very important for security reasons you should never put user input directly into file paths. I won't get into the details of Directory Transversal attacks. But if you just allow anything in there that's what you would be vulnerable to. It's often overlooked, so you wouldn't be the first.
https://en.wikipedia.org/wiki/Directory_traversal_attack
Now granted the Server should have user permissions setup properly, but I say why gamble when we can be safe with 1 line of code.
This should get you started. For the rest of them I would setup a white list like this:
For
folder=foods
You would make an array with the permissible values,
$allowedFolders = [
'food',
'clothes'
'kids'
];
etc...
Then you would check it like this
///set a default
$folder = '';
if(!empty($_GET['folder'])){
if(in_array($_GET['folder'], $allowedFolders)){
$folder = $_GET['folder'].'/';
}else{
throw new Exception('Invalid value for "folder"');
}
}
etc...
Then at the end you would stitch all the "cleaned" values together. As I said before a lot of people simply neglect this and just put the stuff right in the path. But, it's not the right way to do it.
Anyway hope that helps.
You essentially just need to parse the $_GET parameters, then do a few checks that the file is found, a real image and then just serve the file by setting the appropriate content type header and then outputting the files contents.
This should do the trick:
<?php
// define expected GET parameters
$params = ['f', 'folder', 'type', 'desc', 'dim', 'id'];
// loop over parameters in order to build path: /imagenes/foods/salads/green_50/23.png
$path = null;
foreach ($params as $key => $param) {
if (isset($_GET[$param])) {
$path .= ($param == 'dim' ? '_' : '/').basename($_GET[$param]);
unset($params[$key]);
}
}
$path .= '.png';
// check all params were passed
if (!empty($params)) {
die('Invalid request');
}
// check file exists
if (!file_exists($path)) {
die('File does not exist');
}
// check file is image
if (!getimagesize($path)) {
die('Invalid image');
}
// all good serve file
header("Content-Type: image/png");
header('Content-Length: '.filesize($path));
readfile($path);
https://3v4l.org/tTALQ
use $_GET[];
<?php
$yourParam = $_GET['param_name'];
?>
I can obtain the values of parameters in the image.php file tis way:
<?php
$f = $_GET['f'];
$folder = $_GET['folder'];
$type = $_GET['type'];
$desc = $_GET['desc'];
$dim = $_GET['dim'];
$id = $_GET['id'];
?>
But what must i do for the image:
C:/wamp/1VH/PRU1/images/foods/salads/green_50/23.png
can be showed correctly in the DIV with IMG SRC atribute?

Getting base url of my project

I have an XML file that I use to create a PHP object. I then want to simply print out the image however I am getting the error 'Not allowed to load local resource'.
To get the image URL I have set a variable
$root = ( __DIR__ );
And then append that to the path in my XML file.
$parseXML = simplexml_load_file('chicken.xml');
$img_url = $parseXML->picture;
$imgg = $root . '/' . $img_url;
This now gives me the current path which is
C:\wamp\www\recipesUpdated/images/MarinoWebsite.jpg
If I copy and paste this into my browser it displays the image but won't work when I echo it in an img src.
Is there a way of getting the path just to
\recipesUpdated/images/MarinoWebsite.jpg
Without the C:\wamp etc ?
Thank you!
You get path to image on your local computer, and browser not allowed to load this path.
Url must contain web server address or be relative
Example:
http://localhost/recipesUpdated/images/MarinoWebsite.jpg
or
/recipesUpdated/images/MarinoWebsite.jpg
For your question, try to set variable $root to empty string or your web server address.

FileManager For TinyMCE not getting variable

I am using TinyMCE as a WYSIWYG editor.
It is working perfectly, except for the image upload directory. I want each user to have their own directory in the images directory, but I cannot get it to work.
I am passing the user id in the URL and have tried adding the code to get it from the URL in the config.php file where the directories are defined, but the $user_id value remains empty.
Any assistance would be great.
The URL:
http://mydomain.co.za/index.php?user_id=1
The Code:
<?php
$user_id= htmlspecialchars($_GET["user_id"]);
// The URL that points to the upload folder on your site.
// Can be a relative or full URL (include the protocol and domain)
$imageURL = 'http://mydomain.co.za/images/'.$user_id;
// Full upload system path. Make sure you have write permissions to this folder
$uploadPath = '/home/username/public_html/editor/images/'.$user_id;
//We create the directory if it does not exist - you can remove this if you consider it a security risk
if(!is_dir($uploadPath)) {
mkdir($uploadPath,0755,true);
}
//Create thumb directory if doesn't exist
if(!is_dir($uploadPath . 'thumbnail')) {
mkdir($uploadPath . 'thumbnail',0755,true);
}
//Allowed extenstions
$allowedExtensions = array('jpg','gif','jpeg','bmp','tif','png');
//Maximum upload limit
$sizeLimit = 2 * 1024 * 1024;
function isAuth() {
//Perform your own authorization to make sure user is allowed to upload
return true;
}
Is it possible the reason is because it is not in the main php file?
Or Can I get the variable from the URL?
They suggested on their Instructions that I add $userId = Auth::getId(); but id returns an empty value. Plus I have no idea what that command is executing.
PLEASE NOTE:
the file management is being done by TinyMCE Image Uploader & Manager
UPDATE:
By adding the $actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; echo $actual_link; I noticed by the time the $_GET command is rung the URL has changed to http://mydomain.co.za/tinymce/plugins/lioniteimages/connector/php/gallery.php, but in the browser URL bar, the URL is still the same with the variable.
Is there anyway to access that URL instead of the one i am getting?
I found the solution.
Simple enough, just created a session and the problem was solved.
I was able to get the variable from the session.

Saving Images to folder | PHP

I want to be able to open the provided URL (which is done via a form) that is an URL that will allow the server to save the file into a directory, for example:
http://www.google.co.uk/intl/en_com/images/srpr/logo1w.png
I want to save that logo into this directory:
img/logos/
Then it will add it to the database by giving it a random file name before so, e.g.
827489734.png
It will now be inserted to the database with the following:
img/logos/827489734.png
I do not want to use cURL for this, I like to work with fopen, file_get_contents, etc...
Cheers.
EDIT
$logo = safeInput($_POST['logo']);
if(filter_var($avatar, FILTER_VALIDATE_URL))
{
$get_logo = file_get_contents($logo);
$logo_directory = 'img/logos/';
$save_logo = file_put_contents($logo_directory, $logo);
if($save_logo)
{
$logo_path = $logo_directory . $save_logo;
A part of this code I need helping...
You need to specify a full file name when doing a file_put_contents(). A pure directory name won't cut it.

Categories