High CPU consumption by a PHP script - php

My hosting service provider has disabled my account 2 times due to one of my image resizing PHP scripts. The script is lead-img, which is pasted here:
include ("videothumb.php");
function amty_lead_img($w='',$h='',$constrain='',$img='',$percent='',$zc='',$post_id = '',
$img_url_only = 'y',$show_default = 'y',$default_img = '') {
if($img == ''){
if($post_id == ''){
global $id;
$img = amty_take_first_img_by_id($id);
}
else
$img = amty_take_first_img_by_id($post_id);
}
if($img =='' && $show_default != 'y'){
$img_url = $img;
}else{
if($img =='' && $show_default == 'y'){
if($default_img != '')
$img = $default_img;
else
$img = WP_PLUGIN_URL . "/amtythumb/amtytextthumb.gif";
}
if($constrain != '')
$constrain='constrain='. $constrain . '&';
if($h != '')
$h='h='. $h . '&';
if($w != '')
$w='w='. $w . '&';
if($zc != '')
$zc='zc='. $zc . '&';
if($percent != '')
$percent='percent='. $percent . '&';
$img_url = WP_PLUGIN_URL . "/amtythumb/scripts/imgsize.php?".$zc."". $percent."".$constrain."" . $w ."" . $h ."&img=" . $img ;
}
if($img_url_only == "y"){
$out = $img_url;
}else{
$out = '<img src="'.$img_url.'" />';
}
//echo $out;
return $out;
}//function end
function amty_take_first_img_by_id($id) {
$temp = $wp_query; // assign orginal query to temp variable for later use
$wp_query = null;
global $wpdb;
$img='';
$attach_img='';
$uploaded_img = '';
$image_data = $wpdb->get_results("SELECT guid, post_content, post_mime_type, post_title FROM wp_posts WHERE id = $id");
$match_count = preg_match_all("/<img[^']*?src=\"([^']*?)\"[^']*?\/?>/", $image_data[0]->post_content, $match_array, PREG_PATTERN_ORDER);
if($match_count == 0){
/*$match_count = preg_match_all("/<img[^']*?src=\"([^']*?)\"[^']*?>/", $image_data[1]->post_content, $match_array, PREG_PATTERN_ORDER);
if($match_count == 0){
$match_count = preg_match_all("/<img[^>]+>/i", $image_data[1]->post_content, $match_array, PREG_PATTERN_ORDER);
if($match_count == 0)
$match_count = preg_match_all("/<img[^']*?src=\"([^']*?)\"[^']*?\/>/", $image_data[0]->post_content, $match_array, PREG_PATTERN_ORDER);
if($match_count == 0){*/
$img = thumb($image_data[0]->post_content);
/*}
}*/
}
if( $img == '') $img = $match_array[1][0];
$attach_img = amty_get_firstimage($output->guid);
$first_image_data = array ($image_data[0]);
foreach($first_image_data as $output) {
if (substr($output->post_mime_type, 0, 5) == 'image'){
$uploaded_img = $output->guid;
break;
}
}
$wp_query = $temp;
if( $img != '') return $img;
if( $attach_img != '') return $attach_img;
if( $uploaded_img != '') return $uploaded_img;
return '';
}
//get First attached image
function amty_get_firstimage($post_id='', $size='thumbnail') {
$id = (int) $post_id;
$args = array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'numberposts' => 1,
'order' => 'ASC',
'orderby' => 'menu_order ID',
'post_status' => null,
'post_parent' => $id
);
$attachments = get_posts($args);
if ($attachments) {
$img = wp_get_attachment_image_src($attachments[0]->ID, $size);
return $img[0];
}else{
return '';
}
}
?>
This script is calling another script "videothumb.php" for accessing image for a video url from respective site and to resizing it.
I am not able to figure out anything wrong with the script. I checked the log to ensure how many times it was called etc. But everything seems normal.
Can someone guide me which part of script can slow down the CPU or can increase server load?

Related

Joomla 3. Set first image of article as intro image [duplicate]

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!

Auto Photo Albums in codeigniter

