I am trying to get images from while loop and split them up at the period (.).. and then change the name of the image to ImageName + -resized. But I can not seem to figure out how to do this. Any help would be greatly appreciated!
So in short I have this: image.jpg and I want to create this image-resized.jpg: Here is my code:
<?php
$f = $_GET['f'];
$h = $_GET['h'];
$gp = $_GET['gp'];
//Create folder path
$path = "Fotos/".$f."/".$h."/".$gp."/";
//Get pictures from database
$getfolders = mysql_query("SELECT FolderName, Files FROM Files WHERE FolderDate = '$f' AND FolderHour = '$h' AND FolderName = '$gp'") or die(mysql_error());
//List pictures from database
while($row = mysql_fetch_array($getfolders)){
$img = $row['Files'];
//Seperate image at period(.)
$image = explode('.', $img);
//Get image name ----------------Here is where I need help!!
for($i = 0; $i < sizeof($image); $i++)
{
$imag = $image[$i];
}
?>
<div class="picture" id="pic"><img src="<?php echo $path; echo $imag ?>" alt="picture" /><?php echo $img?></div>
<?php
}
?>
Well, the simplest solution would be:
$image = explode('.', $img);
$extension = array_pop($image);
$resizedFileName = implode('.', $image) . "-resized.{$extension}";
But this solution does assume, that there are only simple extensions:
image.jpg => image-resized.jpg // ok
image.tar.gz => image.tar-resized.gz // not so ok
But if there are only simple extensions, this solution might be sufficient.
A better solution would be using SplFileInfo:
$fi = new SplFileInfo($image);
$resizedFileName = $fi->getBasename("." . $fi->getExtension()) . "-resized." . $fi->getExtension();
SplFileInfo::getExtensions() is available since PHP 5.3.6
Related
I am trying to upload multiple images to my server, however it is not working. It gives me status code 200 but it doesn't upload images.
This is what I do:
if($request->hasFile('post_image')){
$images = $request->post_image;
$i = 0;
foreach($images as $image){
$i++;
$filename = $post->id.'.'.$i.'jpg';
$location = '/var/www/site/html/'.$post->id;
$image->move($location, $filename);
}
}
If I am removing the foreach() then it uploads image but only one.
Why it is not uploading them? What I am doing wrong?
Edit:
Answering my own question here also. The problem was that my key "post_image" had to be "post_image[]" instead.
You forgot to add . before 'jpg' extension in your filename:
Should be like this:
$filename = $post->id.'.'.$i.'.jpg';
I am trying this way upload multiple images:
if(!empty(Input::file('image'))){
$files= Input::file('image');
$destinationPath= 'images';
$images=array();
foreach($files as $file){
$fullname= $file->getClientOriginalName();
$hashname = $fullname;
$upload_success =$file->move($destinationPath, $hashname);
$images[]=$fullname;
$has= implode(",",$images);
}
$categories = new CategoryType;
$categories->name = Input::get('name');
$categories->image_attachment = $has;
$categories->save();
}
Follow this awnser you can loop on the all uploaded files
Get all files in a foreach loop in Laravel
like $images = Input::file('post_image');
The problem was that my key "post_image" had to be "post_image[]" instead.
$file_ary = array();
$file_count = count($request->file('image') );
$a=($request->file('image'));
$finalArray=array();
for ($i=0; $i<$file_count; $i++) {
$fileName = time().$a[$i]->getClientOriginalName();
$destinationPath = $request->input('path') ;
$finalArray[$i]['image']=$destinationPath.$fileName;
$a[$i]->move($destinationPath,$fileName);
}
return json_encode($finalArray);
I just wanna ask if someone can explain to me why I cant display my images to the website that I'm creating. I stored the 'path/filename' in one of the columns in the database. While the image image is stored in the server.
<?php foreach $data as $val{?>
<img src="<?php echo base_url();?><?php echo $val->file;?>">
<?php }?>
Controller
$path = $_FILES["addFile"]["name"];
$extension = pathinfo($path, PATHINFO_EXTENSION);
$file_sc = 'uploads/screenshots/'.date("Ymdhms.").$extension;
$new_name = date("Ymdhms").".".$extension;
$target_dir = "./uploads/screenshots/";
$target_file = $target_dir.$new_name;
$type = $_FILES["addFile"]["type"];
$allowed = array('image/jpeg', 'image/png', 'image/gif');
if($_FILES["addFile"]["name"]){
if(!in_array($type,$allowed)){
echo 'File type is not allowed.';
} else {
move_uploaded_file($_FILES["addFile"]["tmp_name"],$target_file);
$this->MyModel->add($file_sc);
}
Model
function add_kudos($file_sc)
{
$query = $this->db->query("insert into tbl_kudos(file) values('$file_sc');
}
This is how it looks like in the database -> 'uploads/screenshots/20170224040231.jpg'
The file name in the server ->20170224040231.jpg
The image is not showing. Even if my url is correct.
Can someone explain to me why it's like this? I am new to this.
create a php file like this named showimg.php:
<?php
$img = $_REQUEST['img'];
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime=finfo_file($finfo, $img) ;
finfo_close($finfo);
header("Content-type: $mime");
$fp = fopen($img, 'rb');
fpassthru($fp);
?>
use your code to get the path of the image that you want to show from the DB in a var named $myimgpath and then use something like this:
<img src="<?php echo base_url()."showimg.php?img=".$myimgpath;?>">
First filename is different to second filename!
You can use urlencode() then print your image URL
Try this
<?php foreach ( $data as $val ) { ?>
<img src="<?php echo base_url( $val->file ); ?>">
<?php } ?>
I have a system that allows user to upload PDF files and save the name of the file on the database.
How can I make this script works so user can delete all files from server whose name is not in my database?
This is what I actually have, but the script deletes all files. I don't know how to proceed.
<?php
include 'fimg.class.php';
require('../../../php/cone.php');
//header('Location: ../produccion.php');
$directory = "upload/";
//get all image files with a .jpg extension.
$images = glob($directory . "*");
foreach($images as $image)
{
$name = explode('_',$image);
$name = 'photos/' . $name[0];
$sql = mysql_query("SELECT imagen FROM r_alumnos");
if(mysql_num_rows($sql) == 0)
unlink($image);
}
?>
You could create something like a maintenance-script which handels this.
First, load everything in an array (I personally don't like the multiple queries execute):
$database_files = array();
$result_db_files = mysqli_query("SELECT imagen FROM r_alumnos");
while ($row = $result_db_files->fetch_assoc())
{
$database_files[] = $row['imagen'];
}
Then check each file:
$images = glob($directory . "*");
foreach($images as $image)
{
$name = explode('_',$image);
$name = 'photos/' . $name[0];
if (!in_array($name, $database_files))
{
unlink($image);
}
}
I am creating a web service using php and json to upload multiple images
to move in the folder and in database, I am able to upload one image using this code
$image_binary=base64_decode($real_img);
$image_file = fopen("images/real/".time().$real_img.$id.'.jpg', 'wb');
fwrite($image_file, $image_binary);
$image_path = "".$id.'.jpg';
move_uploaded_file(fwrite($image_file, $image_binary), $image_path);
How can I use this code for multiple images if I get the multiple images in array.
Loop it:
(untested)
$images = array(0 => 'img1....jpg',
1 => 'img2....jpg');
uploadImages($images);
function uploadImages($images) {
for($i = 0; count($images) > $i; $i++) {
$image = $images[$i];
$image_binary=base64_decode($image);
$image_file = fopen("images/real/".time().$image.$id.'.jpg', 'wb');
fwrite($image_file, $image_binary);
$image_path = "".$id.'.jpg';
move_uploaded_file(fwrite($image_file, $image_binary), $image_path);
}
}
I have a string that contains text and photos as you can see bellow.
My code so far get all the images and upload them into a folder.
I need to replace the new uploaded links with the correct oreder.
$nextstep = "Hello there this is image 1 <img src='http://www.demosite.com/wp-content/uploads/2015/01.jpg' width='653' height='340' alt='xxx' title='xxx'> !! And Now you can see image number 2 <img src='http://www.demosite.com/wp-content/uploads/2015/02.jpg' width='653' height='340' alt='xxx' title='xxx'>";
$string = $nextstep;
$doc = new DOMDocument();
$doc->loadHTML($string);
$images = $doc->getElementsByTagName('img');
foreach ($images as $image) { //STARTING LOOP
echo "</br>";
echo $image->getAttribute('src') . "\n";
echo "</br>";
$urlimg = $image->getAttribute('src'); //IMAGE URL
$URL = urldecode($urlimg);
$image_name = (stristr($URL,'?',true))?stristr($URL,'?',true):$URL;
$pos = strrpos($image_name,'/');
$image_name = substr($image_name,$pos+1);
$extension = stristr($image_name,'.');
if($extension == '.jpg' || $extension == '.png' || $extension == '.gif' || $extension == '.jpeg'){
$img = '../images/' . $image_name;
file_put_contents($img, file_get_contents($url)); //UPLOAD THEM ONE BY ONE
}
}
It's not clear what the desired outcome is here. It sounds like you want to change the src URL in your existing string to the one where you've saved the images. If this isn't the case please do try updating the question for more clarity.
Here's a simple way to break down the problem...
Step 1 - Extract the img tags from DOM using source string
$html = <<<'HTML'
Hello there this is image 1 <img src="http://www.demosite.com/wp-content/uploads/2015/01.jpg" width="653" height="340" alt="xxx" title="xxx"> !!
And Now you can see image number 2 <img src="http://www.demosite.com/wp-content/uploads/2015/02.jpg" width="653" height="340" alt="xxx" title="xxx">
HTML;
$dom = new DOMDocument;
$dom->loadHTML($html);
$imgs = $dom->getElementsByTagName('img');
// Store the list of image urls in an array - this will come in handy later
$imgURLs = [];
foreach($imgs as $img) {
if (!$img->hasAttribute('src')) {
continue;
}
$imgURLs[] = $img->getAttribute('src');
}
Step 2 - Save the image in a different location
$newImgURLs = []; // new modified URLs where images were moved
$newPath = '../images'; // wherever you're saving the images
foreach($imgURLs as $imgURL) {
/**
* Use parse_url and pathinfo to break down the URL parts and extract the
* filename/extension instead of the fragile implementation you used above
*/
$URLparts = parse_url($imgURL);
$file = pathinfo($URLparts['path']);
$fileName = $file['filename'] . '.' . $file['extension'];
$newFileName = $newPath . '/' . $fileName;
$newImgURLs[] = $URLparts['scheme'] . '://' .
$URLparts['host'] . $file['dirname'] . '/' . $newFileName .
(isset($URLparts['query']) ? ('?' . $URLparts['query']) : null) .
(isset($URLparts['fragment']) ? ('#' . $URLparts['fragment']) : null);
// download image and save to new location
file_put_contents($newFileName, file_get_contents($imgURL));
}
Step 3 - Modify the img src URLs to new path
foreach($imgs as $i => $img) {
$img->setAttribute('src', $newImgURLs[$i]);
}
echo $dom->saveHTML(); // new updated DOM
// or just create a new $html string from scratch using the new URLs.