PHP - High Score System
I try to get a high score system to work. The problem is to write data to the txt file:
The file adder.php contains: <?php if(array_key_exists('name',$_GET)==true and array_key_exists('score',$_GET)==true) { $name=$_GET['name']; $score=$_GET['score']; $file=fopen('highscore.txt','a'); fwrite($file,$name.';'.$score.';'); fclose($file); } header("Location: index.php"); // Replace index.php with the name (and, if not in the same folder, path) // of the page that will display the scores (see below) ?> I use this website: http://members.multimania.nl, so it looks like http://members.multimania.nl/mine/adder.php?name=winner&score=99 What am I doing wrong? Similar TutorialsHi all I have some code that displays the high scores for a game. Unfortunately, if a user has more than 1 high score in the table all scores for that user are displayed. I would like to only display the highest score per user. My Current Code Code: [Select] $sql_query = sprintf("SELECT * FROM `highscores` WHERE `gameID` = '106' ORDER BY `score` DESC"); //store the SQL query in the result variable $result = mysql_query($sql_query); if(mysql_num_rows($result)) { //output as long as there are still available fields while($row = mysql_fetch_row($result)) { echo ("$row[3] Scored :$row[5] <br>"); } } //if no fields exist else { echo "no values in the database"; } mysql_close($con); OutPut User1 300 User1 298 User 2 297 User1 296 User3 295 User2 290 I would like the output to be User1 300 User 2 297 User3 295 Any help is much appreciated hey guys. Hopefully someone can help me with this. I have been trying to figure out for a while now why the quiz score keeps incrementing even if i refresh the page. so far there is 2 quiz sections, firstly $_SESSION['score']; is incremented on every correct answer then this information is carried on to the second part of the quiz which increments $_SESSION['score'1]; However everytime a page is refreshed then it increments again. How can i get around this? Also note i have a questions and answers section (array of q's and a's) and a functions page. Any help would be great. Thanks in advance Lance Code: [Select] <?php session_name("Question_Test"); session_start(); $_SESSION['score']; require_once('questionsandanswers2.php'); require_once('functions.php'); if (!isset($_POST['submit'])) { $score1 = 0; $_SESSION['correct'] = array(); $_SESSION['wrong'] = array(); $_SESSION['finished'] = 'no'; if (isset($_SESSION['error'])) { unset($_SESSION['error']); $num = 0; } else { $score1 = 0; $_SESSION['score1'] = $score1; $_SESSION['correct'] = array(); $_SESSION['wrong'] = array(); $_SESSION['finished'] = 'no'; $num = 0; } } else { $num = (int) $_POST['num']; $postedanswers = str_replace("_"," ",$_POST['answers']); if ($postedanswers == $answers[$num]['0']) { $_SESSION['score1'] ++; $_SESSION['correct'][] = $postedanswers; } else { $_SESSION['wrong'][] = $postedanswers; } if ($num < count($questions)-1) { $num++; } else { $last = true; $_SESSION['finished'] = 'yes'; } } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>running an array</title> <?php if (!isset($last)) { echo "<script type=\"text/javascript\" src=\"form.js\"></script>"; } ?> </head> <body> <?php if (!isset($last)){?> <h1>Detection Section</h1> <h2>Questions <?php echo $num+1; ?>:</h2> <p><strong><?php echo $questions[$num]; ?></strong></p> <form id="questionBox" method="post" action="test2.php"> <?php $pattern = ' '; $replace = '_'; $shuffledAnswers = shuffle_assoc($answers[$num]); #var_dump($newanswers); foreach ($shuffledAnswers as $answer) { $answer2 = str_replace($pattern,$replace,$answer); echo "<li><input type=\"radio\" id=\"$answer2\" value=\"$answer2\" name=\"answers\" />\n"; echo "<label for=\"$answer2\">$answer</label></li>\n"; } ?> <input type="hidden" name="num" value="<?php echo $num; ?>" /> <input type="submit" id="submit" name="submit" value="Submit Answer" /></p> </form> <?php } else { $_SESSION['finalscore'] = $_SESSION['score'] + $_SESSION['score1']; echo "your final score is:</h2>\n <h3>{$_SESSION['finalscore']}/20</h3><h4>Verdict:</h4>"; if($_SESSION['finalscore'] <= 5) echo "<p id=\"verdict\"><span>S</span>everely <span>H</span>indered <span>I</span>n the <span>T</span>est!</p>\n"; if(($_SESSION['finalscore'] > 5) && ($_SESSION['finalscore'] <= 10)) echo "<p id=\"verdict\"><span>C</span>ould <span>R</span>ead <span>A</span>nd <span>P</span>ractice more.</p>\n"; if(($_SESSION['finalscore']) && ($_SESSION['finalscore'] <= 15)) echo "<p id=\"verdict\"><span>A</span>cronyms a<span>R</span>e <span>S</span>o <span>E</span>asy!</p>\n"; if($_SESSION['finalscore'] > 15) echo "<p id=\"verdict\"><span>S</span>uper <span>A</span>cronym <span>S</span>pecialist</p>"; echo "<p id=\"compare\"><a href=\"test2.php\">Next Section! <img src=\"images/arrow.png\" /></a></p>"; } ?> </body> </html> Hey guys, I have set a quiz up that pulls questions and answers from an array, every correct answer,.... score increments; however it is within a loop. Something must be wrong with the loop as it keep incrementing however i cant see why. Any help would be great, The main aim what i am trying to do is have 5 questions answered and go to different page (different topic for 5 more questions) however keep the on going score. Hope this makes sense. If not ill try and clear it up. Thanks for all your help guys in advance, i appreciate it also not, i have a functions.php, questionsandanswers.php Code: [Select] <?php session_name("Question_Test"); session_start(); echo $_SESSION['score']; require_once('questionsandanswers.php'); require_once('functions.php'); if (!isset($_POST['submit'])) { $score = 0; $_SESSION['score'] = $score; $_SESSION['correct'] = array(); $_SESSION['wrong'] = array(); $_SESSION['finished'] = 'no'; if (isset($_SESSION['error'])) { unset($_SESSION['error']); $num = 0; } else { $score = 0; $_SESSION['score'] = $score; $_SESSION['correct'] = array(); $_SESSION['wrong'] = array(); $_SESSION['finished'] = 'no'; $num = 0; } } else { $num = (int) $_POST['num']; $postedanswers = str_replace("_"," ",$_POST['answers']); if ($postedanswers == $answers[$num]['0']) { $_SESSION['score'] ++; $_SESSION['correct'][] = $postedanswers; } else { $_SESSION['wrong'][] = $postedanswers; } if ($num < count($questions)-1) { $num++; } else { $last = true; $_SESSION['finished'] = 'yes'; } } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>running an array</title> <?php if (!isset($last)) { echo "<script type=\"text/javascript\" src=\"form.js\"></script>"; } ?> </head> <body> <h1>Protection Section</h1> <?php if (!isset($last)){?> <h2>Questions <?php echo $num+1; ?>:</h2> <p><strong><?php echo $questions[$num]; ?></strong></p> <form id="questionBox" method="post" action="test1.php"> <?php $pattern = ' '; $replace = '_'; $shuffledAnswers = shuffle_assoc($answers[$num]); #var_dump($newanswers); foreach ($shuffledAnswers as $answer) { $answer2 = str_replace($pattern,$replace,$answer); echo "<li><input type=\"radio\" id=\"$answer2\" value=\"$answer2\" name=\"answers\" />\n"; echo "<label for=\"$answer2\">$answer</label></li>\n"; } ?> <input type="hidden" name="num" value="<?php echo $num; ?>" /> <input type="submit" id="submit" name="submit" value="Submit Answer" /></p> </form> <?php } else { echo "your final score is:</h2>\n <h3>{$_SESSION['score']}/20</h3><h4>Verdict:</h4>"; if($_SESSION['score'] <= 5) echo "<p id=\"verdict\"><span>S</span>everely <span>H</span>indered <span>I</span>n the <span>T</span>est!</p>\n"; if(($_SESSION['score'] > 5) && ($_SESSION['score'] <= 10)) echo "<p id=\"verdict\"><span>C</span>ould <span>R</span>ead <span>A</span>nd <span>P</span>ractice more.</p>\n"; if(($_SESSION['score'] > 10) && ($_SESSION['score'] <= 15)) echo "<p id=\"verdict\"><span>A</span>cronyms a<span>R</span>e <span>S</span>o <span>E</span>asy!</p>\n"; if($_SESSION['score'] > 15) echo "<p id=\"verdict\"><span>S</span>uper <span>A</span>cronym <span>S</span>pecialist</p>"; echo "<p id=\"compare\"><a href=\"test2.php\">Next Section! <img src=\"images/arrow.png\" /></a></p>"; } ?> </body> </html> I can't seem to figure out how to calculate the score the user gets when they hit the score button. I figured it would look something like this... $result_score = $right / 9 * 100.... but I've tried a few methods and I can't seem to figure out why its not working. Here is my code for the application.... Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Multiplication Test</title> </head> <body> <?php require_once('database.php'); define ('ROWS', 3); define ('COLS', 3); define ('MAX_NUMBER', 12); date_default_timezone_set('America/New_York'); if (isset($_POST['btn_score'])) { $result_name= $_POST['result_name']; $result_score= $_POST['result_score']; $result_score = / 9 * 100; $sql = "INSERT INTO results (result_name, result_score, result_date_time) VALUES ('$result_name','$result_score', NOW());"; $db->exec($sql); //print_r ($_POST); $time1 = $_POST['ts']; $time1_object = new DateTime($time1); $now = new DateTime(); $time_span = $now->diff($time1_object); $minutes = $time_span->format('%i'); $seconds = $time_span->format('%s'); $seconds+= $minutes * 60; echo "It took $seconds seconds to complete the test<hr />"; foreach ($_POST as $problem => $answer) { if ($problem <> "btn_score" && $problem <> "ts") { //echo "$problem -- $answer <br />"; $problem = explode('_', $problem); $num1 = $problem[2]; $num2 = $problem[3]; $right = $num1 * $num2; if ($answer != $right) { echo "$num1 * $num2 = $answer , The right answer is $right<br />"; } } } } ?> <h1>Multiplication Test</h1> <form name="lab5" method="post" action="lab5b.php"> <?php $now = new DateTime(); //echo $now->format('Y-m-d H:i:s'); echo "<input type='hidden' name='ts' value='" . $now->format('Y-m-d H:i:s') . "'>"; ?> <table border="1" cellspacing="5" cellpadding="5"> <?php $no_of_problems = 0; for ($row=0; $row<ROWS; $row++) { echo "<tr>"; for ($col=0; $col<COLS; $col++) { $num1 = mt_rand(1,MAX_NUMBER); $num2 = mt_rand(1,MAX_NUMBER); echo "<td>$num1 * $num2 </td>"; echo "<td><input type='text' size='2' name=${no_of_problems}_mult_${num1}_${num2}></td>"; $no_of_problems++; } echo "</tr>"; } $colspan = 2 * COLS; echo "<tr><td colspan=$colspan align='right'><input type='submit' value='Score' name='btn_score'></td></tr>"; ?> </table> <br> <br> <label for="result_name">Student Name:</label> <input type="text" id="result_name" name="result_name" /><br /> </form> <br> <br> </body> </html> Hello guys, i need some help in assigning a score to a word according to its occurrence in a group of sentences. Code: [Select] [php] $words="Hello, how are you?"; $sentences="Hello! I am fine. How about you? You look good."; [/php] now i'm trying to assign a score to each word in $words e.g Hello=1, how=1, are=0, you=2. I can't post/contribute in the code repo forum, so I'll post it here and maybe a mod will move it for me? Anyway, this is an algorithm for phonetic search scoring. Basically, it will evaluate a search string against an array of strings (list) and then return an array of ranked results from the list, in order of phonetic likeliness to the search string. In the returned array, the key is the score, the closer to 0, the more likely the phonetic match is; 0 being an exact match. Note: this is not pattern matching, this will match phonetic likeliness only. This is built around the English language as it stands, I am working on multi-lingual considerations. <?php /** * @NAME: Phonetic Search Score * @AUTHOR: Ryan Huff - MyCodeTree.com * @COPYRIGHT: (C)2011 * * The idea here is to supply a list (array) of strings (pressumably from a database * record set) and a single string. The class is designed to return an array of results * with X number of strings from the list that are the closest or equal phonetic * matches to the single string, ranked in order of closest phonetic match. * * The uniqueness of the Phonetic Search Score is the method in which it scores matches. The * scoring is based on the phonetic likeness of the single search string and each string * in the list, and is ranked accordingly. Scoring is not based on string length or * pattern matching like traditional REGEX pattern searching. * * A practical use for this would be a scenario where a user types in a search string, and * then the Phonetic Search Score provides a list of matches, ranked in order of their * phonetic likeliness to the search string. In the returned array, the key is the score, * the closer the key\score is to 0, the more likely the phonetic match is; 0 being an * exact match. * * An example use case is provided below. If you have any questions about the Phonetic * Search Score, you can contact me at support@mycodetree.com * */ class matcher { var $searchCriteria = NULL; //TEXT TO SEARCH FOR var $searchSet = array(); //SET TO SEARCH WITHIN var $numberOfMatches = 5; //NUMBER OF MATCHES TO RETURN var $removalChars = array('.','?','!','@','*','&','%','$','#',',',';',':','"','\''); //PUNCTUATION TO REMOVE var $returnMatches = array(); function scorer() { if (is_array($this->searchSet) && !empty($this->searchCriteria)) { $distal = array(); foreach ($this->removalChars as $val) { $replace[] = ""; } //REMOVE PUNCTUATION, CONVERT TO ALL LOWERCASE AND REMOVE LEADING AND ENDING SPACES $this->searchCriteria = trim(strtolower( str_replace($this->removalChars, $replace, $this->searchCriteria))); //GET METAPHONE KEY FOR SEARCH CRITERIA $scm = metaphone($this->searchCriteria); if ($this->numberOfMatches <= count($this->searchSet)) { for ($i=0; $i < count($this->searchSet); $i++) { $distal[levenshtein($scm, metaphone($this->searchSet[$i]))] = $this->searchSet[$i]; } } else { for ($i=0; $i < $this->numberOfMatches; $i++) { $distal[levenshtein($scm, metaphone($this->searchSet[$i]))] = $this->searchSet[$i]; } } ksort($distal); $this->returnMatches = $distal; } return false; } } /*INSTANTIATE CLASS*/ $score = new matcher(); /*EXAMPLE USE CASE*/ /*SETUP THE LIST OF STRING TO COMPARE THE SEARCH CRITERIA AGAINST*/ $score->searchSet = array( 'this is one item from a result set', 'this is another test item', 'more testing', 'Hello world, I am a test sentence.', 'So, do you have any mustard that I can borrow?' ); /*SETUP THE SEARCH CRITERIA*/ $score->searchCriteria = "Hello world, I am a test sentence."; /*FIRE THE SCORER METHOD (THIS METHOD WOULD BE EXPENSIVE TO CALL IN A LOOP, USE CAUTION)*/ $score->scorer(); /*DUMP THE RESULTS*/ print_r($score->returnMatches); ?> I am trying to create a full Scoreboard like the on the EPSN website. (The Red bar that shows the daily scores). So i created a DB called "scoreDB" I have like 30 sample scores in there.
What i want to create is a set of DIVS that will display the scores from the DB entries and refresh the scores every 10 seconds or so.
Righ now i can display the last score entered from the DB. But i can't make it change automaticly. So I started to think and I creted a Java scrip timer(see below)
My Issue i cant figure out how to make it work
Button line i want a divs that will diplay one score at a time and refresh every 10 seconds or so and display the next available record until it shows the last 10 and start diplaying the laters entry again. I will love to hear your sugestions or soluctions.
One DIV Sample below
<div class="score1" id="score1"> <?php mysql_select_db(scoredb) or die ("Couldn't not find DB"); $query = mysql_query("SELECT * FROM results ORDER BY IDResults DESC 1 "); while($row = mysql_fetch_assoc($query)) { $player1 = $row ["Player1"]; $score1 = $row ["Score1"]; $player2 = $row ["Player2"]; $score2 = $row ["Score2"]; echo $player1" . " " . $scr1 . " " . " " . " - " . " " . $player2" . " " . $scr2 ; } ?> </div> <br></br> <script type="text/javascript" src="jQuery.js"></script> <script type="text/javascript"> function countDown(secs, elem){ var element = document.getElementById(elem); element.innerHTML = "Please wait for "+secs+" seconds"; if(secs <1){ clearTimeout(timer); element.innerHTML = '<h2>Tournament is now Open!</h2>'; element.innerHTML += '<a href="#"> Click here now</a>'; } secs--; var timer = setTimeout('countDown('+secs+',"'+elem+'")',1000); } </script> <div id="status"></div> <script type="text/javascript"> countDown(10,"status");</script> <p></p> I'm in the process of creating a webage that shows latest scores and an updated league table for soccer/football matches like the bbc sports website does. I have the database set up with a form to update and display latest score all work well apart from if i update a score like the following teamA 1 teamB 0 it updates table to give teamA 3 points based on the current score however if teamA score again teamA 2 teamB 0 it updates table again but gives teamA another 3 points which is not correct so i need a way to stop it happening. thought about it for a while and only thing i can come up with is some maths to compare the values of score for each team and add/remove points as dependent on current score. Anyone got something similar to this I'm new to function and I can't figure how to update/result the score. I developed a game called Rock, Paper, & Scissors, so I can learn the function itself with a simple game for now. http://pastebin.com/9MB7ATnt Any tips or instruction would be much appreciated. Thanks. In my app, the users will take a multiplication test with 10 problems... I'm not sure how I would post the grade that the user got to the database. When the user finishes the test and hits score it should post their Name/Date & Time/ and Score to the database. I have the name and date & time working. Just not sure how I would approach the score. This is my application... It is small and simple to run in browser. Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Lab 5</title> </head> <body> <?php require_once('database.php'); define ('ROWS', 3); define ('COLS', 3); define ('MAX_NUMBER', 12); date_default_timezone_set('America/New_York'); if (isset($_POST['btn_score'])) { $result_name=$_POST['result_name']; $sql = "INSERT INTO results (result_name, result_score, result_date_time) VALUES ('$result_name', 100, NOW());"; $db->exec($sql); //print_r ($_POST); $time1 = $_POST['ts']; $time1_object = new DateTime($time1); $now = new DateTime(); $time_span = $now->diff($time1_object); $minutes = $time_span->format('%i'); $seconds = $time_span->format('%s'); $seconds+= $minutes * 60; echo "It took $seconds seconds to complete the test<hr />"; foreach ($_POST as $problem => $answer) { if ($problem <> "btn_score" && $problem <> "ts") { //echo "$problem -- $answer <br />"; $problem = explode('_', $problem); $num1 = $problem[2]; $num2 = $problem[3]; $right = $num1 * $num2; if ($answer != $right) { echo "$num1 * $num2 = $answer , The right answer is $right<br />"; } } } } ?> <h1>Lab 5</h1> <form name="lab5" method="post" action="lab5b.php"> <?php $now = new DateTime(); //echo $now->format('Y-m-d H:i:s'); echo "<input type='hidden' name='ts' value='" . $now->format('Y-m-d H:i:s') . "'>"; ?> <table border="1" cellspacing="5" cellpadding="5"> <?php $no_of_problems = 0; for ($row=0; $row<ROWS; $row++) { echo "<tr>"; for ($col=0; $col<COLS; $col++) { $num1 = mt_rand(1,MAX_NUMBER); $num2 = mt_rand(1,MAX_NUMBER); echo "<td>$num1 * $num2 </td>"; echo "<td><input type='text' size='2' name=${no_of_problems}_mult_${num1}_${num2}></td>"; $no_of_problems++; } echo "</tr>"; } $colspan = 2 * COLS; echo "<tr><td colspan=$colspan align='right'><input type='submit' value='Score' name='btn_score'></td></tr>"; ?> </table> <br> <br> <label for="result_name">Student Name:</label> <input type="text" id="result_name" name="result_name" /><br /> </form> <br> <br> </body> </html> hello dear PHP-Fans - greetings to you - and a happy new year!! i set up a WAMP-System on my openSuse 11.4 system. In order to learn as much as i can bout PHP i want to do some tests and write some scripts. Well the WAMP is allready up and running. Now i try to give the writing access to the folder mkdir /srv/www/ where the php-scripts should go in... i want to give write permission to all to all files in /srv/www As root I generally: mkdir /srv/www/ chown <webmaster usrername> /srv/www/ /srv/www/ should be readable and traversable by all, but only writeable by it's owner (the user designated as the webmaster.) can i do this like mentioned above,... Love to hear from you greetings db1 Hello sir, My name is Soji. I'm working on a php project on result transcript processing. I got to a stage where i need to rank student based on their score (Subject Position) and also Overall Position. I have tried all i could but i still don't get it I have a table called Subject position where with field (id, studentregNo, subjectid, levelid, armsid, yearid, total). what i want is if there is 3 student in a class and the first student score 50 in english and the second student score 45 and the third score 40. i want the system to tell me that the first student position in English is 1st and the second student position in English is 2nd and third student position in English is 3rd. So all this will be applicable to all subjects that the students in a particular level are offering.
Moreover, I need Rank student in a subject in that class, And this will work with each subject for each student in that class. ok so i want to order by high to low on the field price but i don't know how to do this. i can order low to high by using ORDER BY `Price` ASC but how can i order high to low? Hello, I have what I hope to be a very simple question.. I have built a game in flash and for my high score table I simply want to request the high scores in reverse.. i.e the lowest score first.. here is my php.. please help, thanks in advance !! :- <?php include("sqldialog.php"); $table = $_POST['tab']; $recept = SelectDatas($table, "name, score, dategame", "id > 0", "score desc"); if ($recept) { $i = 0; foreach ($recept as $rec) { $i++; if ($i==1) { $result .= "pseudo$i=".$rec['name']."&score$i=".$rec['score']."&dategame$i=".$rec['dategame']; } else { $result .= "&pseudo$i=".$rec['name']."&score$i=".$rec['score']."&dategame$i=".$rec['dategame']; } } echo $result; } else { echo "BAD, $pseudo, $score, $dategame,$ipclient"; } ?> I successfully load a page by simple_html_dom.php (developed in simplehtmldom.sourceforge.net) as $html = file_get_html('externalpage'); But sometimes this make a high load on CPU and the page does not load for a long time (probably due to the external site server). How can I skip the process when it is not normal to avoid high CPU usage? I have just did this php code for the high-low game but the $tries variable always goes down to 0 when I refresh..Can someone help me to return the $tries to browser with the url? Thank you
<html>
<?php function High_Low($guess){
I think I've coded myself into a corner. I have numerous items entered with measurement extremes - highest and lowest. Now I want somebody to be able to search for an item that could match a specific length. So I could have several items that are entered into a database like this: Code: [Select] item_id | length | high_low_param -----------+-----------+---------------------- 1234 | 12 cm | high -----------+-----------+--------------------- 1234 | 6 cm | low If somebody searches for an item that is 8 cm long, I want the results to be item 1234 and any other items that span that range. I'm not sure how to do this? array_fill ? I don't know. I don't want to slow down the database too much, and I don't want to have to put an entry for every single length each item could be. Any suggestions? Hi, i'm new here and have a straightforward question. On a server I use I have this script and we use it to force the download of mp3 files on a single click of a link. (Avoid opening in an internet audio buffering plug in or application) Code: [Select] <?php $filename = $_GET['file']; // required for IE, otherwise Content-disposition is ignored if(ini_get('zlib.output_compression')) ini_set('zlib.output_compression', 'Off'); // addition by Jorg Weske $file_extension = strtolower(substr(strrchr($filename,"."),1)); if( $filename == "" ) { echo "<html><title>Download Script</title><body>ERROR: download file NOT SPECIFIED. USE force-download.php?file=filepath</body></html>"; exit; } elseif ( ! file_exists( $filename ) ) { echo "<html><title>Download Script</title><body>ERROR: File not found. USE force-download.php?file=filepath</body></html>"; exit; }; switch( $file_extension ) { case "pdf": $ctype="application/pdf"; break; case "exe": $ctype="application/octet-stream"; break; case "zip": $ctype="application/zip"; break; case "doc": $ctype="application/msword"; break; case "xls": $ctype="application/vnd.ms-excel"; break; case "ppt": $ctype="application/vnd.ms-powerpoint"; break; case "gif": $ctype="image/gif"; break; case "png": $ctype="image/png"; break; case "mp3": $ctype="audio/mpeg3"; break; case "jpeg": case "jpg": $ctype="image/jpg"; break; default: $ctype="application/force-download"; } header("Pragma: public"); // required header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Cache-Control: private",false); // required for certain browsers header("Content-Type: $ctype"); // change, added quotes to allow spaces in filenames, by Rajkumar Singh header("Content-Disposition: attachment; filename=\"".basename($filename)."\";" ); header("Content-Transfer-Encoding: binary"); header("Content-Length: ".filesize($filename)); readfile("$filename"); exit(); ?> I recently got an email from my service provider quoting the following Quote Hello, I apologize, but I was forced to suspend the script /home/mezerik/********/forcedownload.php as it was causing a high load on the server, and due to it affecting all of the other accounts on the system, I forced to take immediate action for the health of the server. Unfortunately I do not have any specific recommendations for this script, however, in general, adding some sort of caching mechanism, where the script does not need to generate a new page with every request, helps to lower the over load that a script will cause. Likely the original author or support group of the software that you are using will be able to help you to understand how to add something of this nature. If you reply back to this with your IP address (http://www.******.com/ip.shtml) we will be more than happy to go ahead enable HTTP access for you, so that you can safely work on the script without it causing further issues. Please let us know how you would like to proceed. I am not sure what is wrong with the script and if it is insecure to the server and should be edited or removed. I have a class that I created, halfway down my page I call a function from the class which prints some code and also changes a variable inside the class. It's a search class basically it prints out the search results and saves the total amount of results into the variable. I want to display the amount of results above the results like so:- echo $Search->results; $Search->GetResults('foo'); The problem is that $Search->results will be equal to NULL until the variable is updated in the function GetResults. Hope that makes sense, am I going about this wrong? Hello, I am including file SimpleImage.php in my php file. The script will handle everything perfectly, but if I try and upload a very large resolution image 2560x1440 the script just dies and no resizing is made. The file size of the high resolution image is well below 2 Mb, so there is no file size issue. I am troubled. Any ideas? Thanks. SimpleImage.php Code: [Select] <?php /* * File: SimpleImage.php * Author: Simon Jarvis * Copyright: 2006 Simon Jarvis * Date: 08/11/06 * Link: http://www.white-hat-web-design.co.uk/articles/php-image-resizing.php * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details: * http://www.gnu.org/licenses/gpl.html * */ class SimpleImage { var $image; var $image_type; function load($filename) { $image_info = getimagesize($filename); $this->image_type = $image_info[2]; if( $this->image_type == IMAGETYPE_JPEG ) { $this->image = imagecreatefromjpeg($filename); } elseif( $this->image_type == IMAGETYPE_GIF ) { $this->image = imagecreatefromgif($filename); } elseif( $this->image_type == IMAGETYPE_PNG ) { $this->image = imagecreatefrompng($filename); } } function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) { if( $image_type == IMAGETYPE_JPEG ) { imagejpeg($this->image,$filename,$compression); } elseif( $image_type == IMAGETYPE_GIF ) { imagegif($this->image,$filename); } elseif( $image_type == IMAGETYPE_PNG ) { imagepng($this->image,$filename); } if( $permissions != null) { chmod($filename,$permissions); } } function output($image_type=IMAGETYPE_JPEG) { if( $image_type == IMAGETYPE_JPEG ) { imagejpeg($this->image); } elseif( $image_type == IMAGETYPE_GIF ) { imagegif($this->image); } elseif( $image_type == IMAGETYPE_PNG ) { imagepng($this->image); } } function getWidth() { return imagesx($this->image); } function getHeight() { return imagesy($this->image); } function resizeToHeight($height) { $ratio = $height / $this->getHeight(); $width = $this->getWidth() * $ratio; $this->resize($width,$height); } function resizeToWidth($width) { $ratio = $width / $this->getWidth(); $height = $this->getheight() * $ratio; $this->resize($width,$height); } function scale($scale) { $width = $this->getWidth() * $scale/100; $height = $this->getheight() * $scale/100; $this->resize($width,$height); } function resize($width,$height) { $new_image = imagecreatetruecolor($width, $height); imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight()); $this->image = $new_image; } } ?> My code for the resizing where the script dies. It works well for photos but with higher resolution (2560x1440) it fails??: Code: [Select] include('incl/SimpleImage.php'); $image = new SimpleImage(); $image->load('images/avatars/'.$name); //This makes a 400 wide avatar $image->resizeToWidth(400); $image->save('images/avatars/'.strtolower($username.'_400.'.$ext)); //This makes a 30x30 mini avatar $image->resize(30,30); $image->save('images/avatars/'.strtolower($username.'_small.'.$ext)); |