which one is better for checking images? php or js - php

I need to check images of contents on website.
I wrote code use php that doesn't have a problem, but I found some different ways on internet(Click to see example!)
from your opinion which is more efficient?
My website template seems like this: https://imgur.com/XOdDEZu
below is my php code :
$random_img = rand(1,9); // I have saved images to folder img_1, img_2 ...
$fixed_image = "<img src='public/img/duz/img_".$random_img.".jpg' style='width: 100%; height:320px; filter: blur(.1rem);' border:2px solid red;>";
$uploaded_img_file = "public/upload/$value->content_img";
$img_url = $value->content_img;
$find_letters = array('jpg', 'jpeg', 'png','gif','svg');
$match = (str_replace($find_letters, '', substr($img_url,-4)) != substr($img_url,-4));
//true if the last 4 characters of img url match the 4 characters in the array; returns false if it does not match
if (empty($value->content_img)) {
echo $fixed_img;
echo $a;
}elseif (file_exists($uploaded_img_file)) {
echo "<img src='".$uploaded_img_file."'>";
//print_r($uploaded_img_file);
}elseif (strlen($img_url)>=3) { //If the string length of the data from the database exceeds 3 characters. (no image if less than three characters)
if (filter_var($img_url, FILTER_VALIDATE_URL) !== false && $match==true) { //url validation check
echo "<img src='".$img_url."'>";
}else{
echo $fixed_img;
$String_title = $value->content_title;
$title_limit = limit_text($String_baslik, 10);
echo $a;
}
//print_r($img_url);
}else{
echo $fixed_img;
echo '<div style="position:absolute; left:15px; bottom:5px; text-decoration: none;"><span>Merhaba</span></div>';
}

Related

div and class not showing up

I'm testing a barcode on my website but for some reason the div with the class="b128" which stands for the barcodes is not showing up. If I test the same source code on another website it does show up but with different styling.
Does anyone know how I can make this source code show up and keep the original styling at the same time?
<style>
div.b128{
border-left: 1px black solid;
height: 60px;
}
</style>
<?php
global $char128asc,$char128charWidth;
$char128asc=' !"#$%&\'()*+,-./0123456789:;<=>?#ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~';
$char128wid = array(
'212222','222122','222221','121223','121322','131222','122213','122312','132212','221213', // 0-9
'221312','231212','112232','122132','122231','113222','123122','123221','223211','221132', // 10-19
'221231','213212','223112','312131','311222','321122','321221','312212','322112','322211', // 20-29
'212123','212321','232121','111323','131123','131321','112313','132113','132311','211313', // 30-39
'231113','231311','112133','112331','132131','113123','113321','133121','313121','211331', // 40-49
'231131','213113','213311','213131','311123','311321','331121','312113','312311','332111', // 50-59
'314111','221411','431111','111224','111422','121124','121421','141122','141221','112214', // 60-69
'112412','122114','122411','142112','142211','241211','221114','413111','241112','134111', // 70-79
'111242','121142','121241','114212','124112','124211','411212','421112','421211','212141', // 80-89
'214121','412121','111143','111341','131141','114113','114311','411113','411311','113141', // 90-99
'114131','311141','411131','211412','211214','211232','23311120' ); // 100-106
////Define Function
function bar128($text) { // Part 1, make list of widths
global $char128asc,$char128wid;
$w = $char128wid[$sum = 104]; // START symbol
$onChar=1;
for($x=0;$x<strlen($text);$x++) // GO THRU TEXT GET LETTERS
if (!( ($pos = strpos($char128asc,$text[$x])) === false )){ // SKIP NOT FOUND CHARS
$w.= $char128wid[$pos];
$sum += $onChar++ * $pos;
}
$w.= $char128wid[ $sum % 103 ].$char128wid[106]; //Check Code, then END
//Part 2, Write rows
$html="<table cellpadding=0 cellspacing=0><tr>";
for($x=0;$x<strlen($w);$x+=2) // code 128 widths: black border, then white space
$html .= "<td><div class=\"b128\" style=\"border-left-width:{$w[$x]};width:{$w[$x+1]}\"></div>";
return "$html<tr><td colspan=".strlen($w)." align=center><font family=arial size=2><b>$text</table>";
}
?>
<?php
$test = "12345";
echo '<div style="border:3px double #ababab; padding:5px;margin:5px auto;width:135px;">';
echo bar128(stripslashes($test));
echo '</div>';
?>
You aren't closing most of your tags. Try this:
$html = "<table cellpadding=0 cellspacing=0><tr>";
for ($x = 0; $x < strlen($w); $x += 2) // code 128 widths: black border, then white space
$html .= "<td><div class=\"b128\" style=\"border-left-width:{$w[$x]};width:{$w[$x+1]}\"></div></td>";
return "$html</tr><tr><td colspan=" . strlen($w) . " align=center><font family=arial size=2><b>$text</b></font></td></tr></table>";

