PHP - Mmh ... Can't Find A Php Scraper Code Or Php Comments Library. Do You Know Where
Hello happy phpkkies,
I search this forum for a sample php code on how to write a links scrapper that will recursively go through each page within a site and pull all the links. Then, I will save them to a database for analysis. I couldn't find something like that. Also, I was wondering if someone has or is selling a comments library in php. This is, a code or a set of functions that are related to commenting systems. For example; the library should have a function for blocking bad words or a function that will let people vote up or down comments made. Any ideas or links will be appreciated, thank you, V. Similar TutorialsThis topic has been moved to Third Party PHP Scripts. http://www.phpfreaks.com/forums/index.php?topic=356789.0 Hi guys, I am making a bot which only scrapes the source code of the site AFTER logging into the site.The script to login is : Code: [Select] <?php $username="xxx"; $password="iwonttellyou"; $url="http://internet.com/login.php"; $cookie="cookie.txt"; $postdata = "name=".$username."&password=".$password; $ch = curl_init(); curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6"); curl_setopt ($ch, CURLOPT_TIMEOUT, 60); curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 0); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie); curl_setopt ($ch, CURLOPT_REFERER, $url); curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata); curl_setopt ($ch, CURLOPT_POST, 1); $result = curl_exec ($ch); echo $result; ?> I can see different SESSION ID's in cookie.txt everytime i compile this code, which makes me believe its working.However what next? How should i go to that site again, already logged in and scrape the data ? Some suggestions would be nice. Hey php developers. I'm Brent from Beanstream. We just recently opened up some code bounties to create a PHP SDK that uses our payment gateway API. Each bounty is around 1-5 hours work and their reward is between $150 and $400. The SDK is open source (MIT license) and will be hosted on GitHub. There are already 2 other SDKs written in Java and C# that use the same RESTful payments API, so a lot of the code and functionality can be copied over to the PHP SDK. If you are interested in helping out you can sign up here. You can also check out Beanstream's Payments API to see what the SDK will be implementing: http://developer.beanstream.com Feel free to message me if you have questions. Cheers, Brent Beanstream Internet Commerce I have a problem with the "comments count" in the toggle link in my blog: www.albertosotophotography.com
I have this script for show/hide comments in main page:
<script type= "text/javascript"> // Show/Hide Comments jQuery(document).ready(function() { // Get #comments div var uniqueAppend = 1; var tempName = 'comments'; while(jQuery("#comments").length > 0 ){ jQuery("#comments").attr('id',tempName + uniqueAppend++).addClass('commentContainer') } var commentsDiv = jQuery('.commentContainer'); // Only do this work if that div isn't empty if (commentsDiv.length) { // Hide #comments div by default jQuery(commentsDiv).hide(); // Append a link to show/hide jQuery('<a/>') .attr('class', 'toggle-comments') .attr('href', '#') .html('Notes') .insertAfter(commentsDiv); // Encase button in .toggle-comments-container div jQuery('.toggle-comments').wrap(jQuery('<div/>', { class: 'toggle-comments-container' })) // When show/hide is clicked jQuery('.toggle-comments').on('click', function(e) { e.preventDefault(); // Show/hide the div using jQuery's toggle() var commentContainer = jQuery(this).parent('.toggle-comments-container').prev('.commentContainer'); jQuery(commentContainer).slideToggle('slow', function() { // change the text of the anchor var anchor = jQuery(commentContainer).siblings('.toggle-comments-container').children('.toggle-comments'); var anchorText = anchor.text() == 'Notes' ? 'Hide' : 'Notes'; jQuery(anchor).html(anchorText); }); }); } // End of commentsDiv.length }); // End of Show/Hide Comments </script>I use: .html('<?php comments_number( '0 notes', '1 note', '% notes' ); ?>')for name the "comments toggle link" with the count of comments for each single post. The problem is that all posts shows the same count: the comments presents in the first post. Someone can help me? Alberto hello I've some code and I want find and cut url from it using php. this url link between 1 - 5 link. this mean some times 1 URL in the code sometimes 2 url in the code and ... can anyone help me? Code: [Select] MB</div><br/> <br/> <br/> <b><br/> DOWNLOAD<br/> <br/> <a href="http://uploading.com/files/c2182562/LIBERO%252B24%252BLUGLIO%252B2010.pdf/" target="_blank" rel="nofollow">http://uploading.com/files/c2182562/LIBERO%2B24%2BLUGLIO%2B2010.pdf/</a><br/> <br/> <br/> <br/> <br/> <a href="http://rapidshare.com/files/408736098/LIBERO_24_LUGLIO_2010.pdf.html" target="_blank" rel="nofollow">http://rapidshare.com/files/408736098/LIBERO_24_LUGLIO_2010.pdf.html</a></b> </div> <table class='file-express' width='100%'> <tr> <td style='text-align: left; color: #B2AC94; font-size: 3'><br>titletm= LIBERO 24 LUGLIO 2010 LIBERO 24 LUGLIO 2010 :found<br><font color="blue">2</font>http://www.avaxhome.ws/magazines/everyday_practical_electronics_vol_33_no_5_2004.html<br>File exists.dllink'MB</div><br/> <br/> <br/> This topic has been moved to PHP Regex. http://www.phpfreaks.com/forums/index.php?topic=306039.0 Hey all, Basically I have this code which technically should work, but I have put an error in the logic somewhere and am really struggling to find it, I've been going over it for about an hour now :/ The error is that in the second part (// Enter them into the activities database if they're not already there), it won't enter them, and it won't show the word 'Randomevent1' either, so clearly somehow I have put in something to prevent it performing that step. Can anybody help me out? I'd be amazingly grateful, I have no clue how I've screwed it up. if(isset($_POST['submit'])){ $ownerid = $_SESSION['id']; // If completed = Y give an error $completeyn = "SELECT completed FROM activities WHERE playerno='$ownerid' AND activityno = '1'"; $completecheck=mysql_query($completeyn) or die(mysql_error()); while($row = mysql_fetch_array( $completecheck )) { if($row['completed'] == 'Y'){ echo 'Oops, you\'ve already done this twice today!';} else { // Enter them into the activities database if they're not already there $stepno2 = "SELECT playerno, timesdone FROM activities WHERE playerno='$ownerid' AND activityno = '1'"; $stepnoanswer2=mysql_query($stepno2) or die(mysql_error()); $num_rows2 = mysql_num_rows($stepnoanswer2); echo $num_rows2; if($num_rows2 == '0'){ $putintodb2 = mysql_query("INSERT INTO activities (playerno, activityno, timesdone) VALUES ('$ownerid', '1', '1')") or die("Error: ".mysql_error()); echo 'Randomevent1'; }else{ // If they are already there update their stepcount $updatestepcount2=("UPDATE activities SET timesdone=timesdone+'1' WHERE playerno='$ownerid' AND activityno = '1'"); $newstepcount2=mysql_query($updatestepcount2); echo 'Randomevent2';} // If this new stepcount is equal to 2, set completed to Y $checkstep = "SELECT timesdone FROM activities WHERE playerno='$ownerid' AND activityno = '1'"; $checkstepresult=mysql_query($checkstep) or die(mysql_error()); while($row = mysql_fetch_array( $checkstepresult )) { if($row['timesdone'] == '2'){ echo $row['timesdone']; $updatestepcount22=("UPDATE activities SET completed = 'Y' WHERE playerno='$ownerid' AND activityno = '1'"); $newstepcount22=mysql_query($updatestepcount22); } }}}} Here's a neat little script that you simply use by calling yourscript.php?microsoft (where microsoft is any keyword you want) and it returns 100 related keywords. It's pretty raw in it's form. I didn't write it. Purely for learning, I'm trying to figure out how to 1) issue a line break between each item in the elements of the arry? 2) return only the keywords and not the associated array info. Currently, it returns results like: Array ( => microsoft [1] => microsoft security essentials [2] => microsoft office [3] => microsoft templates [4] => microsoft updates [5] => microsoft silverlight [6] => microsoft word [7] => microsoft money [8] => microsoft office 2010 [9] => microsoft clip art [10] => microsoft [11] => microsoft security essentials [12] => microsoft office [13] => microsoft templates [14] => microsoft updates [15] => microsoft silverlight [16] => microsoft word [17] => microsoft money [18] => microsoft office 2010 [19] => microsoft clip art [20] => microsoft security essentials [21] => microsoft security essentials review [22] => microsoft security essentials alert [23] => microsoft security essentials update [24] => microsoft security essentials 2.0 I'm wanting to know how to make it return results like... microsoft microsoft security essential microsoft office microsoft templates etc.... Code: [Select] <?php function text_between($start,$end,$string) { if ($start != '') {$temp = explode($start,$string,2);} else {$temp = array('',$string);} $temp = explode($end,$temp[1],2); return $temp[0]; } function gsscrape($keyword) { $keyword=str_replace(" ","+",$keyword); global $kw; $data=file_get_contents('http://clients1.google.com/complete/search?hl=en&q='.$keyword); $data=explode('[',$data,3); $data=explode('],[',$data[2]); foreach($data as $temp) { $kw[]= text_between('"','"',$temp); } } #simple to use, just use yourscriptname.php?keywords if ($_SERVER['QUERY_STRING']!='') { gsscrape($_SERVER['QUERY_STRING']); foreach ($kw as $keyword) { gsscrape($keyword); } #all results are in array $kw... print_r($kw); } ?> When clicking on the link "groups", there is no problem printing out the first level subgroups. But when clicking on any of the subgroup, the second level subgroups are not being displayed. I have or die(mysql_error()); after some queries but I can not see what is the error. It always gives the same message: Quote No Products Found. Sorry, but there are no products in this section at the moment. The products are constantly being updated, however. Please try again later or contact us. How would I find out which part of the code fails? The code: <?php include 'scrptz/functions.php'; // Page vars $thisPage=$getVars["page"]; if($thisPage<1)$thisPage=1; $firstGroup=($thisPage*16)-16; // Get group details and stick them into an array $qMain="SELECT * FROM PGroups WHERE PG = '".$getVars["prodg"]."'"; $result=mysql_query($qMain) or die(mysql_error()); $groupDetails=mysql_fetch_array($result); // Get all sub groups in current product group $qMain="SELECT * FROM SubG WHERE ProdG = '".$getVars["prodg"]."'"; $result=mysql_query($qMain) or die(mysql_error()); // Stick sub groups in a 2D associative array $j=0; while ($row=mysql_fetch_array($result)) { foreach($row as $i=>$data)$array[$j][$i]=$data; $j++; } // Calculate vars for navigation $totalGroups=$j; $totalPages=ceil($totalGroups/16); // Set page title (for bookmark) $pageTitle=$groupDetails["GPname"]; // Set top title if($totalGroups>0){$topTitle="VIEW PRODUCTS";}else{$topTitle="ERROR";} ?> <html> <head> <title>Lock-Tech® Hi-Specification Architectural Hardware</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <link href="scrptz/styles.css" rel="stylesheet" type="text/css"> <script language="JavaScript" type="text/javascript">var theID="<?php echo $getVars['uid']; ?>";</script> <script language="JavaScript" src="scrptz/content.js" type="text/javascript"></script> <script language="JavaScript" src="scrptz/menu.js" type="text/javascript"></script> <script language="JavaScript" src="scrptz/scripts.js" type="text/javascript"></script> </head> <body background="imgz/bg.gif" leftmargin="0" topmargin="0" marginheight="0" marginwidth="0"<?php echo $notify ?>> <?php include("top.php"); ?> <table width="952" height="509" border="0" cellpadding="0" cellspacing="0" class="maintext"> <?php if($sessions['accCode']){?><form action="http://www.lock-tech.co.uk/index.php" method="post" name="logout" target="_parent"><input name="account" type="hidden" value="<?php echo $sessions['accCode']; ?>"><input name="killSession" type="hidden" value="<?php echo $getVars['uid']; ?>"></form><?php }?> <tr> <td width="1" rowspan="5" bgcolor="#000000"></td> <td height="21" background="imgz/topbar.gif" bgcolor="#14359E"> </td> <td height="21" colspan="5" valign="middle" background="imgz/topbar.gif" bgcolor="#14359E" class="mainyellow"><?php include("scrptz/dd_menu.php"); ?></td> <td height="21" background="imgz/topbar.gif" bgcolor="#14359E"> </td> <td width="1" rowspan="5" bgcolor="#000000"></td> </tr> <tr> <td width="5" rowspan="3"> </td> <td width="306" height="30" valign="bottom" class="title2"><?php echo $groupDetails["GPname"] ?></td> <td width="11" rowspan="3"><img src="imgz/maindiv.gif" width="11" height="466"></td> <td width="306" height="30" align="center" valign="bottom" class="title2"><?php if($totalGroups>0){?><a href="g_view.php?pgroup=<?php echo $groupDetails["PG"] ?>&uid=<?php echo $getVars['uid']; ?>" class="link4" onmouseover="window.status='View List of all Products in <?php echo $groupDetails["GPname"] ?>'; return true">VIEW ALL</a> | <a href="g_browse.php?pgroup=<?php echo $groupDetails["PG"] ?>&uid=<?php echo $getVars['uid']; ?>" class="link4" onmouseover="window.status='Browse all Products in <?php echo $groupDetails["GPname"] ?>'; return true">BROWSE ALL</a><?php }?></td> <td width="11" rowspan="3"><img src="imgz/maindiv.gif" width="11" height="466"></td> <td width="306" height="30" align="center" valign="bottom"> </td> <td width="5" rowspan="3"> </td> </tr> <tr> <td height="20" valign="top" class="mainbold"></td> <td width="306" rowspan="2" valign="top" class="maintext"> <?php for($i=$firstGroup; $i<($firstGroup+8) && $i<$totalGroups; $i++){?> <a href="sub.php?PSubG=<?php echo $array[$i]["SPG"] ?>&uid=<?php echo $getVars['uid']; ?>" class="link1" onmouseover="window.status='View Products in <?php echo $array[$i]["SPGname"] ?>'; return true"><?php echo $array[$i]["SPGname"] ?></a><br> <?php // Get all subsubs in current sub group $qMain="SELECT * FROM SubSubG WHERE SPG = '".$array[$i]["SPG"]."'"; $result=mysql_query($qMain) or die(mysql_error()); // Print subsubs while ($row=mysql_fetch_array($result)) { ?> [<a href="subsub.php?PSubSubG=<?php echo $row["SSPG"]?>&uid=<?php echo $getVars['uid']; ?>" class="link3" onmouseover="window.status='View Products in <?php echo $row["SSPGName"]?>'; return true"><?php echo $row["SSPGName"]?></a>] <?php } ?> <br><br> <?php }?></td> <td width="306" rowspan="2" valign="top" class="maintext"> <?php for($i=$firstGroup+8; $i<($firstGroup+16) && $i<$totalGroups; $i++){ ?> <a href="sub.php?PSubG=<?php echo $array[$i]["SPG"] ?>&uid=<?php echo $getVars['uid']; ?>" class="link1" onmouseover="window.status='View Products in <?php echo $array[$i]["SPGname"] ?>'; return true"><?php echo $array[$i]["SPGname"] ?></a><br> <?php // Get all subsubs in current sub group $qMain="SELECT * FROM SubSubG WHERE SPG = '".$array[$i]["SPG"]."'"; $result=mysql_query($qMain) or die("<font color=\"#FF0000\">ERROR {9.4}! Please navigate to a <a href=\"main.php?uid=".$getVars['uid']."\">different page</a> and then try this page again.</font>"); // Print subsubs while ($row=mysql_fetch_array($result)) { ?> [<a href="subsub.php?PSubSubG=<?php echo $row["SSPG"]?>&uid=<?php echo $getVars['uid']; ?>" class="link3" onmouseover="window.status='View Products in <?php echo $row["SSPGName"]?>'; return true"><?php echo $row["SSPGName"]?></a>] <?php } ?> <br><br> <?php }?></td> </tr> <tr> <td height="416" valign="top" class="mainbold"> <?php if($totalGroups>0) { ?> <img src="grp_pics/<?php echo $groupDetails["PG"] ?>.jpg" alt="Group Picture" galleryimg="no"><br><img src="imgz/pixel.gif" width="306" height="5"><br> <?php echo $groupDetails["GPText"] ?><?php } else { ?> or die(mysql_error()); <p class="noresult">No Products Found.</p><p class="mainbold">Sorry, but there are no products in this section at the moment. The products are constantly being updated, however. Please try again later or <a href="mailto:sales@lock-tech.co.uk" class="link1" onmouseover="window.status='Send us an Email.'; return true">contact us</a>.</p><?php }?></td> </tr> <tr> <td width="5" height="22" background="imgz/btmbar.gif" bgcolor="#14359E"> </td> <td width="306" height="22" align="center" valign="top" background="imgz/btmbar.gif" bgcolor="#14359E"><a href="javascript:history.back()" onmouseover="prev_btn.src='imgz/prev2.gif';window.status='Previous Page'; return true" onmouseout="prev_btn.src='imgz/prev.gif'"><img name="prev_btn" src="imgz/prev.gif" width="124" height="16" border="0"></a></td> <td width="11" height="22" bgcolor="#14359E"><img src="imgz/btmdiv.gif" width="11" height="22"></td> <td width="306" height="22" align="center" background="imgz/btmbar.gif" bgcolor="#14359E" class="nav"><? include 'scrptz/nav.php' ?></td> <td width="11" height="22" bgcolor="#14359E"><img src="imgz/btmdiv.gif" width="11" height="22"></td> <td width="306" height="22" align="center" valign="top" background="imgz/btmbar.gif" bgcolor="#14359E"><a href="javascript:directLink('<?php echo $prodLink; ?>','<? echo $pageTitle ?>')" onmouseover="link_btn.src='imgz/link2.gif'; window.status='Direct Link to This Page'; return true" onmouseout="link_btn.src='imgz/link.gif'"><img name="link_btn" src="imgz/link.gif" alt="" width="182" height="16" border="0"></a></td> <td width="5" height="22" background="imgz/btmbar.gif" bgcolor="#14359E"> </td> </tr> </table> </body> </html> Hi
I have a MySql database and wondered if there is a code to search a table field with a given string and display the number of unique occurrences.
The table is asterisk_cdr and would like to know how many calls received daily on a perticular channel.
Thanks
shmideo
Dear Members, I am a PHP developer and desisgning a WAP page for mobiles.I need some php code to find out the model of a mobile phone from where request is coming so that based on that information I can upload the proper CSS for my page.If you can give me some hints as well that would also help me to proceed further.Currently I am able to fetch user-agent of mobile but not able to find out the specific model of mobile. Hi, how i could do this with gdlibrary: I make image with imagecreatefrompng , and that is my pictures background. Then I add image there, and that is my bird flying in the background. that is only example, i wanna just add image to image I'm trying to write a script that will copy images from one website (a supplier, in this case puma) and save them to the dealer's web server. I have already done this for other supplier's websites but puma uses png's instead of jpeg's and I believe that is what is causing my issues: The original image looks like this: The copied image some odd colors in the background like this: Here is the code: Code: [Select] $puma_image = "http://www.pumab2b.com/_static/images/styleColors/1234560002/" . str_replace(" ", "", $Item_Num) . "_1.png"; $image = imagecreatefrompng($puma_image); if ($image) { //Save image to Soccer Etc server (images folder): if (imagepng($image, "prod_images/" . $cur_Item['Item_Num'] . ".png", 0)) { //DO some other stuff here } } I just noticed after posting the original image on this forum, that it is actually transparent. I'm guessing this has something to do with my problems? Hi, I would like my users to create and save forms via mysql. They should be able to choose what field they want to use, and other users should be able to fill the forms into mysql. Any ideas on how to accomplish this? I want to get the ibase_blob_echo function and I was told I need to uncomment the extension=php_interbase.dll in my php.ini. So I did and now I get the message: Unable to Load Dynamic Library in a pop-up window. I'm lost and don't know how to solve this Hi everyone. There are two nice script which are advanced for me to understand. There is a Knockout tournament scheduler class that makes image of the bracket. and there is a code that makes html of the bracket with jquery. I want to use the class with jquery. but I don't know how to do that and where to start. the class below needs to implement to this http://whileonefork.blogspot.com/2010/10/jquery-json-to-draw-elimination-single.html I attached the php script. please help me! Code: [Select] <?php class KnockoutGD extends Knockout { private $im = null; // GD-lib image resource. private $tc = 0; // Text color. public function getImage($tourName = '') { /* Returns a GD-lib image resource */ // Initial testing. if (empty($this->roundsInfo)) return null; // Dimensional parameters. $fh = imagefontheight(FONT); $fw = imagefontwidth(FONT); $lpad = 30; // Line (branch) padding before and after competitor names and after scores. $hpad = 20; // Outer horizontal image padding. $vpad = 60; // Outer vertical image padding. $lw = $this->getStrLen()*$fw + 3*$lpad; // Line (branch) width. Where getStrLen() gets the length of the longest string used in the image. // Initial calls. $dimensions = $this->getDimens($fh, $lw, $hpad, $vpad); $this->im = imagecreate($dimensions['x'], $dimensions['y']); $bg = imagecolorallocate($this->im, 255, 255, 255); // Set background color. $this->tc = imagecolorallocate($this->im, 0, 0, 0); // Text color. $this->mkStr($dimensions['x'] - $hpad - imagefontwidth(LFONT)*strlen($tourName), $dimensions['y'] - $vpad/2, $tourName, LFONT); // Print tournament name. // Initial positioning values from which drawing begins. $rx = $hpad; // Round X-position. $ry = $vpad; // Round Y-position. $depth = 1; // Branch depth. // Start drawing the tournament bracket/tree. foreach ($this->roundsInfo as $r => $info) { $n = $info[1]; // Number of expected players in round $r. // If a match is no yet created, then a placeholder is made so that the bracket structure is still printable. for ($m = 0; $m <= $n/2 - 1; $m++) { if (!$this->isMatchCreated($m, $r)) { $this->bracket[$r][$m]['c1'] = $this->bracket[$r][$m]['c2'] = null; $this->bracket[$r][$m]['s1'] = $this->bracket[$r][$m]['s2'] = -1; } } // Now we generate round branches. $x = $rx; $y = $ry; $bheight = pow(2, $depth) * $fh; // This is the height of a match-branch, which increases as the tree depth increases. ksort($this->bracket[$r]); foreach ($this->bracket[$r] as $m) { for ($i = 1; $i <= 2; $i++, $y += $bheight) { $this->mkStr($x+$lpad, $y, $m['s'.$i] == -1 ? 'Undecided' : $m['c'.$i]); $this->mkStr($x+$lw-$lpad, $y, $m['s'.$i] == -1 ? '?' : $m['s'.$i]); $this->mkLine($x, $y+$fh, $x+$lw, $y+$fh); } $this->mkLine($x+$lw, ($y+$fh)-$bheight, $x+$lw, ($y+$fh)-2*$bheight); } // Get ready for next loop. $rx += $lw; $ry += $bheight/2; $depth++; } // Add final branch/line for the tournament winner $fr = end(array_keys($this->roundsInfo)); // Final round. $s1 = $this->bracket[$fr][0]['s1']; $s2 = $this->bracket[$fr][0]['s2']; $winner = (!array_key_exists(0, $this->bracket[$fr]) || $s1 == -1 || $s2 == -1 || $s1 === $s2) ? '?' : (($s1 > $s2) ? $this->bracket[$fr][0]['c1'] : $this->bracket[$fr][0]['c2']); $this->mkStr($rx+$lpad, $ry, 'Winner: ' . $winner); $this->mkLine($rx, $ry+$fh, $rx+$lw, $ry+$fh); // Now, we print the round titles. array_push($this->roundsInfo, array('Champion', 1)); // Add fictitious round for printing purposes only. foreach (array_reverse($this->roundsInfo) as $r) { $this->mkStr($rx+$lpad, $vpad/3, $r[0], LFONT); $rx -= $lw; // Move back one round/column. } array_pop($this->roundsInfo); // Remove fictitious round entry again. return $this->im; } private function mkLine($x0, $y0, $x, $y) { /* Wrapper for function that creates a line. */ imageline($this->im, $x0, $y0, $x, $y, $this->tc); } private function mkStr($x, $y, $str, $font = false) { /* Wrapper for function that writes a string. */ imagestring($this->im, $font ? $font : FONT, $x, $y, $str, $this->tc); } private function getDimens($fontHeight, $lineWidth, $horizPad, $vertPad) { /* Returns image dimensions based on the tournament bracket. */ /* Vertically: Each match-branch is outputted like this: Team A ----------- Padding Team B ----------- Padding ... where "Padding" and "Team X" are of height $fontHeight, and "------" are branch lines with approximately no height. Horizontally: Each branch is outputted like this: ----- Team A ------ | ----- Team C ------ | ----- Team B ------ ... where "Team X" branch has an absolute length of $lineWidth. The above therefore illustrates a length of 2*$lineWidth. The image length, $x, must be: $horizPad + number_of_rounds * $lineWidth + $horizPad And the image height, $y, must be: $vertPad + number_of_matches_in_first_round * 4*$fontHeight + $vertPad ... since the first round contains the most matches. */ $frGames = count($this->bracket[1]); // Number of games in the first round. $playInExists = !empty($this->bracket[0]) ? true : false; /* The y-size of the image must be calculated accordingly to the above description. Though, if a play-in round exists, then the play-in round is potentially the round which requires the most vertical space to draw. In this case we scale the image as if the play-in round was the first round. Due to the nature of the tournament bracket, this means that there are twice as many games in that round. */ $y = 2*$vertPad + ($playInExists ? $frGames*2 : $frGames) * 4*$fontHeight; /* The x-size of the image is proportional to the number of rounds in the tournament, where the proportionality constant is the length of a branch, $lineWidth, ie. the width of a round. Since the number of players in the first round is equal to 2^R, where R is a whole number, and denotes the number of rounds required in the tournament, then R = log(players, 2), where "players" also can be found by 2 * matches_in_first_round (2 players pr. match). Like above, if a play-in round exists the x-size of the image must be changed. In this case, we merely add the length of a branch to the total x-size, since all branches are equal in length. Besides that, we add another whole branch length for the Winner/Champion branch, which technically is not a part of the tournament bracket, but is shown anyway. */ $x = 2*$horizPad + (log($frGames*2, 2) + ($playInExists ? 1 : 0) + 1) * $lineWidth; return array('x' => $x, 'y' => $y); } private function getStrLen() { /* Returns the length of longest string used in either rounds. This is done by looking in both play-in round and first round, since all competitors are to be found there. */ $len = 0; foreach (array_merge(array_key_exists(0, $this->bracket) ? $this->bracket[0] : array(), $this->bracket[1]) as $m) { if (($newlen = strlen($m['c1'])) > $len) $len = $newlen; if (($newlen = strlen($m['c2'])) > $len) $len = $newlen; } foreach ($this->roundsInfo as $arr) { if (($newlen = strlen($arr[0])) > $len) $len = $newlen; } return $len; } } ?> What do I need to do in order to use the libssh2 library? Hello, what's the correct use of GD library to compress JPG images please? I am using this upload script with TinyMCE. See below : I have this snippet but it doesn't compress the image: // Accept upload if there was no origin, or if it is an accepted origin // If image is JPEG compress with GD library $filetowrite = $imageFolder . $temp['name']; if (in_array(strtolower(pathinfo($temp['name'], PATHINFO_EXTENSION)), array("jpg", "jpeg"))) { imagejpeg($temp['tmp_name'], $filetowrite, 75); } else { move_uploaded_file($temp['tmp_name'], $filetowrite); } <?php $accepted_origins = array("http://localhost", "http://127.0.0.1", "http://192.168.1.1", "http://example.com"); $month = strtolower(date('M')); $year = date('Y'); $newspath = "img/news/"; if (!is_dir("$newspath/$year/$month")) { mkdir("$newspath/$year/$month", 0777, true); } $imageFolder = "$newspath/$year/$month/"; reset ($_FILES); $temp = current($_FILES); if (is_uploaded_file($temp['tmp_name'])){ if (isset($_SERVER['HTTP_ORIGIN'])) { // same-origin requests won't set an origin. If the origin is set, it must be valid. if (in_array($_SERVER['HTTP_ORIGIN'], $accepted_origins)) { header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']); } else { header("HTTP/1.1 403 Origin Denied"); return; } } /* If your script needs to receive cookies, set images_upload_credentials : true in the configuration and enable the following two headers. */ // header('Access-Control-Allow-Credentials: true'); // header('P3P: CP="There is no P3P policy."'); // Sanitize input if (preg_match("/([^\w\s\d\-_~,;:\[\]\(\).])|([\.]{2,})/", $temp['name'])) { header("HTTP/1.1 400 Invalid file name."); return; } // Verify extension if (!in_array(strtolower(pathinfo($temp['name'], PATHINFO_EXTENSION)), array("gif", "jpg", "jpeg", "png"))) { header("HTTP/1.1 400 Invalid extension."); return; } // Accept upload if there was no origin, or if it is an accepted origin // If image is JPEG compress with GD library $filetowrite = $imageFolder . $temp['name']; if (in_array(strtolower(pathinfo($temp['name'], PATHINFO_EXTENSION)), array("jpg", "jpeg"))) { imagejpeg($temp['tmp_name'], $filetowrite, 75); } else { move_uploaded_file($temp['tmp_name'], $filetowrite); } // Respond to the successful upload with JSON. // Use a location key to specify the path to the saved image resource. // { location : '/your/uploaded/image/file'} // echo json_encode(array('location' => $filetowrite)); $passpath = $year.'/'.$month.'/'.$temp['name']; echo json_encode(array('location' => $passpath)); } else { // Notify editor that the upload failed header("HTTP/1.1 500 Server Error"); } ?>
Font size GD Library Hi All I'm trying to create a font tester - http://www.ttmt.org.uk/fonts/index.php (this demo doesn't use the font I'm using.). I'm using the GD library to create images of the text. I'm not happy with the quality of the fonts at small sizes. I've tried everything to fix it but nothing is working. One suggestion I had was to create the fonts larger then reduce the size of the image. Can anyone offer any advise how I might do this? Code: [Select] <?php header('Content-Type: image/png'); $im = imagecreatetruecolor(1000, 200); $gray = imagecolorallocate($im, 240, 240, 240); $black = imagecolorallocate($im, 0, 0, 0); imagefilledrectangle($im, 0, 0, 1000, 199, $gray); $text = $_GET['text']; $textSize = $_GET['size']; $font = $_GET['font']; imagefttext($im, $textSize, 0, 15, 160, $black, $font, $text); imagepng($im); imagedestroy($im); ?> Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>untitled</title> <style type="text/css"> *{margin:0;padding:0;} #wrap{margin:20px 0 0 20px;} h1{margin:0px 0 20px 0;clear:both;} h2{font-size:1.1em;margin:15px 0 5px 0;} #top{padding:0 0 20px 0;} form{margin:0 0 20px 0;} </style> </head> <body> <div id="wrap"> <form action="index.php" method="post"> <!--<input type="text" name="text" value="<?php echo $_POST['text'];?>" />--> <select name="text" > <option value="<?php echo $_POST['text'];?>">Text</option> <option value="ABCDEFGHIJKLMNOPQRSTUVWXYZ">ABCDEFGHIJKLMNOPQRSTUVWXYZ</option> <option value="abcdefghijklmnopqrstuvwxyz">abcdefghijklmnopqrstuvwxyz</option> <option value="0123456789">0123456789</option> </select> <select name="size"> <option value="<?php echo $_POST['size'];?>">Size</option> <option value="10">10</option> <option value="12">12</option> <option value="14">14</option> <option value="18">18</option> <option value="24">24</option> <option value="30">30</option> <option value="38">38</option> <option value="42">42</option> <option value="50">50</option> <option value="60">60</option> <option value="80">80</option> <option value="100">100</option> </select> <input type="submit" name="submit" value="Set →" /> </form> <div id="top"> <?php $theFont="corbelb.ttf"; if(!empty($_POST['submit'])){ $myText = $_POST['text']; $mySize = $_POST['size']; echo '<img src="imageftt.php?text='.$myText.'&size='.$mySize.'&font='.$theFont.'">'; }else{ $myText = "Handgloves"; $mySize = 24; echo '<img src="imageftt.php?text='.$myText.'&size='.$mySize.'&font='.$theFont.'">'; } ?> </div> </div> </body> </html> Hey guys, I have created combined images from edits I had laying around. I have a chair, and i'm trying to combine different colored tops with a pair of legs using a radio button to choose the top color. Here is what I have so far for the form page: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Untitled Document</title> </head> <body> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <label>Seat Color Choices:</label><br> Red<input type="radio" name="color" value="red" id="red" onFocus="getElementById('config').src = 'red.php'" > Orange<input type="radio" name="color" value="orange" id="orange" onFocus="getElementById('config').src = 'orange.php'" > Ivory<input type="radio" name="color" value="ivory" id="ivory" onFocus="getElementById('config').src = 'ivory.php'" > Black<input type="radio" name="color" value="black" id="black" onFocus="getElementById('config').src = 'black.php'" > </form> <img src="black.php" id="config" alt="color choice for lola chair"> </body> </html> ...and here is one of my image files for an example: <?php //Report any errors ini_set ("display_errors", "1"); error_reporting(E_ALL); //Set the correct content type header('content-type: image/jpeg'); $base = imagecreatefromjpeg('lola_base.jpg'); $red = imagecreatefromgif('lola_red.gif'); $orange = imagecreatefromgif('lola_orange.gif'); $ivory = imagecreatefromgif('lola_ivory.gif'); $black = imagecreatefromgif('lola_black.gif'); imagecopy($base, $red, 0 , 0 , 0, 0,250, 250); imagejpeg($base); //Clear up memory used imagedestroy($base); ?> The problem is, I need to be able to dynamically change which images are being combined. I can't have a different file for each combo (ex. red.gif, black.gif, ivory.gif, etc.) I need it to create them on cue from a single file/function. Is there a way to do that with PHP GD library? |