PHP change variable into jpeg file - php

I have the following code to get the album cover of an mp3 using getid3, the problem is though, how do I copy this image and put it into a specified directory?
<?php
require_once('getid3/getid3.php');
$file = "path/to/mp3/file.mp3";
$getID3 = new getID3;
$getID3->option_tag_id3v2 = true;
$getID3->option_tags_images = true;
$getID3->analyze($file);
if (isset($getID3->info['id3v2']['APIC'][0]['data'])) {
$cover = $getID3->info['id3v2']['APIC'][0]['data'];
} elseif (isset($getID3->info['id3v2']['PIC'][0]['data'])) {
$cover = $getID3->info['id3v2']['PIC'][0]['data'];
} else {
$cover = "no_cover";
}
if (isset($getID3->info['id3v2']['APIC'][0]['image_mime'])) {
$mimetype = $getID3->info['id3v2']['APIC'][0]['image_mime'];
} else {
$mimetype = 'image/jpeg';
}
if (!is_null($cover)) {
// Send file
header("Content-Type: " . $mimetype);
if (isset($getID3->info['id3v2']['APIC'][0]['image_bytes'])) {
header("Content-Length: " . $getID3->info['id3v2']['APIC'][0]['image_bytes']);
}
echo ($cover);
?>
Is this possible, if yes how? Thanks for any help :)

have you tried:
file_put_contents('<filename>', $getID3->info['id3v2']['APIC'][0]['image_bytes']);

Related

Saving Multiple File path to mysql using PHP

Good Day. I have a php script that move multiple file in my directory..
$filepath = 'uploads/';
if (isset($_FILES['file'])) {
$file_id = $_POST['file_id'];
$count = 0;
foreach($_FILES['file']['tmp_name'] as $k => $tmp_name){
$name = $_FILES['file']['name'][$k];
$size = $_FILES['file']['size'][$k];
if (strlen($name)) {
$extension = substr($name, strrpos($name, '.')+1);
if (in_array(strtolower($extension), $file_formats)) { // check it if it's a valid format or not
if ($size < (2048 * 1024)) { // check it if it's bigger than 2 mb or no
$filename = uniqid()."-00000-". $name;=
$tmp = $_FILES['file']['tmp_name'][$k];
if (move_uploaded_file($tmp_name, $filepath . $filename)) {
$id = $file_id;
$file_path_array = array();
$files_path = $filepath . $filename;
$file_extension = $extension;
foreach($file_name as $k_file_path => $v_file_path){
$file_path_array[] = $v_file_path;
}
foreach($file_extension as $k_file_extension){
$file_extension_array[] = $v_file_extension;
}
$file_path = json_encode($files_path);
$file_name = str_replace("\/", "/",$file_path);
var_dump($file_name);
$update = $mysqli->query("UPDATE detail SET file_path='$file_name' WHERE id='$id'");
} else {
echo "Could not move the file.";
}
} else {
echo "Your file is more than 2MB.";
}
} else {
echo "Invalid file format PLEASE CHECK YOU FILE EXTENSION.";
}
} else {
echo "Please select FILE";
}
}
exit();
}
this is my php script that move file to 'uploads/' directory and i want to save the path to my database. i try to dump the $file_name and this is my example path how to save that to my database.. ? any suggestions ?
NOTE: i already move the file to uploads/ directory and i only want to save the path to my database
string(46) "uploads/5638067602b48-00000-samplePDF.pdf"
string(46) "uploads/5638067602dee-00000-samplePDF1.pdf"
string(46) "uploads/5638067602f8d-00000-samplePDF2.pdf"
if you must store them in one field..
inside the loop
$file_name_for_db[]=$file_name;
outside the loop:
$update = $mysqli->query("UPDATE detail SET file_path='".json_encode($file_name_for_db)."' WHERE id='$id'");
there is serialize() instead of json_encode() if you prefer

create and download zip file using php