Check if a string contains a url and get contents of url php

Suppose someone enters a string in a textarea like this
"The best search engine is www.google.com."
or maybe
"The best search engine is https://www.google.co.in/?gfe_rd=cr&ei=FLB1U4HHG6aJ8Qfc1YHIBA."
Then i want to highlight the link as stackoverflow does.
And also i want to file_get_contents to get one image , a short description and title of the page.
Most probably i wanna check if the string contains a url or not -> two times.
On keyup of textarea using jQuery and therefore using the
get_file_contents
When the string is recieved by php.
Possibly how can i do this?
UPDATE
function parseHyperlinks($text) {
// The Regular Expression filter
$reg_exUrl1 = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
$reg_exUrl2 = "/[\w\d\.]+\.(com|org|ca|net|uk)/";
// The Text you want to filter for urls
// Check if there is a url in the text
if(preg_match($reg_exUrl1, $text, $url)) {
// make the urls hyper links
return preg_replace($reg_exUrl1, "<a class=\"content-link link\" href=\"{$url[0]}\">{$url[0]}</a> ", $text);
} else if(preg_match($reg_exUrl2, $text, $url)){
return preg_replace($reg_exUrl2, "<a class=\"content-link link\" href=\"{$url[0]}\">{$url[0]}</a> ", $text);
}else{
// if no urls in the text just return the text
return $text;
}
}
This works only if $str='www.google.com is the best' or $str='http://www.google.com is best' but not if $str='http://stackoverflow.com/ and www.google.com is the best'
First off you create the html then you need to an AJAX to request to the server. Consider this sample codes:
HTML/jQuery:
<!-- instead of textarea, you could use an editable div for styling highlights, or if you want, just use a plugin -->
<div id="textarea"
style="
font-family: monospace;
white-space: pre;
width: 300px;
height: 200px;
border: 1px solid #ccc;
padding: 5px;">For more tech stuff, check out http://www.tomshardware.com/ for news and updates.</div><br/>
<button type="button" id="scrape_site">Scrape</button><br/><br/>
<!-- i just used a button to hook up the scraping, you can just bind it on a keyup/keydown. -->
<div id="site_output" style="width: 500px;">
<label>Site: <p id="site" style="background-color: gray;"></p></label>
<label>Title: <p id="title" style="background-color: gray;"></p></label>
<label>Description: <p id="description" style="background-color: gray;"></p></label>
<label>Image: <div id="site_image"></div></label>
</div>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#scrape_site').on('click', function(){
var value = $.trim($('#textarea').text());
$('#site, #title, #description').text('');
$('#site_image').empty();
$.ajax({
url: 'index.php', // or you php that will process the text
type: 'POST',
data: {scrape: true, text: value},
dataType: 'JSON',
success: function(response) {
$('#site').text(response.url);
$('#title').text(response.title);
$('#description').text(response.description);
$('#site_image').html('<img src="'+response.src+'" id="site_image" />');
}
});
});
// you can use an editable div so that it can be styled,
// theres to much code already in the answer, you can just get a highlighter plugin to ease your pain
$('#textarea').each(function(){
this.contentEditable = true;
});
});
</script>
And on your php that will process, in this case (index.php):
if(isset($_POST['scrape'])) {
$text = $_POST['text'];
// EXTRACT URL
$reg_exurl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
preg_match_all($reg_exurl, $text, $matches);
$usedPatterns = array();
$url = '';
foreach($matches[0] as $pattern){
if(!array_key_exists($pattern, $usedPatterns)){
$usedPatterns[$pattern] = true;
$url = $pattern;
}
}
// EXTRACT VALUES (scraping of title and descriptions)
$doc = new DOMDocument();
$doc->loadHTMLFile($url);
$xpath = new DOMXPath($doc);
$title = $xpath->query('//title')->item(0)->nodeValue;
$description = $xpath->query('/html/head/meta[#name="description"]/#content');
if ($description->length == 0) {
$description = "No description meta tag :(";
// Found one or more descriptions, loop over them
} else {
foreach ($description as $info) {
$description = $info->value . PHP_EOL;
}
}
$data['description'] = $description;
$data['title'] = $title;
$data['url'] = $url;
// SCRAPING OF IMAGE (the weirdest part)
$image_found = false;
$data['src'] = '';
$images = array();
// get all possible images and this is a little BIT TOUGH
// check for og:image (facebook), some sites have this, so first lets take a look on this meta
$facebook_ogimage = $xpath->query("/html/head/meta[#property='og:image']/#content");
foreach($facebook_ogimage as $ogimage) {
$data['src'] = $ogimage->nodeValue;
$image_found = true;
}
// desperation search (get images)
if(!$image_found) {
$image_list = $xpath->query("//img[#src]");
for($i=0;$i<$image_list->length; $i++){
if(strpos($image_list->item($i)->getAttribute("src"), 'ad') === false) {
$images[] = $image_list->item($i)->getAttribute("src");
}
}
if(count($images) > 0) {
// if at least one, get it
$data['src'] = $images[0];
}
}
echo json_encode($data);
exit;
}
?>
Note: Although this is not perfect, you can just use this as a reference to just improved on it and make it more dynamic as you could.