I have used Auto Photo Albums – Multi Level Image Grid for integration of my gallery in my website, it is easily integrated in core PHP but when am using codeigniter frame work for integration of this plugin am unable to get the images
The plugin consists of three files with a directory
reader.php
gallery.html
Reader.php
<?php
//CONFIGURATION
$imgTypes = array('jpeg', 'jpg', 'png', 'gif'); // The extensions of Images that the plugin will read
$imagesOrder = $_GET['imagesOrder']; //byDate, byDateReverse, byName, byNameReverse, random
$folderCoverRandom = $_GET['folderCoverRandom'];
$albumsOrder = $_GET['albumsOrder'];
function getList ($directory, $type='none') {
global $imgTypes;
global $imagesOrder;
global $albumsOrder;
$order = $imagesOrder;
if($type == 'albums'){
$order = $albumsOrder;
}
if( !is_dir($directory)){
return array();
}
$results = array();
$handler = opendir($directory);
while ($file = readdir($handler)) {
if ($file != "." && $file != ".." && $file != ".DS_Store" && $file != "#eaDir") {
$extension = preg_split('/\./',$file);
$extension = strtolower($extension[count($extension)-1]);
if($type == 'none'){
//do nothing
}else if($type == 'albums'){
if( !is_dir($directory.'/'.$file) ){
continue;
}
}else if($type == 'images'){
if( is_dir($directory.'/'.$file) ){
continue;
}
}
if( (array_search($extension,$imgTypes) !== FALSE || is_dir($directory.'/'.$file)) && $file != "thumbnails" ){
$ctime = filemtime($directory .'/'. $file) . ',' . $file; //BRING THE DATE OF THE IMAGE
if($order == 'byName' || $order == 'byNameReverse'){
$ctime = $file;
}
$results[$ctime] = $file;
}
}
}
closedir($handler);
if($order == 'byDate' || $order == 'byNameReverse'){
krsort($results);
}else if($order == 'byDateReverse' || $order == 'byName'){
ksort($results);
}else if($order == 'random'){
shuffle($results);
}
return $results;
}
function fixArray($list, $directory){
global $folderCoverRandom;
$return = array();
foreach ($list as $key => $value) {
$val = "";
if( is_dir($directory.'/'.$value) ){
$val = "folder";
$arr = getList($directory.'/'.$value);
$folderImg = "";
$folderImgCover = "";
$thumb = 'no';
$numImg = 0;
$numFolders = 0;
foreach ($arr as $key2 => $value2) {
if( is_dir( $directory.'/'.$value.'/'.$value2) ){//IF IT IS A FOLDER
$numFolders++;
}else{//IF IT IS AN IMAGE
//PICK THE FIRST IMAGES FROM THE FOLDER TO USE IT AS COVER IMAGE
if( $folderImg == "" ){
$folderImg = $value2;
if( file_exists( $directory.'/'.$value.'/thumbnails'.'/'.$value2 ) ){//VERIFY IF THERE IS ANY THUMBNAIL FOR THE IMAGE
$thumb = 'yes';
}
}
//VERIFY IF THERE IS ANY "folderCover" IMAGE IN THE FOLDER SO WE CAN USE IT AS COVER IMAGE
$arrName = preg_split('/\.(?=[^.]*$)/',$value2);
$imgName = $arrName[0];
if( $folderImgCover == "" && $imgName == "folderCover" ){
$folderImgCover = $value2;
}
if($imgName != "folderCover"){
$numImg++;
}
}
}
//PICK A RANDOM IMAGES FROM THE FOLDER TO USE IT AS RANDOM IMAGE
if($folderCoverRandom == 'true'){
$rand = rand(0,$numImg-1);
$cont = 0;
foreach ($arr as $key2 => $value2) {
if( is_dir( $directory.'/'.$value.'/'.$value2) ){//IF IT IS A FOLDER
// DO NOTHING
}else{//IF IT IS AN IMAGE
if($cont == $rand){
$folderImg = $value2;
if( file_exists( $directory.'/'.$value.'/thumbnails'.'/'.$value2 ) ){//VERIFY IF THERE IS ANY THUMBNAIL FOR THE IMAGE
$thumb = 'yes';
}
}
$cont++;
}
}
}
//IF THERE IS A COVER IMAGE INSIDE THE FOLDER THEN USE IT!
if( $folderImgCover != "" ){
$folderImg = $folderImgCover;
$thumb = "no";
}
$val = array('numImages' => $numImg, 'numFolders' => $numFolders, 'image' => $folderImg, 'thumb' => $thumb);
}else{
$thumb = 'no';
if( file_exists( $directory.'/thumbnails'.'/'.$value ) ){//VERIFY IF THERE IS ANY THUMBNAIL FOR THE IMAGE
$thumb = 'yes';
}
$val = $thumb;
}
$return[$value] = $val;
}
return $return;
}
$directory = $_GET['directory'];
//THE RESULT OF THE JSON CALL
$output = array();
$list = array();
if($albumsOrder != 'none'){//Apply a different order to the folders
$albums = getList($directory, 'albums');
$images = getList($directory, 'images');
$list = $albums + $images;
}else{
//GET LIST OF IMAGES AND FOLDERS
$list = getList($directory);
}
$output = fixArray($list, $directory);
// print_r($output);
//echo json_encode($output, JSON_FORCE_OBJECT); // if you are using PHP 5.3 plase use this line instead of the one below
echo json_encode($output);
?>
Gallery.html
<div class="container-fluid">
<div id="grid" data-directory="Gallery"></div>
</div>
All the images are loaded into the directory i,e Gallery Folder the images are retrieved into the page by using the reader file
When i have integrated the same files in codeigniter the are images are unable to load
I have created reader.php as a library and i have called it in the controller but it shows error
Undefined index: imagesOrder
Undefined index: folderCoverRandom
Undefined index: directory
Gallery Output :http://www.davidbo.dreamhosters.com/plugins/AutoAlbums/plugin/index2.html
Plugin : https://codecanyon.net/item/auto-photo-albums-multi-level-image-grid/5319229
Please help me out how can i integrate this to codeigniter

