Yii2: Error Not allowed to load local resource - php

Im trying to display images from backend of my app
<?php foreach ($img as $key=>$row): ?>
<div class="products_inside_wrapper intro_wrapper">
<div class="classes_inside_item bordered_wht_border">
<?php
foreach (explode(';',rtrim($row['images'],';')) as $key_img => $value_img)
{
?>
<?php echo Html::img('#backend/web'.'/'.$value_img);?>
<?php
}
?>
</div>
</div>
<?php endforeach; ?>
Tried with above code to display all images, but getting error Not allowed to load local resource when I open Google Chrome Inspect Element

i think you are using a local url instead of using this
<?php echo Html::img('#backend/web'.'/'.$value_img);?>
try using it like
<?= Html::img(Yii::getAlias('#web').'/images/'.$value_img]);?>

As stig-js answered you can't load local saved image directly, If you're really interested into loading resources from a local path, you can open image as a binary file with fopen and echo the content of it with a proper header to output. In general way, you can add a method to your model like this:
public function getImage($imageName)
{
$imagePath = '#backend/web' . '/' . $imageName;
$fileInfo = finfo_open(FILEINFO_MIME_TYPE);
$contentType = finfo_file($fileInfo, $imagePath);
finfo_close($fileInfo);
$fp = fopen($imagePath, 'r');
header("Content-Type: " . $contentType);
header("Content-Length: " . filesize($imagePath));
ob_end_clean();
fpassthru($fp);
}
P.S: Also you can use combination of this answer with showing image as base64 on HTML. See How to display Base64 images in HTML?

Images must be accesible by an url, like
yoursite.com/backend/imagedir/IMG'
If yoursite.com/backend points to your backend/web folder.
Backend alias points to your local path, so you need a custom alias to reach image folders.
Yii2 aliases: http://www.yiiframework.com/doc-2.0/guide-concept-aliases.html

Related

Calling external php function in <img>

I've created an external php file (sort.php) that sorts the files in a folder on the server by time modified, and returns the most recent file.
<?php
function scanDir ($dir){
$fileTimeArray = array();
// Scan directory and get each file date
foreach (scandir($dir) as $fileTime){
$fileTimeArray[$fileTime] = filemtime($dir . '/' . $fileTime);
}
//Sort file times
var $latestFile = arsort($fileTimeArray);
return($latestFile[0]);
}
?>
I'm attempting to call this function inside of , in another php file, and set the src:
<img <?php echo 'src="'.scanDir("issues/preview").'"';?>/>
I've included sort.php at the top of the page in question.
The image src reads "(unknown)". What am I missing or doing wrong or both?
Thank you!
I would write
<?php $x = scanDir("issues/preview"); ?>
<img src="<?php echo $x; ?>"/>

Download using Yii::app()->request->SendFile returns corrupted file

I've been trying to download my uploaded file from a specific directory like this:
Yii::app()->request->SendFile($model->statement,
file_get_contents($path.$model->statement)
);
It recognizes the file and downloaded it with the correct name and format, but all I get instead of a 74KB file, is a 1KB corrupted file. Tried other documents such as .doc, .pdf, still the same.
I am not entirely sure about what the file_get_contents actually does as I took this from an example I found.
The file to be downloaded was previously uploaded using
<div class="row">
<?php echo $form->labelEx($model, 'statement'); ?>
<?php echo $form->fileField($model, 'statement', array('size' => 36, 'maxlength' => 255)); ?>
<?php echo $form->error($model, 'statement'); ?>
</div>
in the _form.php and adjusted the actionCreate in the controller:
public function actionCreate($id)
{
$model=new Witness;
$model->ip_id = $id;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
$path = Yii::app()->basePath . '/modules/iris/statements';
if (!is_dir($path)) {
mkdir($path);
}
if(isset($_POST['Witness']))
{
$model->attributes=$_POST['Witness'];
if (#!empty($_FILES['Witness']['name']['statement'])) {
$model->statement = $_POST['Witness']['statement'];
if ($model->validate(array('statement'))) {
$model->statement = CUploadedFile::getInstance($model, 'statement');
} else {
$model->statement = '';
}
$model->statement->saveAs($path . '/' . time() . '_' . str_replace(' ', '_', strtolower($model->statement)));
//$model->doc_type = $model->statement->getType();
//$model->doc_size = $model->statement->getSize();
}
$model->statement = time() . '_' . str_replace(' ', '_', strtolower($model->statement));
if($model->save())
$this->redirect(array('ip/view','id'=>$model->ip_id));
}
$this->render('create',array(
'model'=>$model,
));
}
The uploaded files can be opened with no problem. Any idea of why the download corrupted? Do I have to specify the type/size of the file first before downloading?
With a 1kb file it sounds like your server is throwing a php error after the headers have been set.
Open the downloaded file with text editor and check the contents.
I have found another solution instead of using the SendFile function. Put this in the view file to generate the download link:
CHtml::link('Click to download file', array('ip/download&id='.$model->file_id));
where 'ip' the the model name. This will pass file_id to the function actionDownload created in the controller.php:
public function downloadFile($fullpath){
if(!empty($fullpath)){
header("Content-type:application/pdf"); //for pdf file
//header('Content-Type:text/plain; charset=ISO-8859-15');
//if you want to read text file using text/plain header
header('Content-Disposition: attachment; filename="'.basename($fullpath).'"');
header('Content-Length: ' . filesize($fullpath));
readfile($fullpath);
Yii::app()->end();
}
}
public function actionDownload($id){
$model=Ip::model()->findByPk($id);
$path = Yii::app()->basePath . 'location of file to be downloaded'.$model->filename;
$this->downloadFile($path);
}
This should download the file completely. Don't worry about the content-type, I have tried all common file types (.pdf, .doc, .ppt, .png, .jpg), all works perfectly.
In Yii2, a sendFile() signature is
public $this sendFile ( $filePath, $attachmentName = null, $options = [] )
Sending a file:
Yii::$app->response->sendFile('test.zip');
For those, who get full files, but still corrupted:
You should check if other php files are printing output, sometimes whitespace after closing PHP tags can cause problems.
From here
If you take a look into the arguments list of sendFile, you can see that 3rd parameter is mimeType. In fact, you do not present a HTTP headers response, so my prima vista suggestion to you is to try explicitly specify the Content-Type response header:
Yii::app()->request->sendFile(
"Youfile.pdf",
file_get_contents('path/to/file'),
'application/pdf'
);