i am trying to create a zip file(using php) for this i have written the following code:
$fileName = "1.docx,2.docx";
$fileNames = explode(',', $fileName);
$zipName = 'download_resume.zip';
$resumePath = asset_url() . "uploads/resume/";
//http://localhost/mywebsite/public/uploads/resume/
$zip = new ZipArchive();
if ($zip->open($zipName, ZIPARCHIVE::CREATE) !== TRUE) {
echo json_encode("Cannot Open");
}
foreach ($fileNames as $files) {
$zip->addFile($resumePath . $files, $files);
}
$zip->close();
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=".$zipName."");
header("Content-length: " . filesize($zipName));
header("Pragma: no-cache");
header("Expires: 0");
readfile($zipName);
exit;
however on a button click i am not getting anything..not even any error or message..
any help or suggestion would be a great help for me.. thanks in advance
Why not use the Zip Encoding Class in Codeigniter - it will do this for you
$name = 'mydata1.txt';
$data = 'A Data String!';
$this->zip->add_data($name, $data);
// Write the zip file to a folder on your server. Name it "my_backup.zip"
$this->zip->archive('/path/to/directory/my_backup.zip');
// Download the file to your desktop. Name it "my_backup.zip"
$this->zip->download('my_backup.zip');
https://www.codeigniter.com/user_guide/libraries/zip.html
... it work for me
public function downloadall(){
$createdzipname = 'myzipfilename';
$this->load->library('zip');
$this->load->helper('download');
$cours_id = $this->input->post('todownloadall');
$files = $this->model_travaux->getByID($cours_id);
// create new folder
$this->zip->add_dir('zipfolder');
foreach ($files as $file) {
$paths = 'http://localhost/uploads/'.$file->file_name.'.docx';
// add data own data into the folder created
$this->zip->add_data('zipfolder/'.$paths,file_get_contents($paths));
}
$this->zip->download($createdzipname.'.zip');
}
What is asset_url() function? Try to use APPPATH constant istead this function:
$resumePath = APPPATH."../uploads/resume/";
Add "exists" validation for file names:
foreach ($fileNames as $files) {
if (is_file($resumePath . $files)) {
$zip->addFile($resumePath . $files, $files);
}
}
Add exit() after:
echo json_encode("Cannot Open");
Also I think it's the better desision to use CI zip library User Guide. Simple example:
public function generate_zip($files = array(), $path)
{
if (empty($files)) {
throw new Exception('Archive should\'t be empty');
}
$this->load->library('zip');
foreach ($files as $file) {
$this->zip->read_file($file);
}
$this->zip->archive($path);
}
public function download_zip($path)
{
if (!file_exists($path)) {
throw new Exception('Archive doesn\'t exists');
}
$this->load->library('zip');
$this->zip->download($path);
}
Below scripting working ok in my local system. 1st remove asset_url() from $resumePath and set zip file store location relative path.
- Pass zip file name with its location path to $zip->open()
$fileName = "1.docx,2.docx";
$fileNames = explode(',', $fileName);
$zipName = 'download_resume.zip';
$resumePath = "resume/";
$zip = new ZipArchive();
if ($zip->open($resumePath.$zipName, ZIPARCHIVE::CREATE) !== TRUE) {
echo json_encode("Cannot Open");
}
foreach ($fileNames as $files) {
$zip->addFile($files, $files);
}
$zip->close();
/* create zip folder */
public function zip(){
$getImage = $this->cart_model->getImage();
$zip = new ZipArchive;
$auto = rand();
$file = date("dmYhis",strtotime("Y:m:d H:i:s")).$auto.'.zip';
if ($zip->open('./download/'.$file, ZipArchive::CREATE)) {
foreach($getImage as $getImages){
$zip->addFile('./assets/upload/photos/'.$getImages->image, $getImages->image);
}
$zip->close();
$downloadFile = $file;
$download = Header("Location:http://localhost/projectname/download/".$downloadFile);
}
}
model------
/* get add to cart image */
public function getImage(){
$user_id = $this->session->userdata('user_id');
$this->db->select('tbl_cart.photo_id, tbl_album_image.image as image');
$this->db->from('tbl_cart');
$this->db->join('tbl_album_image', 'tbl_album_image.id = tbl_cart.photo_id', 'LEFT');
$this->db->where('user_id', $user_id);
return $this->db->get()->result();
}