how to execute multi requete pdo mysql

i don't know how execute multi requete sql
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_SESSION['pseudo']) && !empty($_SESSION['pseudo']) && isset($_SESSION['user_id']) && !empty($_SESSION['user_id'])) {
$id = trim(htmlspecialchars($_SESSION['user_id']));
$pseudo = trim(htmlspecialchars($_SESSION['pseudo']));
$stmt->$connect->prepare('SELECT id,pseudo,jeton FROM users WHERE id=:id AND pseudo=:pseudo');
$stmt->execute(array(
':id' => $id,
':pseudo' => $pseudo
));
$row = $stmt->fetch();
if ($_SESSION['pseudo'] == $row['pseudo'] && $_SESSION['user_id'] == $row['id']) {
// Files Image profil
$avatarName = $_FILES['avatarCouverture']['name'];
$avatarTmp = $_FILES['avatarCouverture']['tmp_name'];
$avatarSize = $_FILES['avatarCouverture']['size'];
$avatarType = $_FILES['avatarCouverture']['type'];
$extension = array(
'jpg',
'jpeg',
'png'
);
$avatarExplode = explode('.', $avatarName);
$avatarEnd = end($avatarExplode);
$avatarLower = strtolower($avatarEnd);
$saveIdUser = trim(htmlspecialchars($_SESSION['user_id']));
$saveIdUserNew = filter_var($saveIdUser, FILTER_SANITIZE_NUMBER_INT);
$avatar = rand(0, 100000) . '_' . date('Y-m-d H-i-s') . '_' . $saveIdUserNew;
if (isset($avatarName) && !empty($avatarName)) {
if ($avatarSize < 8000000) {
if (in_array($avatarLower, $extension)) {
if (isset($avatarTmp) && !empty($avatarTmp)) {
$image = getimagesize($avatarTmp);
if ($image['mime'] === 'image/jpeg') {
$imageSrc = imagecreatefromjpeg($avatarTmp);
} elseif ($image['mime'] === 'image/png') {
$imageSrc = imagecreatefrompng($avatarTmp);
} else {
$imageSrc = false;
}
// modifier size image
if ($imageSrc !== false) {
$imageWidth = 60;
$imageHeight = 60;
if ($image[0] >= $imageWidth && $image[1] >= $imageHeight) {
$imageFinale = $imageSrc;
} else {
$newWidth[0] = $imageWidth;
$newHeight[1] = $imageHeight;
$imageFinale = imagecreatetruecolor($newWidth[0], $newHeight[1]);
imagecopyresampled($imageFinale, $imageSrc, 0, 0, 0, 0, $newWidth[0], $newHeight[1], $image[0], $image[1]);
}
$target = imagejpeg($imageFinale, 'upload/avatarPost/' . $avatar . '.jpg');
move_uploaded_file($avatarTmp, $target);
} // ! == false
}
}
}
}
$stmt = $connect->prepare('INSERT INTO users(avatarcouverture) VALUES(:avatarne) ');
$stmt->execute(array(
":avatarne" => $avatar
));
//header('Location: profil.php');
}
}
}
?>
I think the issue was the initial prepared statement assignment
$stmt->$connect->prepare('SELECT id,pseudo,jeton FROM users WHERE id=:id AND pseudo=:pseudo');
it should be perhaps more like this.
$stmt = $connect->prepare('SELECT id, pseudo, jeton FROM users WHERE id=:id AND pseudo=:pseudo');
The final sql query surely should only be run if there is a successfully added avatar? Reorganised a little whilst looking for issues - hope it helps.
if( $_SERVER['REQUEST_METHOD'] === 'POST' ) {
if( !empty( $_SESSION['pseudo'] ) && !empty( $_SESSION['user_id'] ) ) {
$id = trim( htmlspecialchars( $_SESSION['user_id'] ) );
$pseudo = trim( htmlspecialchars($_SESSION['pseudo'] ) );
/*
Assign the prepared statement as a variable
*/
$stmt = $connect->prepare('SELECT id, pseudo, jeton FROM users WHERE id=:id AND pseudo=:pseudo');
if( !$stmt )exit('Failed to prepare sql');
$stmt->execute( array(
':id' => $id,
':pseudo' => $pseudo
)
);
$row=$stmt->fetch();
if( $_SESSION['pseudo'] == $row['pseudo'] && $_SESSION['user_id'] == $row['id'] ) {
$avatarName = $_FILES['avatarCouverture']['name'];
$avatarTmp = $_FILES['avatarCouverture']['tmp_name'];
$avatarSize = $_FILES['avatarCouverture']['size'];
$avatarType = $_FILES['avatarCouverture']['type'];
$extension = array('jpg','jpeg','png');
$avatarLower = strtolower( pathinfo($avatarName,PATHINFO_EXTENSION ) );
$saveIdUser = trim( htmlspecialchars( $_SESSION['user_id'] ) );
$saveIdUserNew = filter_var( $saveIdUser, FILTER_SANITIZE_NUMBER_INT );
$avatar = rand(0,100000).'_'.date('Y-m-d H-i-s').'_'.$saveIdUserNew;
if( !empty( $avatarName ) ) {
if( $avatarSize < 8000000 ) {
if( in_array( $avatarLower, $extension ) ){
if( !empty( $avatarTmp ) ) {
$image = getimagesize( $avatarTmp );
if( $image['mime'] === 'image/jpeg' ) {
$imageSrc = imagecreatefromjpeg( $avatarTmp );
} elseif( $image['mime']==='image/png' ) {
$imageSrc = imagecreatefrompng( $avatarTmp );
} else {
$imageSrc = false;
}
// modifier size image
if( $imageSrc !== false ) {
$imageWidth = 60;
$imageHeight = 60;
if( $image[0]>= $imageWidth && $image[1]>= $imageHeight ) {
$imageFinale = $imageSrc ;
} else {
$newWidth[0] = $imageWidth;
$newHeight[1] = $imageHeight;
$imageFinale = imagecreatetruecolor( $newWidth[0], $newHeight[1] );
imagecopyresampled( $imageFinale, $imageSrc, 0,0,0,0, $newWidth[0], $newHeight[1], $image[0], $image[1] );
}
$target = imagejpeg( $imageFinale,'upload/avatarPost/'.$avatar.'.jpg' );
move_uploaded_file( $avatarTmp ,$target );
$stmt=$connect->prepare('INSERT INTO users( avatarcouverture ) VALUES( :avatarne )');
if( !$stmt )exit('Failed to prepare sql');
$stmt->execute( array( ":avatarne"=> $avatar ) );
}
}
}
}
}
//header('Location: profil.php');
}
}
}

