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?
Related
I'm using summernote as the text editor in a backend. The text and images stored must then be displayed in the pages of the frontend.
The editor and the upload images works, but the problem is to recover the images in the frontend because of the path.
I need to use the absolute path in the img-upload.php file but it doesn't seem to accept it.
img-upload.php
if(empty($_FILES['file']))
{
exit();
}
$errorImgFile = "./img/img_upload_error.jpg";
$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = round(microtime(true)) . '.' . end($temp);
$destinationFilePath = '../../images/img-uploads/'.$newfilename ;
if(!move_uploaded_file($_FILES['file']['tmp_name'], $destinationFilePath)){
echo $errorImgFile;
}
else{
echo $destinationFilePath;
}
with the relative path works:
$destinationFilePath = '../../images/img-uploads/'.$newfilename ;
but in this way not:
$path = 'http://localhost/sites/my-site/';
$destinationFilePath = $path.'images/img-uploads/'.$newfilename ;
I don't see any error.
Thanks
You have probably figured it out by now...
It seems Summernote does not render images from absolute paths, but the closest you can get is to specify the file from the root path, like:
$path = '/sites/my-site/';
$destinationFilePath = $path.'images/img-uploads/'.$newfilename ;
Results in something like: '/sites/my-site/images/img-uploads/filename.jpg'
If you save this to your database, you can render your images anywhere on your site using this rooth path address for the files.
I suggest you to use Ckfinder or Fileman with Ckeditor. I made a repository for that. Go check it out.
https://github.com/senocak/Laravel-CKEDITOR-CKFINDER-usage
I have a piece of code to upload a picture and save it in a folder and the path in a databaseand show it on the webpage. Funny enough, upon uploading the picture for the first time, the image will show on the webpage and with change when I upload a new picture. But when I close the page, reopen it another day and decide to change the picture, the one of the webpage won't change even if i refresh the page but the one in the folder will change.
Here's my code
<?php
$sql2 = "SELECT Picture_HD FROM detailss WHERE Idn_nom = '$Indnum'";
require('connect.php');
$addr = "";
$addr = mysqli_query($conn, $sql2);
if ($addr) {
$locat = $addr->fetch_row();
$locat = (string)$locat[0];
} else {
$locat = "Pictures/default1.png";
}
mysqli_close($conn);
echo "<div id = 'Img'>";
echo "<img src = '" . $locat . "' alt = 'Passport picture/Headshot' style = 'width:80px; height:80px;'/>";
echo "</div>";
?>
Your browser is caching the image.
If you want to prevent the browser to cache the image just add a random parameter at the end of the url.
echo "<img src = '" . $locat . "?t=" . time() . "' alt = 'Passport picture/Headshot' style = 'width:80px; height:80px;'/>";
If your image is changing in your folder but you are seeing the old one on the webpage it's likely a caching issue, clear your browser cache (ctrl+f5 plus this is kinda broken so doesn't always work - so best to go into browser settings to do it, or open a private window after ctrl+f5) and if not the clear server level cache.
The best way to do this is to delete the existing image right before uploading the new one with the same file name
// define variables used for file name from session variable username the directory and extension by exploding the file name from the post method from a form with a metadata type
//set new file name to username from session variable
$filename = $_SESSION['username']
// set directory of files
$dir = "img/";
// set extension variable to file extension after posted from form
$ext=strtolower(end(explode('.',$_FILES['importimg']['name'])));
// new file upload name with existing extension
$upload_file = $dir . $filename . "." . $ext;
// delete file
// find all files with the same name any extension using variable defined above etc .txt, .php, .gif, .jpg, etc. then delete it
foreach (glob("img/$filename.*") as $deletefile) {
// unlink is used to delete the file and delete the cache of the file
unlink($deletefile);
}
// upload image
// upload file with type posted from metadata in form and upload it as your new file name using upload_file variable
if (move_uploaded_file($_FILES['importimg']['tmp_name'], $upload_file)) {
// successful upload of file add code for msg or sql query etc name to users table and redirect to profile page
echo "Successfully uploaded your file.";
} else {
// upload error show message
echo "There was an error uploading your file.";
}
Enjoy
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
Hello my PHP script i have set up uploads files via a html form.
I'm hoping to show a download link / open file link after the upload but the problem is a section of the PHP script I'm using renames the file on upload
//Create full filename including path
if ($random_name_enable = true) {
// Generate random filename
$tmp = str_replace(array('.', ' '), array('', ''), microtime());
if (!$tmp || $tmp == '') {
$out['error'][] = "File must have a name";
}
$newname = $tmp . '.' . $ext;
} else {
$newname = $name . '.' . $ext;
}
enter code here
This results in me not knowing how show a download link with the renamed uploaded file via the php solution below
The upload webpage / site is located at https://beta.filez.ml
as you can see if you try to upload a basic image is does not show the renamed download link, I need to figure out a way to get the PHP script to show a link after the rename of the upload shown below.
The Full PHP file is here for anyone interested in picking it apart
https://gist.github.com/burnsyboo/b9a9512807fc031dc9a7
Why not use Ajax? when upload is done, echo new file name that you generated, ajax takes that name and then append anchor with href with file name that you got from php and add download attribute to anchor so it downloads file when pressed
http://www.w3schools.com/tags/att_a_download.asp
Solution was to just above the $newname variable add global $newname; then at the top of the page i did $newname "";
Then where the success message was displayed i did this
$message = "<style>.php-success { color: darkgreen; font-weight: 400; font-size: 20px; }</style><p class='php-success'>File successfully Uploaded<br><br>Click here to open</p>";
I need to pull all images from a URL directory (they are not displayed...just sitting in a folder on a server that I do not have access to) and display them within a Bootstrap Image gallery.
http://www.electrictoolbox.com/extract-images-web-page-php/
<?php
require_once('./simple_html_dom.php');
require_once('./url_to_absolute.php');
$url = 'http://www.bbc.co.uk';
$html = file_get_html($url);
foreach($html->find('img') as $element) {
echo url_to_absolute($url, $element->src), "\n";
}
?>
The URL for the folder where all the images are stored is:
http://masterplan.imgix.net/Slimming_Book/
Is it possible for php to scan this URL directory and pull the images to another website that is being hosted on another server?
Bit late but I figured I'd answer this. The below PHP code loads all ".png" images from the directory and then echos the image tag. You would replace the plain html tag for the equivalent bootstrap one.
dirname = "media/images/cats/";
$images = glob($dirname."*.png");
foreach($images as $image) {
echo '<img src="'.$image.'" /><br />';
}