How to display image on codeigniter that is stored in oracle database as BLOB type?

I am trying to display an image that is stored in oracle DB as BLOB data-type. this is my MODEL code
function viewblobData() {
$user = $this->session->userdata('user_logged_in');
$returnLobValue = '';
if (!empty($user)) {
$conn = $this->db->conn_id;
$sql = "SELECT * FROM OP_REG_IMAGE WHERE REG_NO = '$user'";
$stmt = oci_parse($conn, $sql);
oci_execute($stmt)
or die("Unable to execute query<br/>");
while ($row = oci_fetch_assoc($stmt)) {
$returnLobValue = $row['PAT_IMAGE']->load();
header("Content-type: image/jpg");
}
}
return $returnLobValue;
}
and this is for display at view
<?php echo $this->MY_MODEL->viewblobData(); ?>
But its shows "the image http://localhost/..... cannot be displayed because it contains errors"
if I remove the line header("Content-type: image/jpg"); then it shows like below whole page:
�M�t9UYG�G��d���~��5 �V�W��jժ�I�P��l6;��Po�ߖ�]��o�_���v��]o7{���Xr?_� ��bp��F3�s>ߙ�K)��f_�w��9����Z#���i�:�V�Y�h�=�����o���{��px=����o��fk���:>����~u�=��w��~9������y�]^����ٹ_���
Can anyone help?
You can use the image libraries:- e.g
$img = imagecreatefromstring($row['PAT_IMAGE']);
if ($img !== false) {
$image_new_name = 'sig_' . time() . '.png';
$image_path = 'upload/' . $image_new_name;
$image_name = $ROOT_DIR . '/' . $image_path;
if (!file_exists($image_name)) {
imagepng($img, $image_name);
imagedestroy($img);
} else {
$image_new_name = 'new_' . $image_new_name;
$image_path = 'upload/new_' . $image_new_name;
$image_name = $ROOT_DIR . '/' . $image_path;
imagepng($img, $image_name);
imagedestroy($img);
}
This code will generate image from your data to the provided dir. then use that image to display. enjoy. :)

Show progessbar on page load