I need to put resize image 150x130

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

Need to set default thumbnail image if the image is not uploaded or not set

i am working in a classified site..if a user has uploaded image it displays thumbnail but i want to add a default thumbnail image if image is not uploaded..i am new to php and am not able to code it in wp template..Thank You
View File
<div class="thumb">
<?php
colabs_image('key=image&width=150&height=154');
?>
</div>
function colabs_image($args) {
/* ------------------------------------------------------------------------- */
/* SET VARIABLES $key = get_option('colabs_custom_field_image');*/
/* ------------------------------------------------------------------------- */
global $post;
global $colabs_options;
//Defaults
if (get_option('colabs_custom_field_image')!=''){
$key = '<img border="0" src="http://mmpropertydevelopers.com/wp-content/uploads/2013/12/thumbnail-default.jpg" alt="Image" width="100" height="100" />';
}else{
$key = 'image';
}
$width = null;
$height = null;
$class = '';
$quality = 90;
$id = null;
$link = 'src';
$repeat = 1;
$offset = 0;
$before = '';
$after = '';
$single = false;
$force = true;
$return = false;
$is_auto_image = false;
$src = '';
$meta = '';
$alignment = '';
$size = '';
$play = false;
$alt = '';
$img_link = '';
$attachment_id = array();
$attachment_src = array();
if ( !is_array($args) )
parse_str( $args, $args );
extract($args);
// Set Play Icon
$playicon = '';
// Set post ID
if ( empty($id) ) {
$id = $post->ID;
}
$thumb_id = get_post_meta($id,'_thumbnail_id',true);
// Set alignment
if ( '' == $alignment)
$alignment = get_post_meta($id, '_image_alignment', true);
// Get standard sizes
if ( !$width && !$height ) {
$width = '100';
$height = '100';
}
/* ------------------------------------------------------------------------- */
/* FIND IMAGE TO USE */
/* ------------------------------------------------------------------------- */
// When a custom image is sent through
if ( $src != '' ) {
$custom_field = $src;
$link = 'img';
// WP 2.9 Post Thumbnail support
} elseif ( 'true' == get_option( 'colabs_post_image_support') AND !empty($thumb_id) ) {
if ( get_option( 'colabs_pis_resize') == "true") {
// Dynamically resize the post thumbnail
$vt_crop = get_option( 'colabs_pis_hard_crop' );
if ($vt_crop == "true") $vt_crop = true; else $vt_crop = false;
$vt_image = vt_resize( $thumb_id, '', $width, $height, $vt_crop );
// Set fields for output
$custom_field = $vt_image['url'];
$width = $vt_image['width'];
$height = $vt_image['height'];
} else {
// Use predefined size string
if ( $size )
$thumb_size = $size;
else
$thumb_size = array($width,$height);
$img_link = get_the_post_thumbnail($id,$thumb_size,array( 'class' => 'colabs-image ' . $class));
}
// Grab the image from custom field
} else {
$custom_field = get_post_meta($id, $key, true);
}
// Automatic Image Thumbs - get first image from post attachment
if ( empty($custom_field) && 'true' == get_option( 'colabs_auto_img') && empty($img_link) && !(is_singular() AND in_the_loop() AND $link == "src") ) {
if( $offset >= 1 )
$repeat = $repeat + $offset;
$attachments = get_children( array( 'post_parent' => $id,
'numberposts' => $repeat,
'post_type' => 'attachment',
'post_mime_type' => 'image',
'order' => 'DESC',
'orderby' => 'menu_order date')
);
// Search for and get the post attachment
if ( !empty($attachments) ) {
$counter = -1;
$size = 'large';
foreach ( $attachments as $att_id => $attachment ) {
$counter++;
if ( $counter < $offset )
continue;
if ( 'true' == get_option('colabs_post_image_support') AND get_option( 'colabs_pis_resize') == "true") {
// Dynamically resize the post thumbnail
$vt_crop = get_option( 'colabs_pis_hard_crop' );
if ($vt_crop == "true") $vt_crop = true; else $vt_crop = false;
$vt_image = vt_resize( $att_id, '', $width, $height, $vt_crop );
// Set fields for output
$custom_field = $vt_image['url'];
$width = $vt_image['width'];
$height = $vt_image['height'];
} else {
$src = wp_get_attachment_image_src($att_id, $size, true);
$custom_field = $src[0];
$attachment_id[] = $att_id;
$src_arr[] = $custom_field;
}
$thumb_id = $att_id;
$is_auto_image = true;
}
// Get the first img tag from content
} else {
$first_img = '';
$post = get_post($id);
ob_start();
ob_end_clean();
$output = preg_match_all( '/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
if ( !empty($matches[1][0]) ) {
// Save Image URL
$custom_field = $matches[1][0];
// Search for ALT tag
$output = preg_match_all( '/<img.+alt=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
if ( !empty($matches[1][0]) ) {
$alt = $matches[1][0];
}
}
}
}
// Check if there is YouTube embed
if ( empty($custom_field) && empty($img_link) ) {
$embed = get_post_meta($id, "colabs_embed", true);
if ( $embed ) {
$custom_field = colabs_get_video_image($embed);
// Set Play Icon
if($play == true){ $playicon = '<span class="playicon">Play</span>'; }
}
}
// Return if there is no attachment or custom field set
if ( empty($custom_field) && empty($img_link) ) {
// Check if default placeholder image is uploaded
$placeholder = get_option( 'framework_colabs_default_image' );
if ( $placeholder && !(is_singular() AND in_the_loop()) ) {
$custom_field = $placeholder;
// Resize the placeholder if
if ( 'true' == get_option('colabs_post_image_support') AND get_option( 'colabs_pis_resize') == "true") {
// Dynamically resize the post thumbnail
$vt_crop = get_option( 'colabs_pis_hard_crop' );
if ($vt_crop == "true") $vt_crop = true; else $vt_crop = false;
$vt_image = vt_resize( '', $placeholder, $width, $height, $vt_crop );
// Set fields for output
$custom_field = $vt_image['url'];
$width = $vt_image['width'];
$height = $vt_image['height'];
}
} else {
return;
}
}
if(empty($src_arr) && empty($img_link)){ $src_arr[] = $custom_field; }
/* ------------------------------------------------------------------------- */
/* BEGIN OUTPUT */
/* ------------------------------------------------------------------------- */
$output = '';
// Set output height and width
$set_width = ' width="' . $width .'" ';
$set_height = ' height="' . $height .'" ';
if($height == null OR '' == $height) $set_height = '';
// Set standard class
if ( $class ) $class = 'colabs-image ' . $class; else $class = 'colabs-image';
// Do check to verify if images are smaller then specified.
if($force == true){ $set_width = ''; $set_height = ''; }
// WP Post Thumbnail
if(!empty($img_link) ){
if( 'img' == $link ) { // Output the image without anchors
$output .= $before;
$output .= $img_link;
$output .= $after;
} elseif( 'url' == $link ) { // Output the large image
$src = wp_get_attachment_image_src($thumb_id, 'large', true);
$custom_field = $src[0];
$output .= $custom_field;
} else { // Default - output with link
if ( ( is_single() OR is_page() ) AND $single == false ) {
$rel = 'rel="lightbox"';
$href = false;
} else {
$href = get_permalink($id);
$rel = '';
}
$title = 'title="' . get_the_title($id) .'"';
$output .= $before;
if($href == false){
$output .= $img_link;
} else {
$output .= '<a '.$title.' href="' . $href .'" '.$rel.'>' . $img_link . '</a>';
}
$output .= $after;
}
}
// Use thumb.php to resize. Skip if image has been natively resized with vt_resize.
elseif ( 'true' == get_option( 'colabs_resize') && empty($vt_image['url']) ) {
foreach($src_arr as $key => $custom_field){
// Clean the image URL
$href = $custom_field;
$custom_field = cleanSource( $custom_field );
// Check if WPMU and set correct path AND that image isn't external
if ( function_exists( 'get_current_site') && strpos($custom_field,"http://") !== 0 ) {
get_current_site();
//global $blog_id; Breaks with WP3 MS
if ( !$blog_id ) {
global $current_blog;
$blog_id = $current_blog->blog_id;
}
if ( isset($blog_id) && $blog_id > 0 ) {
$imageParts = explode( 'files/', $custom_field );
if ( isset($imageParts[1]) )
$custom_field = '/blogs.dir/' . $blog_id . '/files/' . $imageParts[1];
}
}
//Set the ID to the Attachment's ID if it is an attachment
if($is_auto_image == true){
$quick_id = $attachment_id[$key];
} else {
$quick_id = $id;
}
//Set custom meta
if ($meta) {
$alt = $meta;
$title = 'title="'. $meta .'"';
} else {
if ('' == $alt AND get_post_meta($thumb_id, '_wp_attachment_image_alt', true) )
$alt = get_post_meta($thumb_id, '_wp_attachment_image_alt', true);
else
$alt = get_the_title($quick_id);
$title = 'title="'. get_the_title($quick_id) .'"';
}
// Set alignment parameter
if ($alignment <> '')
$alignment = '&a='.$alignment;
$img_link = '<img src="'. get_template_directory_uri(). '/functions/timthumb.php?src='. $custom_field .'&w='. $width .'&h='. $height .'&zc=1&q='. $quality . $alignment . '" alt="'.$alt.'" class="'. stripslashes($class) .'" '. $set_width . $set_height . ' />';
if( 'img' == $link ) { // Just output the image
$output .= $before;
$output .= $img_link;
$output .= $playicon;
$output .= $after;
} elseif( 'url' == $link ) { // Output the image without anchors
if($is_auto_image == true){
$src = wp_get_attachment_image_src($thumb_id, 'large', true);
$custom_field = $src[0];
}
$output .= $custom_field;
} else { // Default - output with link
if ( ( is_single() OR is_page() ) AND $single == false ) {
$rel = 'rel="lightbox"';
} else {
$href = get_permalink($id);
$rel = '';
}
$output .= $before;
$output .= '<a '.$title.' href="' . $href .'" '.$rel.'>' . $img_link . $playicon . '</a>';
$output .= $after;
}
}
// No dynamic resizing
} else {
foreach($src_arr as $key => $custom_field){
//Set the ID to the Attachment's ID if it is an attachment
if($is_auto_image == true AND isset($attachment_id[$key])){
$quick_id = $attachment_id[$key];
} else {
$quick_id = $id;
}
//Set custom meta
if ($meta) {
$alt = $meta;
$title = 'title="'. $meta .'"';
} else {
if ('' == $alt) $alt = get_post_meta($thumb_id, '_wp_attachment_image_alt', true);
$title = 'title="'. get_the_title($quick_id) .'"';
}
$img_link = '<img src="'. $custom_field .'" alt="'. $alt .'" '. $set_width . $set_height . ' class="'. stripslashes($class) .'" />';
if ( 'img' == $link ) { // Just output the image
$output .= $before;
$output .= $img_link;
$output .= $after;
} elseif( 'url' == $link ) { // Output the URL to original image
if ( $vt_image['url'] || $is_auto_image ) {
$src = wp_get_attachment_image_src($thumb_id, 'full', true);
$custom_field = $src[0];
}
$output .= $custom_field;
} else { // Default - output with link
if ( ( is_single() OR is_page() ) AND $single == false ) {
// Link to the large image if single post
if ( $vt_image['url'] || $is_auto_image ) {
$src = wp_get_attachment_image_src($thumb_id, 'full', true);
$custom_field = $src[0];
}
$href = $custom_field;
$rel = 'rel="lightbox"';
} else {
$href = get_permalink($id);
$rel = '';
}
$output .= $before;
$output .= '<a href="' . $href .'" '. $rel . $title .'>' . $img_link . '</a>';
$output .= $after;
}
}
}
// Return or echo the output
if ( $return == TRUE )
return $output;
else
echo $output; // Done
}
/* Get thumbnail from Video Embed code */
You can add a javascript onError to the picture.
$key = '<img border="0" src="mypic.jpg" alt="Image" width="100" height="100"
onError="this.onerror=null;this.src='.chr(39).'alternative.jpg'.chr(39).'"/>';

Categories