limit the word count and add a read more link

Ok i have this code so far which is in my wordpress template so precisely this a wordpress stuff.
<?php
$post_id = 266;
echo "<div id='widgets-wrapper3'><div id='marginwidgets' style='overflow: auto; max-width: 100%; margin: 0 auto; border: none !important;'>";
$queried_post = get_post($post_id);
echo "<div class='thewidgets'>";
echo $queried_post->post_content;
echo '</div>';
echo "</div></div>";
?>
as you can see into the code, the routine is, to display the post which has an id of 266, now all i want is to limit the word count in the post content of that post, let say I want to limit the word to 300 and then add a read more link. how to make that please?
hope there's someone here who figured out how to make that.
I am open in, Ideas, recommendation and suggestion. Hope someone here could help, thank you.
try this:
http://codex.wordpress.org/Function_Reference/the_excerpt
or use php substr:
echo get_sub($queried_post->post_content, 300);
function get_sub($str, $max=300)
{
$ar = explode($str);
$count = 0;
$new_str = "";
$del = " ";
foreach($ar as $a)
{
if($count == 0)
{
//no space
$del = "";
}
if($count < $max)
{
$new_str .= $del.$a;
}
$count++;
}
return $new_str;
}
if the content contains html elements, its a problem.
hope it helps

Foreach loop stop after text is displayed