I have created the script of downloading an facebook album in php. When I will click on download button, script is fetching all photos in that album behind the scene and zip them inside a folder. I want to start a “progress bar” as soon as user-click download button as download process may take time.
Following is index.php
if ($album['count'] != "0 photos")
{
echo "";
}
Here I am passing album id to the download.php
and following is the code for download.php where I am downloading images into the downloads folder, creating the zip file of all that images and downloading that zip file.
<?php
require 'facebook/facebook.php';
$facebook = new Facebook(array(
'appId' => 'xxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxxxxxxx',
'cookie' => true,
));
//GETTING THE ID HERE FROM INDEX.PHP FILE
$albumid = $_GET['id'];
$photos = $facebook->api("/{$albumid}/photos?limit=50");
$file_name = rand(1, 99999) . "_image.zip";
$albumArr = array();
foreach ($photos['data'] as $photo) {
$albumArr[] = $photo['source'];
}
create_zip($albumArr, $file_name);
function create_zip($files, $file_name, $overwrite = false) {
$i = 0;
$imgFiles = array();
foreach ($files as $imglink) {
$img = #file_get_contents($imglink);
$destination_path = 'downloads/' . time() . "Image_" . $i . '.jpg';
#file_put_contents($destination_path, $img);
$imgFiles[] = $destination_path;
$i++;
}
if (file_exists($file_name) && !$overwrite) {
return false;
}
$valid_files = array();
if (is_array($imgFiles)) {
foreach ($imgFiles as $file) {
$valid_files[] = $file;
}
}
if (count($valid_files)) {
$zip = new ZipArchive();
if ($zip->open($file_name, $overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
echo "Sorry ZIP creation failed at this time";
}
$size1 = 0;
foreach ($valid_files as $file) {
$size1+= filesize($file);
$zip->addFile($file, pathinfo($file, PATHINFO_BASENAME));
}
$zip->close();
$allimages = glob('downloads/*.jpg');
foreach ($allimages as $img) { // iterate images
if (is_file($img)) {
unlink($img); // delete images
}
}
$count = $zip->numFiles;
$resultArr = array();
$resultArr['count'] = $count;
$resultArr['destination'] = $file_name;
$filename = $file_name;
$filepath = $_SERVER['HTTP_HOST'] . '/';
$path = $filepath . $filename;
if (file_exists($filename)) {
// push to download the zip
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="' . $filename . '"');
readfile($filename);
unlink($filename);
}
} else {
return false;
}
}
?>
I want to start a “progress bar” as soon as user-click download button as download process may take time.
How can I do this? Thanks
Something like this? PLease tell me if I didn't understand your question
HTML:
<img id="loadingImage" src="pathToImage" alt="" style="display:none" />
//pathToImage is the path to where your image is located
jQuery:
$('#YourButtonID').click(function(){
$('#loadingImage').css('display','block');
//call your download page
return false;
});
After your download and redirect are finished, call this method to hide the progressbar
$('#loadingImage').css('display','none');
You can do this by using ajax.
$(document).ready(function()
{
$("#download_button").click(function() {
document.getElementById('progressbar').style.display='';
//call your download page.
});
});

Joomla custom user extension

I'm writing a Joomla 1.5 extension for an advanced frontend user interface.
Now I have to add a function so the users can upload a picture in the frontend and it will be added to their account.
Is there a standard Joomla picture upload available or something?
Thanks
I have this is my code: (and some more I can not paste everything in here)
function deleteLogo($logo)
{
// define path to file to delete
$filePath = 'images/stories/members/' . $logo;
$imagePath = 'images/stories/members/image/' . $image;
// check if files exists
$fileExists = JFile::exists($filePath);
$imageExists = JFile::exists($imagePath);
if($fileExists)
{
// attempt to delete file
$fileDeleted = JFile::delete($filePath);
}
if($imageExists)
{
// attempt to delete file
$fileDeleted = JFile::delete($imagePath);
}
}
function saveLogo($files, $data)
{
$uploadFile = JRequest::getVar('logo', null, 'FILES', 'ARRAY');
$uploadImage = JRequest::getVar('image', null, 'FILES', 'ARRAY');
$save = true;
$saveImage = true;
if (!is_array($uploadFile)) {
// #todo handle no upload present
$save = false;
}
if ($uploadFile['error'] || $uploadFile['size'] < 1) {
// #todo handle upload error
$save = false;
}
if (!is_uploaded_file($uploadFile['tmp_name'])) {
// #todo handle potential malicious attack
$save = false;
}
if (!is_array($uploadImage)) {
// #todo handle no upload present
$saveImage = false;
}
if ($uploadImage['error'] || $uploadImage['size'] < 1) {
// #todo handle upload error
$saveImage = false;
}
if (!is_uploaded_file($uploadImage['tmp_name'])) {
// #todo handle potential malicious attack
$saveImage = false;
}
// Prepare the temporary destination path
//$config = & JFactory::getConfig();
//$fileDestination = $config->getValue('config.tmp_path'). DS . JFile::getName($uploadFile['tmp_name']);
// Move uploaded file
if($save)
{
$this->deleteLogo($data['oldLogo']);
$fileDestination = 'images/stories/members/' . $data['id'] . '-' . $uploadFile['name'];
$uploaded = JFile::upload($uploadFile['tmp_name'], $fileDestination);
}
if($saveImage)
{
$this->deleteLogo($data['oldImage']);
$fileDestination = 'images/stories/members/image/' . $data['id'] . '-' . $uploadImage['name'];
$uploadedImage = JFile::upload($uploadImage['tmp_name'], $fileDestination);
}
}

Categories