I need help with image resize I don't know how to put in
<?php
if (isset($_POST['newcover'])) {
////GET image uploading settings
$select_upload_options = mysql_query("SELECT * FROM covers_submit_options");
$uop = mysql_fetch_assoc($select_upload_options);
$poster = $uop['cover_who_post'];
$approve = $uop['cover_approve'];
$server = $uop['cover_server'];
$default_user = $uop['cover_default_user'];
$cover_title = $_POST['title'];
$cover_desc = $_POST['desc'];
$cover_desc2 = $_POST['desc2'];
$cover_date = $_POST['date'];
$cover_tags = $_POST['tags'];
$cover_okvir = $_POST['okvir'];
$cover_velicina = $_POST['velicina'];
$cover_image2 = $_POST['image2'];
$cover_category = $_POST['huge'];
if ($poster != 'user' && $_SESSION['userid'] == '') {
$poster_user = $default_user;
} else {
$poster_user = $_SESSION['userid'];
}
if ($cover_title == '') {
$post_error = '<div class="alert alert-danger"><h3>Unesite Ime i Prezme</h3></div>';
} elseif ($cover_category == '') {
$post_error = '<div class="alert alert-danger"><h3>Izaberite Grad ii Općinu</h3></div>';
} elseif ($cover_date == '') {
$post_error = '<div class="alert alert-danger"><h3>Unesite Datum-Godište Npr. 1965-2016</h3></div>';
} elseif ($cover_okvir == '') {
$post_error = '<div class="alert alert-danger"><h3>Izaberite Izgled Osmrtnice</h3></div>';
} elseif ($poster_user == '') {
$poster_user = '1';
} elseif ($_FILES['photo']['size'] == '1') {
$post_error = '<div class="alert alert-danger"><h3>Please Select Image</h3></div>';
} else {
$post_error = '';
}
if ($post_error == '') {
if ($server == 'amazon') {
////////UPLOAD TO AMAZON/////////////////////
include('includes/amazonUpload.php');
////////UPLOAD TO AMAZON/////////////////////
} else {
////////////REGULAR UPLOADER TO SERVER/////////
list($file, $error) = upload('photo', 'images/covers/', 'jpg,jpeg,gif,png');
list($width, $height, $type, $attr) = ('images/covers/' . $file);
////////////Da bi upload slike mogao da radi uklonio sam dio koda orginal kod je ovaj dolje getimagesize prije zagrade images/covers /////////
if ($width < 0 || $height < 0) {
$post_error = "<div class='alert alert-danger'><h3>The Cover is Small<br>Please note that the Minimum allowed hight is 300px and Minimum Width is 800px </h3></div>";
unlink('images/covers/' . $file);
} else {
$image = 'images/covers/' . $file;
}
////////////REGULAR UPLOADER TO SERVER/////////
$error = $post_error;
}
////Store Into Database
if (!$error) {
$string = $slug;
if (strlen($string) != mb_strlen($string, 'utf-8')) {
$slug = date("M-D-His");
} else {
$slug = preg_replace("/[^a-zA-Z0-9_\-]/", '', $cover_title);
//$slug = preg_replace('/\s+/', '-', $cover_title);
$slug = strtolower($slug);
}
$is_slug_exists = mysql_query("SELECT * FROM covers_posts WHERE post_slug = '$slug' ");
$slug_exsits = mysql_num_rows($is_slug_exists);
if ($slug_exsits != '0') {
$slug = $slug . '-' . date('sy');
} else {
$slug = $slug;
}
$cover_datum = date("d-m-Y");
$insert = mysql_query("INSERT INTO covers_posts VALUES ('',
'$cover_title',
'$cover_desc',
'$cover_desc2',
'$cover_date',
'$cover_tags',
'$cover_okvir',
'$cover_velicina',
'$slug',
'$image',
'$cover_image2',
'$cover_category',
'1',
'$poster_user',
'$approve',
'0',
'0',
'0',
'$cover_datum'
) ");
order_badge($poster_user);
$post_error = '<div class="alert alert-success"><h3>Uspješno Ste Dodali Osmrtnicu , Prebacit će vas za 5 sekundi<br>
Ukolko ste zastali Kliknite Ovde
</h3></div>';
$redir = 'osmrtnica-' . $slug . '.html';
redirect($redir, '5');
} else {
$post_error = '<div class="alert alert-danger"><h3>' . $error . '</h3></div>';
}
} else {
$post_error = $post_error;
}
$smarty->assign('UploadResult', $post_error);
}
ok I know it is older script and I changed later in mysqli connection.
I read manual about upload and resize image now it is resize image but all image are black
elseif ($cover_okvir == '') {
$post_error = '<div class="alert alert-danger"><h3>Izaberite Izgled Osmrtnice</h3></div>';
}
elseif ($poster_user == '') {
$poster_user = '1';
}else{
////////////REGULAR UPLOADER TO SERVER/////////
list($file,$error) = upload('photo','images/covers/','jpg,jpeg,gif,png');
list($width, $height, $type, $attr) = getimagesize('images/covers/'.$file);
$width = 140;
$height = 150;
////////////REGULAR UPLOADER TO SERVER/////////
$src = imagecreatefromstring('images/covers/'.$file);
$dst = imagecreatetruecolor($width,$height);
imagecopyresampled($dst,$src,0,0,0,0,$width,$height);
imagedestroy($src);
imagepng($dst,'images/covers/'.$file); // adjust format as needed
imagedestroy($dst);
}
$image = 'images/covers/'.$file;
enter code here
Related
This question already has answers here:
Matching SRC attribute of IMG tag using preg_match
(6 answers)
Closed 3 years ago.
7moHi,
I have joomla 3 and I want set the first image of article as intro image in category blog override.
I have a plugin that grab first image of article and set it in og image metatag. I think that we can use this function for my question.
This is the code of plugin
// Image
$pictures = '';
if (isset($row->images)) {
//$pictures = json_decode($row->images);
$pictures = (is_string($row->images) ? json_decode($row->images) : $row->images);
}
$imgSet = 0;
if ($this->params->get('image'.$suffix, '') != '' && $parameterImage == 1) {
$this->renderTag('og:image', $this->setImage($this->params->get('image'.$suffix, '')), $type);
$imgSet = 1;
} else if ($thisImg != ''){
$this->renderTag('og:image', $this->setImage($thisImg), $type);
$imgSet = 1;
} else if (isset($pictures->{'image_intro'}) && $pictures->{'image_intro'} != '') {
$this->renderTag('og:image', $this->setImage($pictures->{'image_intro'}), $type);
$imgSet = 1;
} else if (isset($pictures->{'image_fulltext'}) && $pictures->{'image_fulltext'} != '') {
$this->renderTag('og:image', $this->setImage($pictures->{'image_fulltext'}), $type);
$imgSet = 1;
} else {
// Try to find image in article
$fulltext = '';
if (isset($row->fulltext) && $row->fulltext != '') {
$fulltext = $row->fulltext;
}
$introtext = '';
if (isset($row->introtext) && $row->introtext != '') {
$introtext = $row->introtext;
}
$content = $introtext . $fulltext;
preg_match('/< *img[^>]*src *= *["\']?([^"\']*)/i', $content, $src);
if (isset($src[1]) && $src[1] != '') {
$this->renderTag('og:image', $this->setImage($src[1]), $type);
//$this->renderTag('og:image', JURI::base(false).$src[1], $type);
$imgSet = 1;
}
// Try to find image in images/phocaopengraph folder
if ($imgSet == 0) {
if (isset($row->id) && (int)$row->id > 0) {
jimport( 'joomla.filesystem.file' );
$imgPath = '';
$path = JPATH_ROOT . '/images/phocaopengraph/';
if (JFile::exists($path . '/' . (int)$row->id.'.jpg')) {
$imgPath = 'images/phocaopengraph/'.(int)$row->id.'.jpg';
} else if (JFile::exists($path . '/' . (int)$row->id.'.png')) {
$imgPath = 'images/phocaopengraph/'.(int)$row->id.'.png';
} else if (JFile::exists($path . '/' . (int)$row->id.'.gif')) {
$imgPath = 'images/phocaopengraph/'.(int)$row->id.'.gif';
}
if ($imgPath != '') {
$this->renderTag('og:image', $this->setImage($imgPath), $type);
$imgSet = 1;
}
}
}
}
// If still image not set and parameter Image is set as last, then try to add the parameter image
if ($imgSet == 0 && $this->params->get('image'.$suffix, '') != '' && $parameterImage == 0) {
$this->renderTag('og:image', $this->setImage($this->params->get('image'.$suffix, '')), $type);
}
// END IMAGE
And I want insert result in my override page, in this point
<div class="image-intro">
<?php echo JLayoutHelper::render('joomla.content.intro_image', $this->item); ?>
<div>
But I can't modify the code for my purpose.
In override eof template I have find also $this->item->event->beforeDisolayContent;
That think show full article.
Can I grab first image of article and insert in intro text?
$texthtml=$this->item->text;
preg_match('/<img.+src=[\'"](?P<src>.+?)[\'"].*>/i', $texthtml, $image);
$imgkk=$image['src'];
echo '<img src="' . $imgkk. ' ">'
?>
I've solved!
Firstly, I had only one picture to submit, so that there was nothing sophisticated to accomplish, but now there could be either one, two or three images. I made my code too complicated.
The main problem is:
<div id="upload-area">
<label for="file-upload" class="custom-file-upload">
<i class="fa fa-cloud-upload"></i> Add Photo or Video
</label>
<input name="files[]" id="file-upload" accept="image/*" type="file" multiple/>
I have a submit form on the website, there is an upload area to choose multiple files, so I have an array of them.
The first my idea was to run a “for” loop through all indices, but I failed, because realized that it could have worked only if I need to send images to the DB one by one(as a sequence of records) neither as a one unite raw in the table.
That’s why I added duplicated parts of code, but with different url, image name, path and etc number.
But I understood it works properly only for 3 images chosen.
I approached to make something like this:
if ($_FILES["files"]["name"][1] === null | $_FILES["files"]["name"][1].length === 0) {
$image1 = “ “;
$url1 = “ “;
else {
$upload_path1 = "uploads/1" . $_FILES["files"]["name"][1];
$url1 = "https://bettercity.online/$upload_path1";
$image1 = $_FILES["files"]["name"][1];
$uploadedfile1 = $_FILES['files']['tmp_name'][1];
$image_type1 = $_FILES["files"]["type"][1];
}
But there is a problem with inserting those empty variables values that I am unable to solve.
The current(abysmal) code:
$upload_path0 = "uploads/0" . $_FILES["files"]["name"][0];
$url0 = "https://bettercity.online/$upload_path0";
$image0 = $_FILES["files"]["name"][0];
$uploadedfile0 = $_FILES['files']['tmp_name'][0];
$image_type = $_FILES["files"]["type"][0];
$upload_path1 = "uploads/1" . $_FILES["files"]["name"][1];
$url1 = "https://bettercity.online/$upload_path1";
$image1 = $_FILES["files"]["name"][1];
$uploadedfile1 = $_FILES['files']['tmp_name'][1];
$image_type1 = $_FILES["files"]["type"][1];
$upload_path2 = "uploads/2" . $_FILES["files"]["name"][2];
$url2 = "https://bettercity.online/$upload_path2";
$image2 = $_FILES["files"]["name"][2];
$uploadedfile2 = $_FILES['files']['tmp_name'][2];
$image_type2 = $_FILES["files"]["type"][2];
$ftp_server = " ";
$conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");
$user = " ";
$pass = " ";
if (ftp_login($conn_id, $user, $pass))
{
if ($_FILES["files"]["error"][0] > 0)
{
echo "Return Code: " . $_FILES["files"]["error"][0] . "<br />";
}
else
{
if($image_type=='image/png' || $image_type=='image/x-png')
{
if($image_type1=='image/png' || $image_type1=='image/x-png')
{
if($image_type2=='image/png' || $image_type2=='image/x-png')
{
$src0 = imagecreatefrompng($uploadedfile0);
$src1 = imagecreatefrompng($uploadedfile1);
$src2 = imagecreatefrompng($uploadedfile2);
}
elseif($image_type2=='image/jpeg' || $image_type2=='image/jpg' || $image_type2 == 'image/pjpeg')
{
$src0 = imagecreatefrompng($uploadedfile0);
$src1 = imagecreatefrompng($uploadedfile1);
$src2 = imagecreatefromjpeg($uploadedfile2);
}
}
elseif($image_type1=='image/jpeg' || $image_type1=='image/jpg' || $image_type1 == 'image/pjpeg')
{
if($image_type2=='image/png' || $image_type2=='image/x-png')
{
$src0 = imagecreatefrompng($uploadedfile0);
$src1 = imagecreatefromjpeg($uploadedfile1);
$src2 = imagecreatefrompng($uploadedfile2);
}
elseif($image_type2=='image/jpeg' || $image_type2=='image/jpg' || $image_type2 == 'image/pjpeg')
{
$src0 = imagecreatefrompng($uploadedfile0);
$src1 = imagecreatefromjpeg($uploadedfile1);
$src2 = imagecreatefromjpeg($uploadedfile2);
}
}
}
elseif($image_type=='image/jpeg' || $image_type=='image/jpg' || $image_type == 'image/pjpeg')
{
if($image_type1=='image/png' || $image_type1=='image/x-png')
{
if($image_type2=='image/png' || $image_type2=='image/x-png')
{
$src0 = imagecreatefromjpeg($uploadedfile0);
$src1 = imagecreatefrompng($uploadedfile1);
$src2 = imagecreatefrompng($uploadedfile2);
}
elseif($image_type2=='image/jpeg' || $image_type2=='image/jpg' || $image_type2 == 'image/pjpeg')
{
$src0 = imagecreatefromjpeg($uploadedfile0);
$src1 = imagecreatefrompng($uploadedfile1);
$src2 = imagecreatefromjpeg($uploadedfile2);
}
}
elseif($image_type1=='image/jpeg' || $image_type1=='image/jpg' || $image_type1 == 'image/pjpeg')
{
if($image_type2=='image/png' || $image_type2=='image/x-png')
{
$src0 = imagecreatefromjpeg($uploadedfile0);
$src1 = imagecreatefromjpeg($uploadedfile1);
$src2 = imagecreatefrompng($uploadedfile2);
}
elseif($image_type2=='image/jpeg' || $image_type2=='image/jpg' || $image_type2 == 'image/pjpeg')
{
$src0 = imagecreatefromjpeg($uploadedfile0);
$src1 = imagecreatefromjpeg($uploadedfile1);
$src2 = imagecreatefromjpeg($uploadedfile2);
}
}
}
$new_width=768;
$new_height=500;
$image_p=imagecreatetruecolor($new_width,$new_height);
imagealphablending($image_p, false);
imagesavealpha($image_p, true);
list($width,$height)=getimagesize($uploadedfile0);
$image_p1=imagecreatetruecolor($new_width,$new_height);
imagealphablending($image_p1, false);
imagesavealpha($image_p1, true);
list($width1,$height1)=getimagesize($uploadedfile1);
$image_p2=imagecreatetruecolor($new_width,$new_height);
imagealphablending($image_p2, false);
imagesavealpha($image_p2, true);
list($width2,$height2)=getimagesize($uploadedfile2);
imagecopyresampled($image_p,$src0,0,0,0,0,$new_width,$new_height,$width,$height);
imagecopyresampled($image_p1,$src1,0,0,0,0,$new_width,$new_height,$width1,$height1);
imagecopyresampled($image_p2,$src2,0,0,0,0,$new_width,$new_height,$width2,$height2);
if(move_uploaded_file($_FILES["files"]["tmp_name"][0], $upload_path0) && move_uploaded_file($_FILES["files"]["tmp_name"][1], $upload_path1) && move_uploaded_file($_FILES["files"]["tmp_name"][2], $upload_path2))
{
if ($resp['status'] == 'OK') {
$latitude = $resp['results'][0]['geometry']['location']['lat'];
$longitude = $resp['results'][0]['geometry']['location']['lng'];
$sql = "INSERT INTO problem_data(username, name, description, mediafile, mediafile1, mediafile2, district_id, category_id, location, latitude, longitude, rating, counter, general_rating, status_id, upl_date) values('$username','$name','$description','$url0','$url1','$url2','$district_id','$category_id','$location','$latitude','$longitude', 0.0, 0, 0.0, 1, '$date')";
if(mysqli_query($con, $sql))
{
if($image_type=='image/png' || $image_type=='image/x-png'){
if($image_type1=='image/png' || $image_type1=='image/x-png'){
if($image_type2=='image/png' || $image_type2=='image/x-png'){
imagepng($image_p,$upload_path0,9) ;
imagepng($image_p1,$upload_path1,9) ;
imagepng($image_p2,$upload_path2,9) ;
}
else {
imagepng($image_p,$upload_path0,9) ;
imagepng($image_p1,$upload_path1,9) ;
imagejpeg($image_p2,$upload_path2,100);
}
}
else {
if($image_type2=='image/png' || $image_type2=='image/x-png'){
imagepng($image_p,$upload_path0,9) ;
imagejpeg($image_p1,$upload_path1,100);
imagepng($image_p2,$upload_path2,9) ;
}
else {
imagepng($image_p,$upload_path0,9) ;
imagejpeg($image_p1,$upload_path1,100);
imagejpeg($image_p2,$upload_path2,100);
}
}
}
else {
if($image_type1=='image/png' || $image_type1=='image/x-png'){
if($image_type2=='image/png' || $image_type2=='image/x-png'){
imagejpeg($image_p0,$upload_path0,100);
imagepng($image_p1,$upload_path1,9) ;
imagepng($image_p2,$upload_path2,9) ;
}
else {
imagejpeg($image_p0,$upload_path0,100);
imagepng($image_p1,$upload_path1,9) ;
imagejpeg($image_p2,$upload_path2,100);
}
}
else {
if($image_type2=='image/png' || $image_type2=='image/x-png'){
imagejpeg($image_p0,$upload_path0,100);
imagejpeg($image_p1,$upload_path1,100);
imagepng($image_p2,$upload_path2,9) ;
}
else {
imagejpeg($image_p0,$upload_path0,100);
imagejpeg($image_p1,$upload_path1,100);
imagejpeg($image_p2,$upload_path2,100);
}
}
}
}
echo 'Problem uploaded';
imagedestroy($image_p);
imagedestroy($image_p1);
imagedestroy($image_p2);
}
}
}
}
I want to upload image from galery to server. I succeed to upload image, but i just can upload 1 file. if i upload 2 file, the 2nd file will be upload. The 1st file will not upload. or if i edit and upload 2nd image file, then 1st image file will be replaced by 2nd image file.
this is webservicecontroller.php
$imagePath = IMAGE_PATH_FOR_TIM_THUMB.'/'.STUDY_MATERIAL_DIR.'/';
if (!empty($_POST))
{
$this->loadModel('StudyMaterial');
if($_POST['type'] != 'delete')
{
$shift = array();
if($_POST['type'] == 'edit')
{
$shift['StudyMaterial']['id'] = $_POST['study_material_id'];
}
$shift['StudyMaterial']['user_id'] = $_POST['user_id'];
$shift['StudyMaterial']['standard_id'] = $_POST['standard_id'];
$shift['StudyMaterial']['subject_id'] = $_POST['subject_id'];
$shift['StudyMaterial']['topic_id'] = $_POST['topic_id'];
$shift['StudyMaterial']['lesson_id'] = $_POST['lesson_id'];
$shift['StudyMaterial']['name'] = $_POST['name'];
$shift['StudyMaterial']['description'] = $_POST['description'];
$this->StudyMaterial->save($shift);
$study_material_id = $this->StudyMaterial->id;
if(isset($_FILES['study_material_file']) && !empty($_FILES['study_material_file']) && ($_FILES['study_material_file']['error'] == 0))
{
$name = $_FILES['study_material_file']['name'];
$ext = substr(strrchr($name, "."), 1);
$only_name = $name . "_" . time();
$filename = 'topic_file_'.microtime(true).'.'.strtolower($ext);
$original = STUDY_MATERIAL_DIR . "/" . $filename;
$file_type = $_POST['file_type'];
if($file_type == 'video')
{
if(strtolower($ext) == 'mov')
{
$original = STUDY_MATERIAL_DIR . "/" . $filename;
#move_uploaded_file($_FILES["study_material_file"]["tmp_name"], $original);
$new_filename = $only_name. '.mp4';
$srcFile = STUDY_MATERIAL_DIR . "/" . $filename;
$destFile = STUDY_MATERIAL_DIR . "/" . $new_filename;
exec('ffmpeg -i '.$srcFile.' -f mp4 -s 320x240 '.$destFile.'');
if($_POST['type'] == 'edit')
{
$checkAlready = $this->StudyMaterial->find('first',array('conditions'=>array('StudyMaterial.id'=>$_POST['study_material_id'])));
$image = $checkAlready['StudyMaterial']['file_name'];
if($image && file_exists(WWW_ROOT.STUDY_MATERIAL_DIR.DS.$image ))
{
#unlink(WWW_ROOT.STUDY_MATERIAL_DIR.DS.$image);
}
}
$this->StudyMaterial->saveField('file_name',$filename,false);
$this->StudyMaterial->saveField('type',$file_type,false);
}
else
{
#move_uploaded_file($_FILES["study_material_file"]["tmp_name"], $original);
if($_POST['type'] == 'edit')
{
$checkAlready = $this->StudyMaterial->find('first',array('conditions'=>array('StudyMaterial.id'=>$_POST['study_material_id'])));
$image = $checkAlready['StudyMaterial']['file_name'];
if($image && file_exists(WWW_ROOT.STUDY_MATERIAL_DIR.DS.$image ))
{
#unlink(WWW_ROOT.STUDY_MATERIAL_DIR.DS.$image);
}
}
$this->StudyMaterial->saveField('file_name',$filename,false);
$this->StudyMaterial->saveField('type',$file_type,false);
}
}
else
{
#move_uploaded_file($_FILES["study_material_file"]["tmp_name"], $original);
if($_POST['type'] == 'edit')
{
$checkAlready = $this->StudyMaterial->find('first',array('conditions'=>array('StudyMaterial.id'=>$_POST['study_material_id'])));
$image = $checkAlready['StudyMaterial']['file_name'];
if($image && file_exists(WWW_ROOT.STUDY_MATERIAL_DIR.DS.$image ))
{
#unlink(WWW_ROOT.STUDY_MATERIAL_DIR.DS.$image);
}
}
$this->StudyMaterial->saveField('file_name',$filename,false);
$this->StudyMaterial->saveField('type',$file_type,false);
}
}
else
{
if($_POST['type'] == 'edit')
{
$this->StudyMaterial->id = $_POST['study_material_id'];
$this->StudyMaterial->saveField('file_name','',false);
$this->StudyMaterial->saveField('type','',false);
}
}
if($_POST['type'] == 'edit')
{
$responseData = array(
'status' => 1,
'message' => "Study Material updated successfully."
);
}
else
{
$responseData = array(
'status' => 1,
'message' => "Study Material added successfully."
);
}
}
Is the problem in webservice or android? this is add_material.java
private void selectImage() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
getActivity().startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
}
public String getRealPathFromURI(Uri contentUri) {
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
Problem in your server side please check your database query where you update your column.
I am trying to fix/debug a site where all images in the site are being generated by an script. Another developer created this. Now all the images for some reason don’t work.
I am trying to debug the code and try to break it somewhere where it should work so that then I can see whats broken and stablish a baseline. But I cant find a way to debug this properly.
Could anyone point me on the right direction on how to debug the following script or what could be broken? Nothing that I do seems to work.
Update: Thanks Pekka 웃 comment I can now see the error and it says Warning: imagejpeg(): Filename cannot be empty in /var/www/vhosts/mysticindia.co.uk/httpdocs/inc/class.images.php on line 496
that line is the imagejpg() that is after the line
if ($imageModify == "grey") {
imagefilter($this->imageResized, IMG_FILTER_GRAYSCALE);
}
CODE
<?php
class images {
var $imageID;
var $imageData;
var $image;
var $width;
var $height;
var $imageResized;
function __construct($imageID = null) {
if ($imageID !== null) {
$this->imageID = $imageID;
$this->imageData = $this->getImageInfo();
}
}
function removeImage() {
if ($this->imageID) {
$query = "DELETE FROM Images ";
$query .= "WHERE ImageID = '%s' ";
$result = RunQuery($query,__LINE__);
$query = sprintf($query, mysql_real_escape_string($this->imageID));
$result = RunQuery($query,__LINE__);
tableEmpty("Images");
}
}
private function buildImageQuery($options=array()) {
global $maxItems;
$maxItems = ((isset($options["maxItems"])) && (!empty($options["maxItems"]))) ? $options["maxItems"] : $maxItems;
$pageID = isset($options["pageID"]) ? $options["pageID"] : "";
$orderBy = ((isset($options["orderBy"])) && (!empty($options["orderBy"]))) ? $options["orderBy"] : "ImageIndex";
$sortBy = ((isset($options["sortBy"])) && (!empty($options["sortBy"]))) ? $options["sortBy"] : "ASC";
$groupBy = (isset($options["groupBy"])) ? $options["groupBy"] : "";
$groupBy = (isset($options["groupBy"])) ? $options["groupBy"] : "";
$limit = isset($options["limit"]) ? $options["limit"] : "";
$searchArray = isset($options["searchArray"]) ? $options["searchArray"] : "";
$recordOffset = ($pageID - 1) * $maxItems;
$query = "SELECT SQL_CALC_FOUND_ROWS i.ImageID, ImageName, ImageIndex FROM Images i ";
$query .= "WHERE i.ImageID != '0' ";
if ((isset($searchArray["catalogue"])) && (!empty($searchArray["catalogue"]))) {
$query .= "AND Catalogue = '" . $searchArray["catalogue"] . "' ";
}
if ((isset($searchArray["catalogueID"])) && (!empty($searchArray["catalogueID"]))) {
if (is_array($searchArray["catalogueID"])) {
$count = 0;
$query .= "AND (";
foreach ($searchArray["catalogueID"] as $catalogueID) {
$count++;
$query .= "CatalogueID= '" . $catalogueID . "' ";
if ($count < count($searchArray["catalogueID"])) {
$query .= "OR ";
}
}
$query .= ") ";
} else {
$query .= "AND CatalogueID= '" . $searchArray["catalogueID"] . "' ";
}
}
if ((isset($searchArray["imageName"])) && (!empty($searchArray["imageName"]))) {
$query .= "AND ImageName = '" . $searchArray["imageName"] . "' ";
}
if ((isset($groupBy)) && (!empty($groupBy))) {
$query .= "GROUP BY " . $groupBy . " ";
}
if ((isset($groupBy)) && (!empty($groupBy))) {
$query .= "GROUP BY " . $groupBy . " ";
}
if ($orderBy) {
$query .= "ORDER BY $orderBy $sortBy ";
}
if (($pageID) && (empty($limit))) {
$query .= "LIMIT $recordOffset, $maxItems ";
} else if (!empty($limit)) {
$query .= "LIMIT $limit ";
}
return $query;
}
function getImages($options=array()) {
global $maxItems;
$maxItems = ((isset($options["maxItems"])) && (!empty($options["maxItems"]))) ? $options["maxItems"] : $maxItems;
$pageID = isset($options["pageID"]) ? $options["pageID"] : "";
$recordOffset = ($pageID - 1) * $maxItems;
$dataArray = array();
$listArray = array();
$maxPages = 0;
$query = $this->buildImageQuery($options);
$result = RunQuery($query,__LINE__);
if (($pageID) && (empty($limit))) {
$query2 = "SELECT FOUND_ROWS() AS NoItems ";
$result2 = RunQuery($query2);
$row2 = mysql_fetch_assoc($result2);
$maxPages = ceil($row2["NoItems"] / $maxItems);
}
if (mysql_num_rows($result) != 0) {
while ($row = mysql_fetch_assoc($result)) {
$listArray[] = $row["ImageID"];
}
$dataArray["maxPages"] = $maxPages;
$dataArray["results"] = $listArray;
return $dataArray;
}
}
function listImages($options=array()) {
$query = $this->buildImageQuery($options);
$result = RunQuery($query,__LINE__);
if (mysql_num_rows($result)) {
$dataArray = array();
while ($row = mysql_fetch_assoc($result)) {
$key = $row["ImageID"];
$value = $row["ImageName"];
$dataArray[$key] = $value;
}
return $dataArray;
} else {
return false;
}
}
function manageImage($options=array()) {
global $sesAdminID;
$imageInfo = isset($options["imageInfo"]) ? $options["imageInfo"] : "";
$catalogue = isset($options["catalogue"]) ? $options["catalogue"] : "";
$catalogueID = isset($options["catalogueID"]) ? $options["catalogueID"] : "";
$imageCaption = isset($options["imageCaption"]) ? $options["imageCaption"] : "";
$imageName = isset($imageInfo["imageName"]) ? $imageInfo["imageName"] : "";
$imageWidth = isset($imageInfo["imageWidth"]) ? $imageInfo["imageWidth"] : "";
$imageHeight = isset($imageInfo["imageHeight"]) ? $imageInfo["imageHeight"] : "";
$imageType = isset($imageInfo["imageType"]) ? $imageInfo["imageType"] : "image/jpeg";
$imageIndex = isset($imageInfo["imageIndex"]) ? $imageInfo["imageIndex"] : "";
if ($this->imageID) {
$query = "UPDATE Images SET ";
$query .= "ImageName = '%s', ";
$query .= "ImageWidth = '%s', ";
$query .= "ImageHeight = '%s', ";
$query .= "ImageType = '%s', ";
$query .= "Catalogue = '%s', ";
$query .= "CatalogueID = '%s', ";
$query .= "ImageCaption = '%s', ";
$query .= "ImageIndex = '%s' ";
$query .= "WHERE ImageID = '" . $this->imageID . "' ";
} else {
$query = "INSERT INTO Images SET ";
$query .= "ImageName = '%s', ";
$query .= "ImageWidth = '%s', ";
$query .= "ImageHeight = '%s', ";
$query .= "ImageType = '%s', ";
$query .= "Catalogue = '%s', ";
$query .= "CatalogueID = '%s', ";
$query .= "ImageCaption = '%s', ";
$query .= "ImageIndex = '%s' ";
}
$query = sprintf($query, mysql_real_escape_string($imageName),
mysql_real_escape_string($imageWidth),
mysql_real_escape_string($imageHeight),
mysql_real_escape_string($imageType),
mysql_real_escape_string($catalogue),
mysql_real_escape_string($catalogueID),
mysql_real_escape_string($imageCaption),
mysql_real_escape_string($imageIndex));
$result = RunQuery($query,__LINE__);
$this->imageID = (!empty($this->imageID)) ? $this->imageID : mysql_insert_id();
return $this->imageID;
}
function updateCaption($imageCaption) {
$query = "UPDATE Images SET ";
$query .= "ImageCaption = '%s' ";
$query .= "WHERE ImageID = '%s' ";
$query = sprintf($query, mysql_real_escape_string($imageCaption),
mysql_real_escape_string($this->imageID));
$result = RunQuery($query,__LINE__);
}
function reOrderImages($options=array()) {
$catalogue = isset($options["catalogue"]) ? $options["catalogue"] : "";
$catalogueID = isset($options["catalogueID"]) ? $options["catalogueID"] : "";
$sortOrder = isset($options["sortOrder"]) ? str_replace("Image_", "", $options["sortOrder"]) : "";
if (!empty($sortOrder)) {
$sortArray = explode(",", $sortOrder);
foreach ($sortArray as $order => $imageID) {
$query = "UPDATE Images SET ";
$query .= "ImageIndex = '%s' ";
$query .= "WHERE ImageID = '%s' ";
$query .= "AND Catalogue = '%s' ";
$query .= "AND CatalogueID = '%s' ";
$query = sprintf($query, mysql_real_escape_string($order),
mysql_real_escape_string($imageID),
mysql_real_escape_string($catalogue),
mysql_real_escape_string($catalogueID));
$result = RunQuery($query,__LINE__);
}
}
}
function returnImageType($options=array()) {
$imageName = ((isset($options["imageName"])) && (!empty($options["imageName"]))) ? $options["imageName"] : "";
$imageType = ((isset($options["imageType"])) && (!empty($options["imageType"]))) ? $options["imageType"] : "";
// Image Extensions
$imgExt["pjpeg"] = "jpg";
$imgExt["jpeg"] = "jpg";
$imgExt["gif"] = "gif";
$imgExt["png"] = "png";
$imgExt["jpg"] = "jpg";
// Image Types
$imgType["pjpeg"] = "jpeg";
$imgType["jpeg"] = "jpeg";
$imgType["jpg"] = "jpeg";
$imgType["gif"] = "gif";
$imgType["png"] = "png";
if ($imageType) {
$tempImageType = explode("/", strtolower($imageType));
$tempImageType = str_replace(" ", "", $tempImageType[count($tempImageType)-1]);
} else if ($imageName) {
$tempImageType = explode("/", strtolower($imageName));
$tempImageType = explode(".", $tempImageType[count($tempImageType)-1]);
$tempImageType = $tempImageType[count($tempImageType)-1];
} else {
return "";
}
$resizeInfo = array();
$resizeInfo["imageType"] = isset($imgType[$tempImageType]) ? $imgType[$tempImageType] : "jpeg";
$resizeInfo["imageExt"] = isset($imgExt[$tempImageType]) ? $imgExt[$tempImageType] : "jpg";
return $resizeInfo;
}
function createImageName($imageFolder,$imageName) {
global $documentRoot;
if (file_exists($documentRoot . $imageFolder . $imageName)) {
$imageName = strtotime("now") . "_" . $imageName;
}
return $imageName;
}
function uploadImage($options=array()) {
global $documentRoot, $imageFolder, $maxImageW;
$imageInfo = array();
$imageLocal = ((isset($options["tmp_name"])) && (!empty($options["tmp_name"]))) ? $options["tmp_name"] : "";
$imageType = ((isset($options["type"])) && (!empty($options["type"]))) ? $options["type"] : "";
$imageName = ((isset($options["name"])) && (!empty($options["name"]))) ? $options["name"] : "";
$imageSize = ((isset($options["size"])) && (!empty($options["size"]))) ? $options["size"] : "";
$functionArray = array("imageName"=>$imageName,"imageType"=>$imageType);
$imageTypeInfo = $this->returnImageType($functionArray);
$tempImageType = $imageTypeInfo["imageType"];
$tempImageExt = $imageTypeInfo["imageExt"];
$row = getimagesize($imageLocal);
$width = $row[0];
$height = $row[1];
$imageName = $this->createImageName($imageFolder,fileNameFix($imageName) . "." . $tempImageExt);
if ($width <= $maxImageW) {
copy($imageLocal, $documentRoot . $imageFolder . $imageName);
$imageInfo["imageWidth"] = $width;
$imageInfo["imageHeight"] = $height;
} else {
$functiontoRun = "imagecreatefrom" . $tempImageType;
$this->image = $functiontoRun($imageLocal);
$functionArray = array("origWidth"=>$width,"origHeight"=>$height,"imageWidth"=>$maxImageW);
$resizeImage = $this->resizeImage($functionArray);
$newImageWidth = $resizeImage["CanvasWidth"];
$newImageHeight = $resizeImage["CanvasHeight"];
$image = imagecreatetruecolor($newImageWidth, $newImageHeight);
imagecopyresampled($image, $this->image, 0, 0, 0, 0, $newImageWidth, $newImageHeight, $width, $height);
$functiontoRun = "image" . $tempImageType;
#$functiontoRun($image, $documentRoot . $imageFolder . $imageName) or die("can not create image");
$imageInfo["imageWidth"] = $newImageWidth;
$imageInfo["imageHeight"] = $newImageHeight;
}
$imageInfo["imageType"] = $imageType;
$imageInfo["imageName"] = $imageName;
return $imageInfo;
}
function uploadImages($options=array()) {
$catalogue = isset($options["catalogue"]) ? $options["catalogue"] : "";
$catalogueID = isset($options["catalogueID"]) ? $options["catalogueID"] : "";
$newImages = isset($options["newImages"]) ? $options["newImages"] : "";
$functionArray = array("searchArray"=>$options);
$imageIndex = $this->returnImageIndex($functionArray);
foreach ($newImages as $newImage) {
$imageIndex++;
$imageCaption = $newImage["caption"];
$imageInfo = $this->uploadImage($newImage);
$functionArray = array("imageCaption"=>$imageCaption,"imageInfo"=>$imageInfo,"catalogue"=>$catalogue,"catalogueID"=>$catalogueID,"imageIndex"=>$imageIndex);
$this->imageID = 0;
$this->manageImage($functionArray);
}
}
private function getDimensions($newWidth, $newHeight, $option) {
switch ($option) {
case 'exact':
$optimalWidth = $newWidth;
$optimalHeight= $newHeight;
break;
case 'portrait':
$optimalWidth = $this->getSizeByFixedHeight($newHeight);
$optimalHeight= $newHeight;
break;
case 'landscape':
$optimalWidth = $newWidth;
$optimalHeight= $this->getSizeByFixedWidth($newWidth);
break;
case 'auto':
$optionArray = $this->getSizeByAuto($newWidth, $newHeight);
$optimalWidth = $optionArray['optimalWidth'];
$optimalHeight = $optionArray['optimalHeight'];
break;
case 'square':
$optionArray = $this->getOptimalCrop($newWidth, $newHeight);
$optimalWidth = $optionArray['optimalWidth'];
$optimalHeight = $optionArray['optimalHeight'];
break;
}
return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
}
private function getSizeByFixedHeight($newHeight) {
$ratio = $this->width / $this->height;
$newWidth = $newHeight * $ratio;
return $newWidth;
}
private function getSizeByFixedWidth($newWidth) {
$ratio = $this->height / $this->width;
$newHeight = $newWidth * $ratio;
return $newHeight;
}
private function getSizeByAuto($newWidth, $newHeight) {
if ($this->height < $this->width) {
$optimalWidth = $newWidth;
$optimalHeight= $this->getSizeByFixedWidth($newWidth);
} elseif ($this->height > $this->width) {
$optimalWidth = $this->getSizeByFixedHeight($newHeight);
$optimalHeight= $newHeight;
} else {
if ($newHeight < $newWidth) {
$optimalWidth = $newWidth;
$optimalHeight= $this->getSizeByFixedWidth($newWidth);
} else if ($newHeight > $newWidth) {
$optimalWidth = $this->getSizeByFixedHeight($newHeight);
$optimalHeight= $newHeight;
} else {
// *** Sqaure being resized to a square
$optimalWidth = $newWidth;
$optimalHeight= $newHeight;
}
}
return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
}
private function getOptimalCrop($newWidth, $newHeight) {
$heightRatio = $this->height / $newHeight;
$widthRatio = $this->width / $newWidth;
if ($heightRatio < $widthRatio) {
$optimalRatio = $heightRatio;
} else {
$optimalRatio = $widthRatio;
}
$optimalHeight = $this->height / $optimalRatio;
$optimalWidth = $this->width / $optimalRatio;
return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
}
private function crop($optimalWidth, $optimalHeight, $newWidth, $newHeight) {
// *** Find center - this will be used for the crop
$optionArray["cropStartX"] = ( $optimalWidth / 2) - ( $newWidth /2 );
$optionArray["cropStartY"] = ( $optimalHeight/ 2) - ( $newHeight/2 );
return $optionArray;
}
public function resizeImage($options=array()) {
$imageCrop = ((isset($options["imageCrop"])) && (!empty($options["imageCrop"]))) ? $options["imageCrop"] : "landscape";
$this->width = ((isset($options["origWidth"])) && (!empty($options["origWidth"]))) ? $options["origWidth"] : 0;
$this->height = ((isset($options["origHeight"])) && (!empty($options["origHeight"]))) ? $options["origHeight"] : 0;
$newWidth = ((isset($options["imageWidth"])) && (!empty($options["imageWidth"]))) ? $options["imageWidth"] : 0;
$newHeight = ((isset($options["imageHeight"])) && (!empty($options["imageHeight"]))) ? $options["imageHeight"] : 0;
if ((empty($newHeight)) && ($imageCrop == "square")) {
$newHeight = $newWidth;
}
// *** Get optimal width and height - based on $option
$optionArray = $this->getDimensions($newWidth, $newHeight, $imageCrop);
if ($imageCrop == 'square') {
$tempOptions = $this->crop($optionArray["optimalWidth"], $optionArray["optimalHeight"], $newWidth, $newHeight);
$optionArray["cropStartX"] = $tempOptions["cropStartX"];
$optionArray["cropStartY"] = $tempOptions["cropStartY"];
}
$optionArray["CanvasWidth"] = $newWidth;
$optionArray["CanvasHeight"] = (!empty($newHeight)) ? $newHeight : $optionArray["optimalHeight"];
return $optionArray;
}
function showImage($options=array()) {
global $documentRoot, $imageFolder;
$imageSize = ((isset($options["imageSize"])) && (!empty($options["imageSize"]))) ? $options["imageSize"] : "";
$imageCrop = ((isset($options["imageCrop"])) && (!empty($options["imageCrop"]))) ? $options["imageCrop"] : "";
$imageType = ((isset($options["imageType"])) && (!empty($options["imageType"]))) ? $options["imageType"] : "";
$imageName = ((isset($options["imageName"])) && (!empty($options["imageName"]))) ? $options["imageName"] : "";
$imageModify = ((isset($options["imageModify"])) && (!empty($options["imageModify"]))) ? $options["imageModify"] : "";
$imageQuality = ((isset($options["imageQuality"])) && (!empty($options["imageQuality"]))) ? $options["imageQuality"] : 100;
$imageFolder = ((isset($options["imageFolder"])) && (!empty($options["imageFolder"]))) ? $options["imageFolder"] : $imageFolder;
if (($imageType) || ($imageSize) || ($imageCrop)) {
if ((!empty($imageSize)) && (!empty($imageType))) {
$imageSize .= ucfirst($imageType);
} else if ((empty($imageSize)) && (!empty($imageType))) {
$imageSize .= strtolower($imageType);
}
$imageSize .= (!empty($imageCrop)) ? ucfirst($imageCrop) : "";
$tempWidth = lcfirst($imageSize . "W");
$tempHeight = lcfirst($imageSize . "H");
global $$tempWidth, $$tempHeight;
$maxWidth = isset($$tempWidth) ? $$tempWidth : 0;
$maxHeight = isset($$tempHeight) ? $$tempHeight : 0;
}
if (empty($maxWidth)) {
$tempWidth = "maxImageW";
$tempHeight = "maxImageH";
global $$tempWidth, $$tempHeight;
$maxWidth = isset($$tempWidth) ? $$tempWidth : 0;
$maxHeight = isset($$tempHeight) ? $$tempHeight : 0;
}
if (empty($this->imageID)) {
$searchArray = array("imageName"=>$imageName);
$functionArray = array("searchArray"=>$searchArray);
$this->imageID = $this->returnImageID($functionArray);
}
$imageData = $this->getImageInfo();
if (is_array($imageData)) {
$imageName = $imageData["ImageName"];
$width = $imageData["ImageWidth"];
$height = $imageData["ImageHeight"];
$imageType = $imageData["ImageType"];
} else {
$imageType = "";
}
$functionArray = array("imageName"=>$imageName,"imageType"=>$imageType);
$imageTypeInfo = $this->returnImageType($functionArray);
$tempImageType = $imageTypeInfo["imageType"];
$tempImageExt = $imageTypeInfo["imageExt"];
$thisImage = $documentRoot . $imageFolder . $imageName;
if (file_exists($thisImage)) {
if ((empty($width)) || (empty($height))) {
$row = getimagesize($thisImage);
$width = $row[0];
$height = $row[1];
}
if ((isset($maxWidth)) && (($width > $maxWidth) || ($height > $maxHeight))) {
$functiontoRun = "imagecreatefrom" . $tempImageType;
$this->image = $functiontoRun($thisImage);
if (!$this->image) {
$this->image = imagecreatefromjpeg($thisImage);
}
$functionArray = array("imageCrop"=>$imageCrop,"origWidth"=>$width,"origHeight"=>$height,"imageWidth"=>$maxWidth,"imageHeight"=>$maxHeight);
$resizeImage = $this->resizeImage($functionArray);
$optimalWidth = $resizeImage['optimalWidth'];
$optimalHeight = $resizeImage['optimalHeight'];
$canvasWidth = $resizeImage["CanvasWidth"];
$canvasHeight = $resizeImage["CanvasHeight"];
$cropStartX = isset($resizeImage["cropStartX"]) ? $resizeImage["cropStartX"] : 0;
$cropStartY = isset($resizeImage["cropStartY"]) ? $resizeImage["cropStartY"] : 0;
// *** Resample - create image canvas of x, y size
$this->imageResized = imagecreatetruecolor($optimalWidth, $optimalHeight);
$background = imagecolorallocate($this->imageResized, 255, 255, 255);
imagefill ($this->imageResized, 0, 0, $background);
imagecopyresampled($this->imageResized, $this->image, 0, 0, 0, 0, $optimalWidth, $optimalHeight, $this->width, $this->height);
// *** if option is 'crop', then crop too
if ($imageCrop == 'square') {
$crop = $this->imageResized;
//imagedestroy($this->imageResized);
// *** Now crop from center to exact requested size
$this->imageResized = imagecreatetruecolor($canvasWidth , $canvasHeight);
imagecopyresampled($this->imageResized, $crop , 0, 0, $cropStartX, $cropStartY, $canvasWidth, $canvasHeight , $canvasWidth, $canvasHeight);
}
if ($imageModify == "grey") {
imagefilter($this->imageResized, IMG_FILTER_GRAYSCALE);
}
header("Content-type: image/$tempImageType");
imagejpeg($this->imageResized, "", $imageQuality);
exit();
} else {
header("Content-type: image/$tempImageType");
$image = imagecreatefromjpeg($thisImage);
imagejpeg($image);
exit();
}
}
else {
header("HTTP/1.0 404 Not Found");
exit();
}
}
private function grayscale($r, $g, $b) {
return (($r*0.299)+($g*0.587)+($b*0.114));
}
function returnImageID($options=array()) {
$imageID = 0;
$query = $this->buildImageQuery($options);
$result = RunQuery($query,__LINE__);
if (mysql_num_rows($result) != 0) {
$row = mysql_fetch_assoc($result);
$imageID = $row["ImageID"];
}
return $imageID;
}
function returnImageIndex($options=array()) {
$imageIndex = 0;
$query = $this->buildImageQuery($options);
$result = RunQuery($query,__LINE__);
if (mysql_num_rows($result) != 0) {
$row = mysql_fetch_assoc($result);
$imageIndex = $row["ImageIndex"];
}
return $imageIndex;
}
private function getImageInfo() {
$query = "SELECT ImageID, ImageName, ImageWidth, ImageHeight, ImageType, Catalogue, CatalogueID, ImageCaption, ImageIndex FROM Images i ";
$query .= "WHERE ImageID= '%s' ";
$query = sprintf($query, mysql_real_escape_string($this->imageID));
$result = RunQuery($query,__LINE__);
if (mysql_num_rows($result) != 0) {
return mysql_fetch_assoc($result);
}
}
}
?>
While you state:
I am trying to fix/debug a site where all images in the site are being
generated by an script.
Looking at this chunk of code implies that the images for the site are actually stored in the file system in some way via that file_exists() check:
$thisImage = $documentRoot . $imageFolder . $imageName;
if (file_exists($thisImage)) {
if ((empty($width)) || (empty($height))) {
$row = getimagesize($thisImage);
$width = $row[0];
$height = $row[1];
}
if ((isset($maxWidth)) && (($width > $maxWidth) || ($height > $maxHeight))) {
$functiontoRun = "imagecreatefrom" . $tempImageType;
$this->image = $functiontoRun($thisImage);
if (!$this->image) {
$this->image = imagecreatefromjpeg($thisImage);
}
Also, looking at the tons of repetitive code coupled with this odd set of if ( checks I would concentrate on the code around function showImage($options=array()) {.
Now responding to your comment where you tell us what the site is & the fact the images are not loading.
Loading a URL like this:
http://www.mysticindia.co.uk/images/galleries/small/square/JCxTPFAsMGBgCmA.jpg
Shows an error—I assume that comes from your debugging—like this:
_image.phpA: Resource id #11 Warning: imagejpeg(JC0jQFgsMGBgCmA.jpg): failed to open stream: Permission denied in /var/www/vhosts/mysticindia.co.uk/httpdocs/inc/class.images.php on line 496
The failed to open stream tells me that while you are saying the images are being generated by the script, file system interaction is clearly happening at some point.
Then this error of:
Permission denied in /var/www/vhosts/mysticindia.co.uk/httpdocs/inc/class.images.php on line 496
Seems to tell me the error is not in your code, but in the file system permissions. It seems that the script is indeed generating derivative thumbnails & other versions of the parent image. But at some point the script is caching them to the file system in some way. Unclear where the source images come from—a BLOB in the database—but my best advice right now is to look at the file system permissions for the site & see if anything changed.
I mean you—or others—didn’t screw around with this script yet it stopped working right? I bet you anything that the directory this script uses to cache derivatives no longer exists or has incorrect ownership or permissions. Something like that would choke this process.
I want to be able to upload an MS word document and export it a page in my site.
Is there any way to accomplish this?
//FUNCTION :: read a docx file and return the string
function readDocx($filePath) {
// Create new ZIP archive
$zip = new ZipArchive;
$dataFile = 'word/document.xml';
// Open received archive file
if (true === $zip->open($filePath)) {
// If done, search for the data file in the archive
if (($index = $zip->locateName($dataFile)) !== false) {
// If found, read it to the string
$data = $zip->getFromIndex($index);
// Close archive file
$zip->close();
// Load XML from a string
// Skip errors and warnings
$xml = DOMDocument::loadXML($data, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
// Return data without XML formatting tags
$contents = explode('\n',strip_tags($xml->saveXML()));
$text = '';
foreach($contents as $i=>$content) {
$text .= $contents[$i];
}
return $text;
}
$zip->close();
}
// In case of failure return empty string
return "";
}
ZipArchive and DOMDocument are both inside PHP so you don't need to install/include/require additional libraries.
One may use PHPDocX.
It has support for practically all HTML CSS styles. Moreover you may use templates to add extra formatting to your HTML via the replaceTemplateVariableByHTML.
The HTML methods of PHPDocX also allow for the direct use of Word styles. You may use something like this:
$docx->embedHTML($myHTML, array('tableStyle' => 'MediumGrid3-accent5PHPDOCX'));
If you want that all your tables use the MediumGrid3-accent5 Word style. The embedHTML method as well as its version for templates (replaceTemplateVariableByHTML) preserve inheritance, meaning by that that you may use a predefined Word style and override with CSS any of its properties.
You may also extract selected parts of your HTML using 'JQuery type' selectors.
You can convert Word docx documents to html using Print2flash library. Here is an PHP excerpt from my client's site which converts a document to html:
include("const.php");
$p2fServ = new COM("Print2Flash4.Server2");
$p2fServ->DefaultProfile->DocumentType=HTML5;
$p2fServ->ConvertFile($wordfile,$htmlFile);
It converts a document which path is specified in $wordfile variable to a html page file specified by $htmlFile variable. All formatting, hyperlinks and charts are retained. You can get the required const.php file altogether with a fuller sample from Print2flash SDK.
this is a workaround based on David Lin's answer above
removing "w:" in a docx's xml tags leave behing Html like tags
function readDocx($filePath) {
// Create new ZIP archive
$zip = new ZipArchive;
$dataFile = 'word/document.xml';
// Open received archive file
if (true === $zip->open($filePath)) {
// If done, search for the data file in the archive
if (($index = $zip->locateName($dataFile)) !== false) {
// If found, read it to the string
$data = $zip->getFromIndex($index);
// Close archive file
$zip->close();
// Load XML from a string
// Skip errors and warnings
$xml = new DOMDocument("1.0", "utf-8");
$xml->loadXML($data, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING|LIBXML_PARSEHUGE);
$xml->encoding = "utf-8";
// Return data without XML formatting tags
$output = $xml->saveXML();
$output = str_replace("w:","",$output);
return $output;
}
$zip->close();
}
// In case of failure return empty string
return "";
}
Ok Im in very late, but thought I'd post this to save you all some time.
This is some php code I have put together not just to read the text from docx but the images too, currently it does not support floating images / text, but what I have done so far is a massive move forwards to whats already been posted on here - note you need to update https://example.co.uk to YOUR domain name.
<?php
class Docx_ws_imglnk {
public $originalpath = '';
public $extractedpath = '';
}
class Docx_ws_rel {
public $Id = '';
public $Target = '';
}
class Docx_ws_def {
public $styleId = '';
public $type = '';
public $color = '000000';
}
class Docx_p_def {
public $data = array();
public $text = "";
}
class Docx_p_item {
public $name = "";
public $value = "";
public $innerstyle = "";
public $type = "text";
}
class Docx_reader {
private $fileData = false;
private $errors = array();
public $rels = array();
public $imglnks = array();
public $styles = array();
public $document = null;
public $paragraphs = array();
public $path = '';
private $saveimgpath = 'docimages';
public function __construct() {
}
private function load($file) {
if (file_exists($file)) {
$zip = new ZipArchive();
$openedZip = $zip->open($file);
if ($openedZip === true) {
$this->path = $file;
//read and save images
for ( $i = 0; $i < $zip->numFiles; $i ++ ) {
$zip_element = $zip->statIndex( $i );
if ( preg_match( "([^\s]+(\.(?i)(jpg|jpeg|png|gif|bmp))$)", $zip_element['name'] ) ) {
$imglnk = new Docx_ws_imglnk;
$imglnk->originalpath = $zip_element['name'];
$imagename = explode( '/', $zip_element['name'] );
$imagename = end( $imagename );
$imglnk->extractedpath = dirname( __FILE__ ) . '/' . $this->savepath . $imagename;
$putres = file_put_contents( $imglnk->extractedpath, $zip->getFromIndex( $i ));
$imglnk->extractedpath = str_replace('var/www/', 'https://example.co.uk/', $imglnk->extractedpath);
$imglnk->extractedpath = substr($imglnk->extractedpath, 1);
array_push($this->imglnks, $imglnk);
}
}
//read relationships
if (($styleIndex = $zip->locateName('word/_rels/document.xml.rels')) !== false) {
$stylesRels = $zip->getFromIndex($styleIndex);
$xml = simplexml_load_string($stylesRels);
$XMLTEXT = $xml->saveXML();
$doc = new DOMDocument();
$doc->loadXML($XMLTEXT);
foreach($doc->documentElement->childNodes as $childnode)
{
$nodename = $childnode->nodeName;
if($childnode->hasAttributes())
{
$rel = new Docx_ws_rel;
for ($a = 0; $a < $childnode->attributes->count(); $a++)
{
$attrNode = $childnode->attributes->item($a);
if (strcmp( $attrNode->nodeName, 'Id') == 0)
{
$rel->Id = $attrNode->nodeValue;
}
if (strcmp( $attrNode->nodeName, 'Target') == 0)
{
$rel->Target = $attrNode->nodeValue;
}
}
array_push($this->rels, $rel);
}
}
}
//attempt to load styles:
if (($styleIndex = $zip->locateName('word/styles.xml')) !== false) {
$stylesXml = $zip->getFromIndex($styleIndex);
$xml = simplexml_load_string($stylesXml);
$XMLTEXT = $xml->saveXML();
$doc = new DOMDocument();
$doc->loadXML($XMLTEXT);
foreach($doc->documentElement->childNodes as $childnode)
{
$nodename = $childnode->nodeName;
//get style
if (strcmp($nodename, "w:style") == 0)
{
$ws_def = new Docx_ws_def;
for ($a=0; $a < $childnode->attributes->count(); $a++ )
{
$item = $childnode->attributes->item($a);
//style id
if (strcmp($item->nodeName, "w:styleId") == 0)
{
$ws_def->styleId = $item->nodeValue;
}
//style type
if (strcmp($item->nodeName, "w:type") == 0)
{
$ws_def->type = $item->nodeValue;
}
}
}
//push style to the array of styles
if (strcmp($ws_def->styleId, "") != 0 && strcmp($ws_def->type, "") != 0)
{
array_push($this->styles, $ws_def);
}
}
}
if (($index = $zip->locateName('word/document.xml')) !== false) {
$stylesDoc = $zip->getFromIndex($index);
$xml = simplexml_load_string($stylesDoc);
$XMLTEXT = $xml->saveXML();
$this->document = new DOMDocument();
$this->document->loadXML($XMLTEXT);
}
$zip->close();
} else {
switch($openedZip) {
case ZipArchive::ER_EXISTS:
$this->errors[] = 'File exists.';
break;
case ZipArchive::ER_INCONS:
$this->errors[] = 'Inconsistent zip file.';
break;
case ZipArchive::ER_MEMORY:
$this->errors[] = 'Malloc failure.';
break;
case ZipArchive::ER_NOENT:
$this->errors[] = 'No such file.';
break;
case ZipArchive::ER_NOZIP:
$this->errors[] = 'File is not a zip archive.';
break;
case ZipArchive::ER_OPEN:
$this->errors[] = 'Could not open file.';
break;
case ZipArchive::ER_READ:
$this->errors[] = 'Read error.';
break;
case ZipArchive::ER_SEEK:
$this->errors[] = 'Seek error.';
break;
}
}
} else {
$this->errors[] = 'File does not exist.';
}
}
public function setFile($path) {
$this->fileData = $this->load($path);
}
public function to_plain_text() {
if ($this->fileData) {
return strip_tags($this->fileData);
} else {
return false;
}
}
public function processDocument() {
$html = '';
foreach($this->document->documentElement->childNodes as $childnode)
{
$nodename = $childnode->nodeName;
//get the body of the document
if (strcmp($nodename, "w:body") == 0)
{
foreach($childnode->childNodes as $subchildnode)
{
$pnodename = $subchildnode->nodeName;
//process every paragraph
if (strcmp($pnodename, "w:p") == 0)
{
$pdef = new Docx_p_def;
foreach($subchildnode->childNodes as $pchildnode)
{
//process any inner children
if (strcmp($pchildnode, "w:pPr") == 0)
{
foreach($pchildnode->childNodes as $prchildnode)
{
//process text alignment
if (strcmp($prchildnode->nodeName, "w:pStyle") == 0)
{
$pitem = new Docx_p_item;
$pitem->name = 'styleId';
$pitem->value = $prchildnode->attributes->getNamedItem('val')->nodeValue;
array_push($pdef->data, $pitem);
}
//process text alignment
if (strcmp($prchildnode->nodeName, "w:jc") == 0)
{
$pitem = new Docx_p_item;
$pitem->name = 'align';
$pitem->value = $prchildnode->attributes->getNamedItem('val')->nodeValue;
if (strcmp($pitem->value, "left") == 0)
{
$pitem->innerstyle .= "text-align:" . $pitem->value . ";";
}
if (strcmp($pitem->value, "center") == 0)
{
$pitem->innerstyle .= "text-align:" . $pitem->value . ";";
}
if (strcmp($pitem->value, "right") == 0)
{
$pitem->innerstyle .= "text-align:" . $pitem->value . ";";
}
if (strcmp($pitem->value, "both") == 0)
{
$pitem->innerstyle .= "word-spacing:" . 10 . "px;";
}
array_push($pdef->data, $pitem);
}
//process drawing
if (strcmp($prchildnode->nodeName, "w:drawing") == 0)
{
$pitem = new Docx_p_item;
$pitem->name = 'drawing';
$pitem->value = '';
$pitem->type = 'graphic';
$extents = $prchildnode->getElementsByTagName('extent')[0];
$cx = $extents->attributes->getNamedItem('cx')->nodeValue;
$cy = $extents->attributes->getNamedItem('cy')->nodeValue;
$pcx = (int)$cx / 9525;
$pcy = (int)$cy / 9525;
$pitem->innerstyle .= "width:" . $pcx . "px;";
$pitem->innerstyle .= "height:" . $pcy . "px;";
$blip = $prchildnode->getElementsByTagName('blip')[0];
$pitem->value = $blip->attributes->getNamedItem('embed')->nodeValue;
array_push($pdef->data, $pitem);
}
//process spacing
if (strcmp($prchildnode->nodeName, "w:spacing") == 0)
{
$pitem = new Docx_p_item;
$pitem->name = 'paragraphSpacing';
$bval = $prchildnode->attributes->getNamedItem('before')->nodeValue;
if (strcmp($bval, '') == 0)
$bval = 0;
$pitem->innerstyle .= "padding-top:" . $bval . "px;";
$aval = $prchildnode->attributes->getNamedItem('after')->nodeValue;
if (strcmp($aval, '') == 0)
$aval = 0;
$pitem->innerstyle .= "padding-bottom:" . $aval . "px;";
array_push($pdef->data, $pitem);
}
}
}
if (strcmp($pchildnode, "w:r") == 0)
{
foreach($pchildnode->childNodes as $rchildnode)
{
//process text
if (strcmp($rchildnode->nodeName, "w:t") == 0)
{
$pdef->text .= $rchildnode->nodeValue;
if (count($pdef->data) == 0)
{
$pitem = new Docx_p_item;
$pitem->name = 'styleId';
$pitem->value = '';
array_push($pdef->data, $pitem);
}
}
if (strcmp($rchildnode->nodeName, "w:rPr") == 0)
{
foreach($rchildnode->childNodes as $rPrchildnode)
{
if (strcmp($rPrchildnode->nodeName, "w:b") == 0 )
{
$pitem = new Docx_p_item;
$pitem->name = 'textBold';
$pitem->value = '';
$pitem->innerstyle .= "text-weight: 500;";
array_push($pdef->data, $pitem);
}
if (strcmp($rPrchildnode->nodeName, "w:i") == 0 )
{
$pitem = new Docx_p_item;
$pitem->name = 'textItalic';
$pitem->value = '';
$pitem->innerstyle .= "text-style: italic;";
array_push($pdef->data, $pitem);
}
if (strcmp($rPrchildnode->nodeName, "w:u") == 0 )
{
$pitem = new Docx_p_item;
$pitem->name = 'textUnderline';
$pitem->value = '';
$pitem->innerstyle .= "text-decoration: underline;";
array_push($pdef->data, $pitem);
}
if (strcmp($rPrchildnode->nodeName, "w:sz") == 0 )
{
$pitem = new Docx_p_item;
$pitem->name = 'textSize';
$sz = $rPrchildnode->attributes->getNamedItem('val')->nodeValue;
if ($sz == '')
{
$sz=0;
}
$pitem->value = $sz;
array_push($pdef->data, $pitem);
}
}
}
}
}
}
array_push($this->paragraphs, $pdef);
}
}
}
}
}
public function to_html()
{
$html = '';
foreach($this->paragraphs as $para)
{
$styleselect = null;
$type = 'text';
$content = $para->text;
$sz = 0;
$extent = '';
$embedid = '';
$pinnerstylesid = '';
$pinnerstylesunderline = '';
$pinnerstylessz = '';
if (count($para->data) > 0)
{
foreach($para->data as $node)
{
if (strcmp($node->name, "styleId") == 0)
{
$type = $node->type;
$pinnerstylesid = $node->innerstyle;
foreach($this->styles as $style)
{
if (strcmp ($node->value, $style->styleId) == 0)
{
$styleselect = $style;
}
}
}
if (strcmp($node->name, "align") == 0)
{
$pinnerstylesid .= $node->innerstyle. ";";
}
if (strcmp($node->name, "drawing") == 0)
{
$type = $node->type;
$extent = $node->innerstyle;
$embedid = $node->value;
}
if (strcmp($node->name, "textSize") == 0)
{
$sz = $node->value;
}
if (strcmp($node->name, "textUnderline") == 0)
{
$pinnerstylesunderline = $node->innerstyle;
}
}
}
if (strcmp($type, 'text') == 0)
{
//echo "has valid para";
//echo "<br>";
if ($styleselect != null)
{
//echo "has valid style";
//echo "<br>";
if (strcmp($styleselect->color, '') != 0)
{
$pinnerstylesid .= "color:#" . $styleselect->color. ";";
}
}
if ($sz != 0)
{
$pinnerstylesid .= 'font-size:' . $sz . 'px;';
//echo "sz<br>";
}
$span = "<p style='". $pinnerstylesid . $pinnerstylesunderline ."'>";
$span .= $content;
$span .= "</p>";
//echo $span;
$html .= $span;
}
if (strcmp($type, 'graphic') == 0)
{
$imglnk = '';
foreach($this->rels as $rel)
{
if(strcmp($embedid, '') != 0 && strcmp($rel->Id, $embedid) == 0)
{
foreach($this->imglnks as $imgpathdef)
{
if (strpos($imgpathdef->extractedpath, $rel->Target) >= 0)
{
$imglnk = $imgpathdef->extractedpath;
//echo "has img link<br>";
//echo $imglnk . "<br>";
}
}
}
}
if ($styleselect != null)
{
//echo "has valid style";
//echo "<br>";
if (strcmp($styleselect->color, '') != 0)
{
$pinnerstylesid .= "color:#" . $styleselect->color. ";";
}
}
if ($sz != 0)
{
$pinnerstylesid .= 'font-size:' . $sz . 'px;';
//echo "sz<br>";
}
$span = "<p style='". $pinnerstylesid . $pinnerstylesunderline ."'>";
$span .= "<img style='". $extent ."' alt='image coming soon' src ='". $imglnk ."'/>";
$span .= "</p>";
//echo $span;
$html .= $span;
}
}
return $html;
}
public function get_errors() {
return $this->errors;
}
private function getStyles() {
}
}
function getDocX($path)
{
//echo $path;
$doc = new Docx_reader();
$doc->setFile($path);
if(!$doc->get_errors()) {
$doc->processDocument();
$html = $doc->to_html();
echo $html;
}
return "";
}
?>