I'm generating and showing pictures in a picture of a day sort of script. I have a gallery page for that picture of the day (that pulls from a directory). So I want to pull all the files from the directory and when it hits the current date (which is also the same as the file name IE. 20120822.jpg is what's displaying today and 20120823.jpg is what will display tomorrow). I have it looping all of the directory images and displaying them in a gallery, but I want the loop to stop after the current date so we don't show or load the future images. Here is my code.. I'm sure I'm just doing something silly..
<?PHP
// filetypes to display
$imagetypes = array("image/jpeg", "image/gif");
?>
<?PHP
function getImages($dir)
{
global $imagetypes;
// array to hold return value
$retval = array();
// add trailing slash if missing
if(substr($dir, -1) != "/") $dir .= "/";
// full server path to directory
$fulldir = "{$_SERVER['DOCUMENT_ROOT']}/$dir";
$d = #dir($fulldir) or die("getImages: Failed opening directory $dir for reading");
while(false !== ($entry = $d->read())) {
// skip hidden files
if($entry[0] == ".") continue;
// check for image files
$f = escapeshellarg("$fulldir$entry");
$mimetype = trim(`file -bi $f`);
foreach($imagetypes as $valid_type) {
if(preg_match("#^{$valid_type}#", $mimetype)) {
$retval[] = array(
'file' => "/$dir$entry",
'size' => getimagesize("$fulldir$entry")
);
break;
}
}
}
$d->close();
return $retval;
}
?>
<?PHP
// fetch image details
$images = getImages("galleries/photo-of-the-day/images");
$today = date("Ymd") . ".jpg";
// display on page
sort($images, SORT_REGULAR);
foreach($images as $img ) {
if ($img == "20120822.jpg" ) {
break;
} else {
?>
<div style="margin-right: 10px; float: left; margin-bottom: 10px; padding-bottom: 10px; border: 1px #CCCCCC solid;">
<a href="<? echo $img['file']; ?>" rel="prettyPhoto" title="">
<img class="image-gals" src="<? echo $img['file']; ?>" style="width: 260px; margin-bottom: 0px;padding: 10px; " /></a>
Download
</div>
<?
}
}
?>
This is where you're populating your $images array:
$retval[] = array(
'file' => "/$dir$entry",
'size' => getimagesize("$fulldir$entry")
);
But when you compare them, you're doing this:
foreach($images as $img ) {
if ($img == "20120822.jpg" ) {
$img will contain an array. You'll need to check $img['file'], and that also has the directory name in, so it won't match just the image name.

Cannot change src of image with Javascript in some versions of Chrome

Never could have imagined that chrome would have been the browser giving me grief, but the slideshow for our new website does not function properly in some versions of Chrome.
The error occurs here:
"mainPicture.src = \''.$directory.$current_pic.'\'; setMarkerPos('.$i.')"
Claiming that I can't modify mainPicture, an id that doesn't exist.
Obviously, other browsers don't have a problem seeing this object.
All help is much appreciated!
.
You can find the page here.
Source code:
<?php
/********************************************************************
* GATHER IMAGES FROM IMAGE DIRECTORY *
********************************************************************/
// Define directory where images are stored
$directory = "../../images/slideshow/";
// Create blank array to store image names
$pic_array = array("");
$num_pics;
// Create number to define position of images in array
$counter = 0;
// Gather pictures from image directory
if(is_dir($directory))
{
// Open directory to view files
if($dh = opendir($directory))
{
// Continue while still files to view
while(($file = readdir($dh)) !== false)
{
// Stop if picture limit of 6 reached
if($counter == 6)
break;
// Gather if object found is file or directory
$file_check = filetype($directory.$file);
// If object is a file, add it to the slideshow
if ($file_check == "file")
{
$extension = substr($file, strpos($file, "."));
if ($extension == ".png" || $extension == ".jpg")
{
$pic_array[$counter] = $file;
$counter++;
}
}
}
}
}
// Determine number of pics gathered
$num_pics = count($pic_array);
?>
<html>
<head>
<link href="scripts/slideshow.css" rel="stylesheet" type="text/css">
<?php
/********************************************************************
* CONTROL BEHAVIORS OF SLIDESHOW *
********************************************************************/
?>
<!-- Begin script to control slideshow -->
<script type = "text/javascript">
var thumbTop = 450; // starting value of thumb.style.top (make sure multiple of increment)
var highestTop = 342; // highest point mask can be on screen ,-, (make sure multiple of increment)
var lowestTop = 450; // lowest point mask can be on screen ,_, (make sure multiple of increment)
var delay = 2; // speed in which slide up and down methods are called
var increment = 5; // value that thumbTop increments with each method call
var intervalUp; // interval for thumb upward movements
var intervalDown; // interval for thumb downward movements
function startThumbSlideUp()
{
window.clearInterval(intervalDown);
intervalUp = window.setInterval(thumbSlideUp,delay);
}
function startThumbSlideDown()
{
window.clearInterval(intervalUp);
intervalDown = window.setInterval(thumbSlideDown,delay);
}
function thumbSlideUp()
{
thumbTop -= increment;
if (thumbTop <= highestTop)
{
thumbTop = highestTop;
window.clearInterval(intervalUp);
}
else
thumbMask.style.top = thumbTop;
}
function thumbSlideDown()
{
// Added to fix issue where images would start from too large a height
if (thumbTop <= highestTop)
thumbTop = highestTop;
thumbTop += increment;
if (thumbTop >= lowestTop)
{
thumbTop = lowestTop;
window.clearInterval(intervalDown);
}
else
thumbMask.style.top = thumbTop;
}
// Move marker above image <pos>
function setMarkerPos(pos)
{
marker.style.left = 600 - (66 * (pos)) + 19;
}
</script>
</head>
<?php
/********************************************************************
* DISPLAY SLIDESHOW *
********************************************************************/
// Start body and make images unhighlightable
echo '<body onselectstart="return false" style="margin: 0px;">';
// Create base value to increment horizontal position of thumbnails
$curr_thumb_left = 595; // (ignore this comment) 660<width of image> - 66<width of thumb> - 10<space between side> // 660
// Create and display main (large) image and image thumbnails
echo '<div id="mask" onmouseout = "startThumbSlideDown()" onmouseover = "startThumbSlideUp();">
';
echo '<img src = "'.$directory.$pic_array[0].'" id = "mainPicture" height = "420" width = "660" style = "z-index: -1; position:absolute;"/>
';
echo '<div id="thumbMask" height="66" width="660" style="z-index: 1; top: 450px; position: absolute;">
';
echo '<img id="marker" src="images/marker.png" height="10" width="10" style="z-index: 2; top: 0px; position: absolute;" onload="setMarkerPos(0);"/>';
// Search through image array, then assign names to and display thumbnails
for ($i=0; $i < $num_pics; $i++)
{
// Point to pic in array
$current_pic = $pic_array[$i];
// Create and display image thumbnails
if ($current_pic !== "")
{
echo '<img src = "'.$directory.$current_pic.'" id = "thumb'.$i.'" height = "50" width = "50" style = "left:'.$curr_thumb_left.'px; top: 10px; border: 3px white solid; position: absolute;" onclick = "mainPicture.src = \''.$directory.$current_pic.'\'; setMarkerPos('.$i.')"/>
';
// Move left value to the left [50px width + (3px padding * 2 sides) + 10px space between = 66px]
$curr_thumb_left -= 66;
}
}
echo '</div>';
echo '</div>';
?>
</body>
</html>
Chrome doesn't make image elements available by just their "id" value; you have to use document.getElementById("mainPicture") to get a reference to the DOM element. That'll work in all browsers anyway, so it's safe to just code it that way.
You are attempting to alter the src of mainPicture as though it were a global variable:
mainPicture.src = '.....';
Try referencing mainPicture by its id instead:
document.getElementById('mainPicture').src = '......';
You're not actually setting what mainPicture is, other browsers must be guessing whereas Chrome is doing what it should. Change:
echo '<img src = "'.$directory.$current_pic.'" id = "thumb'.$i.'" height = "50" width = "50" style = "left:'.$curr_thumb_left.'px; top: 10px; border: 3px white solid; position: absolute;" onclick = "mainPicture.src = \''.$directory.$current_pic.'\'; setMarkerPos('.$i.')"/>
to
echo '<img src = "'.$directory.$current_pic.'" id = "thumb'.$i.'" height = "50" width = "50" style = "left:'.$curr_thumb_left.'px; top: 10px; border: 3px white solid; position: absolute;" onclick = "document.getElementById('mainPicture').src = \''.$directory.$current_pic.'\'; setMarkerPos('.$i.')"/>

Categories