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

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!

Related

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

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

copy a php file to every directory

I've a simple problem of copying a a php folder to some directories, bu the problem is I can't the solution for that, the idea is that I've an Online Manga Viewer script, and what I want to do is I want to add comments page to every chapter, the I dea that I came with, is, I create a separate comments page file and once a new chapter added the the comments file will be copied to the folder of the chapter :
Description Image:
http://i.stack.imgur.com/4wYE0.png
What I to know is how can I do it knowing that I will use Disqus commenting System.
Functions used in the script:
function omv_get_mangas() {
$mangas = array();
$dirname = "mangas/";
$dir = #opendir($dirname);
if ($dir) {
while (($file = #readdir($dir)) !== false) {
if (is_dir($dirname . $file . '/') && ($file != ".") && ($file != "..")) {
$mangas[] = $file;
}
}
#closedir($dir);
}
sort($mangas);
return $mangas;
}
function omv_get_chapters($manga) {
global $omv_chapters_sorting;
$chapters = array();
$chapters_id = array();
$dirname = "mangas/$manga/";
$dir = #opendir($dirname);
if ($dir) {
while (($file = #readdir($dir)) !== false) {
if (is_dir($dirname . $file . '/') && ($file != ".") && ($file != "..")) {
$chapter = array();
$chapter["folder"] = $file;
$pos = strpos($file, '-');
if ($pos === false) {
$chapter["number"] = $file;
} else {
$chapter["number"] = trim(substr($file, 0, $pos - 1));
$chapter["title"] = trim(substr($file, $pos + 1));
}
$chapters_id[] = $chapter["number"];
$chapters[] = $chapter;
}
}
#closedir($dir);
}
array_multisort($chapters_id, $omv_chapters_sorting, $chapters);
return $chapters;
}
function omv_get_chapter_index($chapters, $chapter_number) {
$i = 0;
while (($i < count($chapters)) && ($chapters[$i]["number"] != $chapter_number)) $i++;
return ($i < count($chapters)) ? $i : -1;
}
function omv_get_pages($manga, $chapter) {
global $omv_img_types;
$pages = array();
$dirname = "mangas/$manga/$chapter/";
$dir = #opendir($dirname);
if ($dir) {
while (($file = #readdir($dir)) !== false) {
if (!is_dir($dirname . $file . '/')) {
$file_extension = strtolower(substr($file, strrpos($file, ".") + 1));
if (in_array($file_extension, $omv_img_types)) {
$pages[] = $file;
}
}
}
#closedir($dir);
}
sort($pages);
return $pages;
}
/*function add_chapter_comment($dirname){
$filename = $dirname.'comments.php';
if (file_exists($filename)) {
} else {
copy('comments.php', .$dirname.'comments.php');
}
}*/
function omv_get_previous_page($manga_e, $chapter_number_e, $current_page, $previous_chapter) {
if ($current_page > 1) {
return $manga_e . '/' . $chapter_number_e . '/' . ($current_page - 1);
} else if ($previous_chapter) {
$pages = omv_get_pages(omv_decode($manga_e), $previous_chapter["folder"]);
return $manga_e . '/' . omv_encode($previous_chapter["number"]) . '/' . count($pages);
} else {
return null;
}
}
function omv_get_next_page($manga_e, $chapter_number_e, $current_page, $nb_pages, $next_chapter) {
if ($current_page < $nb_pages) {
return $manga_e . '/' . $chapter_number_e . '/' . ($current_page + 1);
} else if ($next_chapter) {
return $manga_e . '/' . omv_encode($next_chapter["number"]);
} else {
return null;
}
}
function omv_get_image_size($img) {
global $omv_img_resize, $omv_preferred_width;
$size = array();
$imginfo = getimagesize($img);
$size["width"] = intval($imginfo[0]);
$size["height"] = intval($imginfo[1]);
if ($omv_img_resize) {
if ($size["width"] > $omv_preferred_width) {
$size["height"] = intval($size["height"] * ($omv_preferred_width / $size["width"]));
$size["width"] = $omv_preferred_width;
}
}
return $size;
}
And thanks for all of you!
Include the following line in all of your pages in a small php statement, if it covers two folder paths, use this. Which I think in your case it does.
<?php
include('../../header.php');
?>
And then save this in the main root directory. Which in your diagram is called "Main Folder"

jQuery/PHP File Upload Times Out Before Loading Next Page

So I am developing the following image upload script, based off an existing open-source script. It's currently viewable live here: http://images.oneightynyc.com/
Now if you take any series of regular sized images (under 5mb) and proceed to upload them, the upload process goes just fine. Uploads the files, and brings you to a page that displays the link codes to those files. However let's say you upload a few large images, like the following:
http://imaging.nikon.com/lineup/dslr/d90/img/sample/pic_005b.jpg
http://imaging.nikon.com/lineup/dslr/d90/img/sample/pic_003b.jpg
The uploads happen in the process, however the script never brings you to the uploaded page. The only way I am aware that the upload has actually taken place is if I browse to the Gallery page and see that the files are listed there.
Here is the uploader.php file which handles the upload:
<?
//ob_start();
session_start();
$auth_id=$_SESSION['userid'];
if (!$auth_id || empty($auth_id) || $auth_id==""){
$auth_id = 0;
}
require_once("config.php");
require_once("limits.php");
require_once("ftp.class.php");
require_once("func.php");
$link = mysql_connect($db_server, $db_user, $db_password) or die("Could not connect to the database.");
mysql_select_db($db_name) or die("Could not select the database.");
if ($config[Uploads] == 0) {
$msg= "<center><b><br><br><br>Uploads are temporarily disabled by the site admin</center></b>";
}
else if ($config[Uploads] == 1 && !$auth_id) {
$msg= "<center><b><br><br><br>You have to Register before you will be able to upload photos.</center></b>";
}
$query = "select count(*) as total from ftp where status=1";
$result = mysql_query($query) or die("Query failed.");
while ($row = mysql_fetch_array($result))
{
$total=$row[total];
}
if($total<=0)
{
$no_server="1";
$ftpid=0;
$url=$server_url."/images/";
}
else
{
$query = "select * from ftp where status=1 ORDER BY RAND() limit 1";
$result = mysql_query($query) or die("Query failed.");
while ($row = mysql_fetch_array($result))
{
$no_server="0";
$ftpid=$row['ftpid'];
$path=$row['name'];
$url=$row['dir'];
$host=$row['host'];
$user=$row['user'];
$pass=$row['ftppass'];
}
}
// get variables for fields on upload screen
$tos = $_POST['tos'];
$prv = $_POST['prv'];
if($prv!="1")
$prv=0;
$uploaderip = $_SERVER['REMOTE_ADDR'];
$messages="";
$msg="";
$newID="";
$FileName="";
$FileFile="";
$FileUrl="";
$FileUrlLink="";
$FiletnUrl="";
// check for blocked ip address
if ($uploaderip != "") {
$query = "select ip from blocked where ip = '$uploaderip'";
$result = mysql_query($query) or die("Query failed.");
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
$msg= "Your IP address (".$uploaderip.") has been blocked from using this service.";
}
}
if ($config[AcceptTerms]=="1"){
if ($tos=="")
{
$msg= "You must check the box stating you agree to our terms.";
echo "<script language='javascript'>parent.upload('".$msg."','".$newID."','".$messages."','".$FileName."','".$FileFile."','".$FileUrl."','".$FileUrlLink."','".$FiletnUrl."','".$page_url."','".$server_url."','".$site_name."','".$HotLink."');</script>";
}
}
if($msg=="")
{
// check for a file
for($i=0;$i<=14;$i++)
{
$err="0";
$thefile = $_FILES['thefile'.$i];
if ($thefile['name']!="")
{
// check for valid file extension
$path_parts = pathinfo($thefile['name']);
$file_ext = strtolower($path_parts['extension']);
if ($err == "0")
{
// check for valid file type
if (!in_array_nocase($file_ext, $valid_file_ext))
{
$messages.= "|<em>".$thefile['name']."</em> is not in a valid format (".$valid_mime_types_display.")";
$err="1";
}
}
if ($err == "0") {
// check for valid image file
$imageinfo = getimagesize($_FILES['thefile0']['tmp_name']);
if(!eregi('image',$imageinfo['mime'])) {
$messages.="|". "Sorry, This is not a valid image file!";
$err="1"; } }
if ($err == "0")
{
// check for valid file size
if ($thefile['size'] > ($max_file_size_b))
{
$filesizemb =($thefile['size']/1048576);
$filesizemb = number_format($filesizemb, 3);
$messages.="Sorry but this image size is ".$filesizemb." MB which is bigger than the max allowed file size of ".$max_file_size_mb." MB.";
$err="1";
}
}
// save the file, if no error messages
if ($err == "0")
{
// replace special chars with spaces
$thefile['name'] = eregi_replace("[^a-z0-9.]", " ", $thefile['name']);
// Replace multiple spaces with one space
$thefile['name'] = ereg_replace(' +', ' ', $thefile['name']);
// Replace spaces with underscore
$thefile['name'] = str_replace(' ', '_', $thefile['name']);
// Replace hyphens with underscore
$thefile['name'] = str_replace('-', '_', $thefile['name']);
// Replace multiple underscores with one underscore
$thefile['name'] = ereg_replace('_+', '_', $thefile['name']);
$path_parts = pathinfo($thefile['name']);
// if php < 5.2
if(!isset($path_parts['filename'])){
$path_parts['filename'] = substr($path_parts['basename'], 0,strpos($path_parts['basename'],'.'));
}
$thefile['name'] = strpos($path_parts['filename'], '.');
$thefile['name'] = substr($path_parts['filename'], 0, 22); // limit file name length to 22 chars from the beginning
$thefile['name'] = $thefile['name'] . "." . strtolower($path_parts['extension']);
// Generate prefix to add to file name
$prefix = rand(99,999);
// Add prefix to file name
$newFileName = $prefix . $thefile['name'];
// SAVE THE PICTURE
$FileName.="|". newImageName($thefile['name']);
$FileFile.="|". $server_dir . $newFileName;
$newFile = $server_dir . $newFileName;
$newFileUrl = $url . $newFileName;
$FileUrl.="|". $url . $newFileName;
$newFileUrlLink = $server_save_directory . $newFileName;
$FileUrlLink.="|". $newFileName;
if (in_array_nocase($file_ext, $valid_file_ext))
{
$lx = 3;
if ($file_ext == "jpeg") {
$lx = 4; }
$tnFileName = substr($newFileName, 0, strlen($newFileName) - $lx) . "jpg";
$tnFileName = str_replace('.', '_tn.', $tnFileName);
$tnFile = $server_dir . $tnFileName;
$FiletnUrl.="|". $url . $tnFileName;
$tnFileUrl = $url . $tnFileName;
}
else
{
$tnFileName = "";
$tnFile = "";
$tnFileUrl = "";
}
$filesize = $thefile['size'];
$newID = "";
if (!#copy($thefile['tmp_name'], $newFile))
{
$messages.="|". "Please check site settings in admin panel and set proper value for server local path.<br><br>Also please make sure the images folder is chmodded to 0777";
}
else
{
// add to database
if($auth_id)
$uid=$auth_id;
else $uid=0;
//ftpupload($host,$user,$pass,$path."/".$dir."/".$newFileName,$newFileUrl);
//ftpupload
if($no_server=="0")
{
$ftp =& new FTP();
if ($ftp->connect($host)) {
if ($ftp->login($user,$pass)) {
$ftp->chdir($path);
$ftp->put($newFileName,$newFile);
}
}
// unlink($newFile);
}
//ftpupload
$date_add=time();
$query = "INSERT INTO images (prv,ftpid,userid,filename, tn_filename, filepath, ip, filesize,added) VALUES ($prv,$ftpid,$uid,'$newFileName', '$tnFileName', '$url', '$uploaderip', $filesize,$date_add)";
mysql_query($query) or die("Database entry failed.");
$newID.="|". mysql_insert_id();
}
if ($file_ext == "jpeg" ||$file_ext == "jpg" || $file_ext == "png" || $file_ext == "gif" || $file_ext == "bmp")
{
if ($file_ext == "jpg")
{
$source_id = imagecreatefromjpeg($newFile);
}
if ($file_ext == "jpeg")
{
$source_id = imagecreatefromjpeg($newFile);
}
elseif ($file_ext == "png")
{
$source_id = imagecreatefrompng($newFile);
}
elseif ($file_ext == "gif")
{
$source_id = imagecreatefromgif($newFile);
}
elseif ($file_ext == "bmp")
{
$source_id = ImageCreateFromBMP($newFile);
}
$true_width = imagesx($source_id);
$true_height = imagesy($source_id);
}
}
}
}
mysql_close($link);
// create URL links to display to user
$showURL1 = false; // image on hosted page - image only
$showURL2 = false; // direct link to file - all
$showURL3 = false; // HTML for img - image only
$showURL4 = false; // [img][/img] tags - image only
$showURL5 = false; // thumbnail pic - image only
// determine flags
$showURL2 = true;
if ($file_ext == "jpg" || $file_ext == "jpeg"|| $file_ext == "gif" || $file_ext == "png" || $file_ext == "bmp") {
$showURL1 = true;
$showURL3 = true;
$showURL4 = true;
}
if ($file_ext == "jpg" || $file_ext == "gif" || $file_ext == "png"|| $file_ext == "jpeg" || $file_ext == "bmp") {
$showURL5 = true;
}
echo "<script language='javascript'>parent.upload('".$msg."','".$newID."','".$messages."','".$FileName."','".$FileFile."','".$FileUrl."','".$FileUrlLink."','".$FiletnUrl."','".$page_url."','".$server_url."','".$site_name."','".$HotLink."');</script>";
}
else
{
echo "<script language='javascript'>parent.uploaderror('".$msg."');</script>";
exit;
}
function newImageName($fname) {
$timestamp = time();
$new_image_file_ext = substr($fname, strlen($fname) - 3, strlen($fname));
if ($new_image_file_ext == "peg") {
$ext = ".jpg";
} else {
$ext = "." . $new_image_file_ext;
}
$newfilename = randString() . substr($timestamp, strlen(timestamp) - 4, strlen(timestamp)) . $ext;
return $newfilename;
}
function randString() {
$newstring="";
while(strlen($newstring) < 3) {
$randnum = mt_rand(0,61);
if ($randnum < 10) {
$newstring .= chr($randnum + 48);
} elseif ($randnum < 36) {
$newstring .= chr($randnum + 55);
} else {
$newstring .= chr($randnum + 61);
}
}
return $newstring;
}
function in_array_nocase($item, $array) {
$item = &strtoupper($item);
foreach($array as $element) {
if ($item == strtoupper($element)) {
return true;
}
}
return false;
}
?>
And the upload.js script which takes care of producing the uploaded page:
var cp = new cpaint();
cp.set_transfer_mode('get');
cp.set_response_type('xml');
cp.set_debug(1);
function uploaderror(msg)
{
alert(msg);
}
function showfile()
{
var countfld=1;
countfld=document.getElementById("countfld").value+countfld;
fld=countfld.length;
if(fld>14)
{
alert("Sorry, i can upload max 15 files at once.");
return false;
}
else
{
document.getElementById("f"+fld).style.display="block";
document.getElementById("countfld").value=countfld;
}
var file=document.getElementById("f"+fld).value;
if(file=="")
{
msg="Please fill this field.";
alert(msg);
document.getElementById("f"+fld).focus();
return false;
}
}
function showfileux()
{
var countfld=1;
countfld=document.getElementById("countfldu").value+countfld;
fld=countfld.length;
if(fld>14)
{
alert("Sorry, i can upload max 15 files at once.");
return false;
}
else
{
document.getElementById("u"+fld).style.display="block";
document.getElementById("countfldu").value=countfld;
}
}
function showfileu()
{
var countfld=1;
countfld=document.getElementById("countfldu").value+countfld;
fld=countfld.length;
fldx=fld-1;
fldxx=fld.value;
if(fldxx=="")
{
msg="Email Address cannot be left empty.";
alert(msg);
document.getElementById("u"+fldxx).select();
document.getElementById("u"+fldxx).focus();
return false;
}
if(fld>14)
{
alert("Sorry, i can upload max 15 files at once.");
return false;
}
else
{
document.getElementById("u"+fld).style.display="block";
document.getElementById("countfldu").value=countfld;
}
}
function uploadfile(id)
{
if(document.getElementById(id).value==1)
{
document.getElementById("showurl").style.display="none";
document.getElementById("showfl").style.display="block";
return true;
}
if(document.getElementById(id).value==2)
{
document.getElementById("showfl").style.display="none";
document.getElementById("showurl").style.display="block";
return true;
}
document.getElementById("countfldu").value="0";
document.getElementById("countfld").value="0";
}
function show_loading()
{
document.getElementById('loading').style.display = "block";
document.getElementById('newupload').submit;
document.getElementById('submit').disabled = true;
// return true;
}
function show_loading1()
{
document.getElementById('loading1').style.display = "block";
document.getElementById('newupload1').submit;
document.getElementById('submit').disabled = true;
}
function upload(msg,newID,messages,FileName,FileFile,FileUrl,FileUrlLink,FiletnUrl,page_url,server_url,site_name,HotLink)
{
var html='<div id="wrapper"><div style="width:760px;"><center><FONT SIZE="4" COLOR="#00A4B7">Photo Links</FONT></h4><br></center><span class="body"><form name="uploadresults" action="uploademail.php" method="post">';
if(newID)
{
html=html+'<input type="hidden" name="idx[]" value="'+newID+'">';
}
if(msg)
{
var getmsg = msg.split("|");
for(i=0;i<getmsg.length;i++)
{
if(getmsg[i] && getmsg[i]!="on")
html=html+'<span style="font-weight: bold; color: red;">'+getmsg[i]+'</span><br>';
}
}
html=html+'<br><center>';
if(messages)
{
var getmessages = messages.split("|");
for(i=0;i<getmessages.length;i++)
{
if(getmessages[i] && getmessages[i]!="on")
html=html+'<span style="font-weight: bold; color: red;">'+getmessages[i]+'</span>';
}
html=html+'</center>';
}
if(FileName)
{
var getFileName = FileName.split("|");
var getFileFile = FileFile.split("|");
var getFileUrl = FileUrl.split("|");
var getFileUrlLink = FileUrlLink.split("|");
var getFiletnUrl = FiletnUrl.split("|");
var getHotLink = HotLink.split("|");
for(i=0;i<getFileName.length;i++)
{
if(getFileName[i] && getFileName[i]!="on") {
html=html+'<center><br><img src="'+getFileUrl[i]+'" style="max-width: 550px;"" /><br><br>';
html=html+'<strong>Link to add tags and delete the photo <br><div align="center"><textarea name="url1[]" cols="80" rows="1" READONLY onfocus="javascript: this.select()">'+server_url+'/view2.php?filename='+getFileUrlLink[i]+'
Let me know what you think is causing this error, as this is the final step I need to fix.
I've had similar issue with creating excel files from large data bases. What it boils down to is that the PHP script exceeds the servers set time limit. There are multiple ways to delay/extend this from built in PHP functions, some or all may be used. I personally had use a combination of the ability with AJAX to allow it run in the backgroun and then redirect that page.
Here is the documentation on how to delay/extend it:
http://php.net/manual/en/function.set-time-limit.php
Here is the documentation on how check for a time out as well:
http://php.net/manual/en/function.connection-timeout.php
If you end up going the AJAX route as I did, I highly recommend going the jQuery route instead of vanilla JS.

High CPU consumption by a PHP script

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?

Categories