Display the uploaded image after uploading on the web page

I am trying to display the image that i have uploaded and moved to the desired location. Here is the code below.
if(isset($_FILES['image']))
// image upload from upload.html
{
session_start();
$_SESSION['str'];
$_SESSION['img'];
$image = basename($_FILES["image"]["name"]);
move_uploaded_file($_FILES['image']['tmp_name'], $_SESSION['str'].'_5'.$_SESSION['img']);
//I am trying to display the uploaded pic
echo '<img src= "$image"/>';
}
The image is stored at the location $_SESSION['str']. How can i display this uploaded image.
You're using the wrong path to show the image. You're using the orginal name of the image $_FILES["image"]["name"] that was uploaded and then you use the move_uploaded_file function to move and save the file as $_SESSION['str'].'_5'.$_SESSION['img'] so that doesn't match (can't see how your session variables are created).
Also, is the location where you save the uploaded file to accessable by the client side? Move the file in the public area of your web application.
Update
I now understand from your comment that you want to save the file in a private location and then show that file in a <img> element in some HTML template.
I changed the example code to embed the uploaded image into the HTML with base64.
You can use this function for creating the embed code. I took it from the answer from this question How to embed images...
function dataUri($file, $mime)
{
$contents = file_get_contents($file);
$base64 = base64_encode($contents);
return 'data:' . $mime . ';base64,' . $base64;
}
So then you can use it like:
session_start();
// absolute path including the path to the public folder
$image_dest_path = './public/img/' . $_SESSION['str'] . '_5' . $_SESSION['img'];
// move file to server location
move_uploaded_file($_FILES['image']['tmp_name'], $image_dest_path);
// imbed the image into the HTML.
echo '<img src= "' . dataUri($image_dest_path, 'image/jpg') . '"/>';
First of you say the location is stored in $_SESSION['str'] but you try to place an image with the value of basename($_FILES["image"][""name]).
Second; you should be using session_start() at the top of your page.
Third; in order to use a variable in a string, you need to use double quotes (") in stead of single quotes ('). Like so:
echo "<img src='$_SESSION['str']">;
But I'd use this:
echo '<img src="'. $_SESSION['str'] .'" >';
Also, are you sure you're not getting any errors? If you don't see any try placing this at the top of your file:
error_reporting(E_ALL);
ini_set('display_errors', 1);
iam assuming that $_SESSION['str'] session variable is the path till the folder where the image is stored
Use the below code, give the complete url of the image:
echo "<img src = '".$_SESSION['str'].DIRECTORY_SEPARATOR.$image."'"." />";
how to call the node js method in angular js?

Displaying an image resource with PHP

I am trying to simply get a test image, crop it a bit, and display it. The thing is, I am doing this from PHP, and every attempt I have made thus far has frustrated me even more; /* and the internet is telling me to do things that I have already done. */
OK, so what have you done??
I have tried various ways of getting the $image itself. I have tried the following:
Using imagecreatefromstring($url); /* where $url is the location of the image (I am pulling from random sites, which is a necessity for my project */
Using imagecreatefromstring(file_get_contents($url)); and then, in a <div> tag, echoing the image
Using imagecreatefromstring(file_get_contents($url)); and then, in an <img> tag, echoing the image
Doing 3., except using imagejpeg($image)
Doing 4., except, this time, putting header('Content-Type: image/jpeg');
OK, what happened?
First attempt returned a nice error saying that $image was not recognized.
Second attempt seems to work, but instead of an image, I get back the following text: Resource id #5
Third attempt gives me a bunch of gibberish.
Fourth attempt also gave me a bunch of gibberish.
Fifth attempt gave me a black screen with this error message: The image “http://localhost/ResearchProject/sampleImageDisplay.php” cannot be displayed because it contains errors.
Here is the final code (and header.php just contains all of the necessary HTML tags to display the web page (the DOCTYPE tag, the html tag, the meta tag...) ):
<?php
include "header.php";
$url = "http://byebyedoctor.com/wp-content/uploads/2010/12/alopecia-areata-3.jpg";
$image = imagecreatefromstring(file_get_contents($url));
?>
<img>
<?php header('Content-Type: image/jpeg'); imagejpeg($image); ?>
</img>
<?php imagedestroy($image); ?>
</body>
</html>
Why can't I display this simple image??
This code worked for me. Just create empty php file and paste this code. It should return the photo of a semi-bold man.
$url = "http://byebyedoctor.com/wp-content/uploads/2010/12/alopecia-areata-3.jpg";
$im = imagecreatefromstring(file_get_contents($url));
if ($im !== false) {
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
}
else {
echo 'An error occurred.';
}
First off...
You have to make sure that "allow_url_fopen" is enabled in php.ini.
If you have access to this file just change
;allow_url_fopen
To
allow_url_fopen
Some hosts disable access to php.ini though.
Then all you have to do is this....
$url = "http://byebyedoctor.com/wp-content/uploads/2010/12/alopecia-areata-3.jpg";
$image = file_get_contents($url);
Then you can store it temporarily to resize it or whatever...
//Store in the filesystem.
$fp = fopen("/location/to/save/tempimage.jpg", "w");
fwrite($fp, $image);
fclose($fp);
Your major planning problem is: You try to include you image into a html code.
For this you need 2 phps:
A php file what contains your html-code with an img-tag (src must be the second php-file)
A php file what reads you base image and outputs the BINARY image data
your_htmlpage.php
<html>
<?php
include "header.php";
?>
<body>
<img src="your_image.php">
</body>
</html>
your_image.php
<?php
$url = "http://byebyedoctor.com/wp-content/uploads/2010/12/alopecia-areata-3.jpg";
$image = imagecreatefromstring(file_get_contents($url));
if($image !== false) {
header('Content-Type: image/jpeg');
imagejpeg($image);
imagedestroy($image);
} else {
header("X-Error", true, 404);
echo "Error loading remote image";
}
?>
Another option would be to send the image as base64encoded String to the browser. But this means that the WHOLE image-data is part of the html-code.
e.g. lik this:
<html>
<?php
include "header.php";
$url = "http://byebyedoctor.com/wp-content/uploads/2010/12/alopecia-areata-3.jpg";
$image = imagecreatefromstring(file_get_contents($url));
if($image !== false) {
// start buffering and catch image output
ob_start();
imagejpg($image);
$contents = ob_get_contents();
ob_end_clean();
imagedestroy($image);
$img_data = "data:image/jpg;base64,".base64_encode($contents);
} else {
$img_data = "";
}
?>
<body>
<img src="<?php echo $img_data; ?>">
</body>
</html>

Display image via local path - file:\\\c:\ using PHP

I want to load image via c:/user_name/image/image_name.jpg using http://intranet/user/index.php.
<img src="file:///c:/user_name/image/image_name.jpg">
How do I display them?
Thanks
Jean
You realize this would only work if that image is in the exact same location on every machine which will be viewing this page? Is there any reason you can't serve up the image normally, via the web server itself?
Since you're using an absolute Windows path, this would only work on Windows machines, which actually have a C drive, the same directories, etc... It won't work at all on a Mac or Linux or whatever else box, since they don't bother with drive letters.
followup:
after pondering your question a bit, it looks like you want to serve up a specific image that's not stored in your document root and serve it from a specific page. If you put something like this at the start of your index.php:
<?php
if (isset($_GET['username']) && isset($_GET['image'])) {
$user = $_GET['username'];
$image = $_GET['image'];
$path = "C:\\{$user}\\image\\{$image}";
if (is_readable($path)) {
$info = getimagesize($path);
if ($info !== FALSE) {
header("Content-type: {$info['mime']}");
readfile($path);
exit();
}
}
}
?>
and within the HTML:
<img src="index.php?user=user_name&image=image_name" />
Of course, this is very basic, and serving up files this way is highly insecure, but most likely this is the basics of what you wanted.
<?php
$path = "C:\\xampp\\htdocs\\Create.jpg";
if (is_readable($path))
{
$info = getimagesize($path);
if ($info !== FALSE)
{
header("Content-type: {$info['mime']}");
readfile($path);
echo '<img src="data:image/jpeg;base64,'. base64_encode($path) .'" height="100" width="100"/>';
}
}
?>

Categories