PHP - Get Sum Of Two Variables Using Javascript Not Working
hi,
I'm new to php. I tried to get sum of two variables using java script. Value of one variable come from a php variable, Other one is a static value. here is the code
$price_per_day=100; it displays correctly. but when i try to add it with another variable it displays nothing. Please help me.
<!DOCTYPE html>
Similar TutorialsHello All, In below script, I'm using another script called "SimpleImage.php" to upload and resize photos for a news site. The problem comes with renaming the photos. I need to name the photo based off of the story id. I have everything right to get the story id, but saving it as the variable is what's confusing me. Here's what I have: <?php include ("newsconnection.php");?> <?php $picturename = $_POST['newstoryid']; include('SimpleImage.php'); $image = new SimpleImage(); $image->load($_FILES['uploaded_image']['tmp_name']); $image->resizeToWidth(300); $image->save('$picturename'); ?> It's the $image->save('$picturename'); line that's messing me up. Any help would be great!! I have no idea and there is no reason why this should not be working. im simply trying to add three variables into a database, and only one works. the other two do not work for any reason i can find. can someone point out my error, if any? code: <?php $date = date("Y-m-d"); $dbc = mysqli_connect('localhost', 'root', '', 'timer') or die('Error connecting to DB'); $query = @"INSERT INTO sessions (date, user, sessiontime) VALUES ('$date', '$user', '$sessiontime')"; $user = @$_GET['user']; $sessiontime = @$_GET['clock']; if (@$_GET['addDB'] == "Session Complete") { mysqli_query($dbc, $query) or die( '<br>Query string: ' . $query . '<br>Produced error: ' . mysqli_error($dbc) ); } ?> Form: Code: [Select] <label for="user"><b><em>Your name: </b></em></label><br /><input type="text" name="user" value="Admin/User" /> <input id="clock" name="clock" type="text" value="00:00:0" readonly><br> <input id="startstopbutton" type="button" value="S t a r t" onClick="startstop();" style="font-weight:bold"><br> <input type="submit" name="addDB" value="Session Complete" /> See, all the variables match up!? I dont get what im doing wrong? I've got a mailing list (uses DadaMail) which provides a perl script (subscribe_email.pl) so that I can pass subscribers to it thorugh a PHP script. Info he http://dadamailproject.com/support/documentation-5_0_1/COOKBOOK-subscriptions.pod.html#command_line_utility___subscribe_email_pl The trouble is I can get it working when variables are passed to it via URL query strings, but when I try to hard-code variables into it it stops working. I can't see any reason for this, it's got me really confused. This works: - Code: [Select] <?php // example usage: - // http://www.domain.com/ds1.php?sendto=user@domain.com&title=Mr&forename=John&surname=Doe&company=None&country=UK if (isset($_GET['sendto'])) { $email = $_GET['sendto']; } if (isset($_GET['title'])) { $title = preg_replace("/[^A-Za-z ]/", "", $_GET['title']); } if (isset($_GET['forename'])) { $forename = preg_replace("/[^A-Za-z\-. ]/", "", $_GET['forename']); } if (isset($_GET['surname'])) { $surname = preg_replace("/[^A-Za-z\-. ]/", "", $_GET['surname']); } if (isset($_GET['company'])) { $company = preg_replace("/[^A-Za-z()\-.& ]/", "", $_GET['company']); $company = str_replace('&', 'and', $company); } if (isset($_GET['country'])) { $country = preg_replace("/[^A-Za-z\-.& ]/", "", $_GET['country']); $country = str_replace('&', 'and', $country); } if (isset($email)) { $exec_command = 'perl ./subscribe_email.pl --list mylist --email '. $email; if (isset($title)) $exec_command .= ' --fields title '. $title; if (isset($forename)) $exec_command .= ' --fields forename '. $forename; if (isset($surname)) $exec_command .= ' --fields surname '. $surname; if (isset($company)) $exec_command .= ' --fields company '. $company; if (isset($country)) $exec_command .= ' --fields country '. $country; exec(escapeshellcmd($exec_command)); } else { echo 'Nothing to do'; } ?> The mail address and all the parameters are passed to the subscribe_email.pl script. But, this doesn't work: - Code: [Select] <?php $subscriber_email = 'user@domain.com'; $subscriber_title = 'Mr'; $subscriber_forename = 'John'; $subscriber_surname = 'Doe'; $subscriber_company = 'None'; $subscriber_country = 'UK'; if (isset($subscriber_email)) { $email = escapeshellcmd($subscriber_email); } if (isset($subscriber_title)) { $title = preg_replace("/[^A-Za-z ]/", "", $subscriber_title); } if (isset($subscriber_forename)) { $forename = preg_replace("/[^A-Za-z\-. ]/", "", $subscriber_forename); } if (isset($subscriber_surname)) { $surname = preg_replace("/[^A-Za-z\-. ]/", "", $subscriber_surname); } if (isset($subscriber_company)) { $company = preg_replace("/[^A-Za-z()\-. ]/", "", $subscriber_company); $company = str_replace('&', 'and', $company); } if (isset($subscriber_country)) { $country = preg_replace("/[^A-Za-z\-. ]/", "", $subscriber_country); $country = str_replace('&', 'and', $country); } if (isset($email)) { $exec_command = 'perl ./subscribe_email.pl --list mylist --email '. $email; if (isset($title)) $exec_command .= ' --fields title '. $title; if (isset($forename)) $exec_command .= ' --fields forename '. $forename; if (isset($surname)) $exec_command .= ' --fields surname '. $surname; if (isset($company)) $exec_command .= ' --fields company '. $company; if (isset($country)) $exec_command .= ' --fields country '. $country; exec(escapeshellcmd($exec_command)); } else { echo 'Nothing to do'; } ?> In the second example, only the list and email parameters are passed, all the others are lost (or ignored). All that's different between the two is the way the variables are inititally set, I can't for the life of me figure out why the second one isn't working . Even stranger, I tried testing with just: - Code: [Select] <?php exec("perl ./subscribe_email.pl --list mylist --email user@domain.com --fields title Mr --fields forename John--fields surname Doe --fields company None --fields country UK") ?> and this doesn't work fully either (again just the list and email parameters are passed). Unfortunately, it's the second method I need to use as it's tagged on to the end of a contact form processing script which initiates the subscription if a checkbox is left ticked...and all variables will be coming from this form script. Any help greatly appreciated! Hello all, I'm passing variables through a URL. This will work: echo $v4; But neither of these will: echo "<a href='test.php?v4=$v4'>Places</a>"; echo "<a href='test.php?v4=".$v4."> Places</a>"; It WILL work if I hardcode v4, like so: echo "<a href='test.php?v4=Utah'>Places</a>"; But that's useless to me, as I don't want to have to write 50 If statements for every database entry. Does anyone know how to fix this? Thanks! I am trying to run a mysql query to get the sum of a column. When I type out the column name it works. When the column name is stored in a variable it does not seem to work. Code: [Select] <?php $total = $_GET['total']; if ($order != "" && $total != ""){ $query2 = "SELECT SUM('.$type2.') FROM customers WHERE sched=1"; $result2 = mysql_query($query2) or die(mysql_error()); while($row = mysql_fetch_array($result2)){ echo "Total ". " = $". $row["SUM('.$type2.')"]; echo "<br />"; } } ?> Any Help would be appreciated. Hi everyone, I am trying to implement an OAuth system in PHP. I've got the code working but the very first time a fresh, new browser window is opened, the code doesn't work. If I refresh the page and try again, then it works. I have a few suspicions as to where the problem might be but other than that I am stumped. I have two classes: OAuthServer and OAuthClient. I create and store an object of the appropriate class in session variables. I know this is tricky but I am serializing and unserializing properly. To fetch responses from the Server, I am using curl. As curl uses a different session from the browser, I am doing a session_write_close before initializing curl and passing the appropriate parameters to curl. But my code needed to further write session variables even after session_write_close was called and to achieve this, I am calling session_start(), once again, after the curl code is finished. I found that this works but PHP was throwing warnings saying that the header info had already been sent or something like that, but I have suppressed such warnings. I suspect the error has something to do with this but I'm not sure. The part that doesn't work the very first time is that on the server-side, the session variable that is supposed to contain the OAuthServer object is NULL. But if I do a refresh of the page(flow: login_page->error_page), it works. Can anyone tell me why I am encountering the above error and if I am doing things correctly or not. Any help would be greatly appreciated. Thanks & Regards, GarbageGigo http://paste.ee/p/OhiWv
The above is a link to a readable version of my code. The XMLHTTPREQUEST worked, and the array was pulled down. Was able to print out the undecoded/unparsed array. However, immediately afterwards, all code stops working.
<script> var xhr; if (window.XMLHttpRequest) { // Mozilla, Safari, ... xhr = new XMLHttpRequest(); } else if (window.ActiveXObject) { // IE 8 and older xhr = new ActiveXObject("Microsoft.XMLHTTP"); } xhr.open("POST", "PHPLibrary/selectMemberResults.php", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.send(); xhr.onreadystatechange = display_data; var $phparray function display_data() { if (xhr.readyState == 4) { if (xhr.status == 200) { //alert(xhr.responseText); $phparray = xhr.responseText; document.getElementById("suggestion").innerHTML = $phparray; // // //......................................................? // The above line of code is the last thing to print or // to do anything that returns to the browser.... //.......................................................? // All lines below do nothing............................? // } else { //alert('There was a problem with the request.'); } } } document.write("Length of phparray Array :" + $phparray.length + "<"); var output = JSON.parse($phparray, function (key,val) { if ( typeof val === 'string' ) { // regular expression to remove extra white space if ( val.indexOf('\n') !== -1 ) { var re = /\s\s+/g; return val.replace(re, ' '); } else { return val; } } return val; } ); document.write("Length of Array :" + $output.length + "<"); for (var i=0; i < $output.length; i++) { document.getElementById("suggestion").innerHTML = $output[i].MEMBER_NAME; } </script> hi is there an easy way to get a variable in javascript? I have separate php, tpl and js files. With a onload in my tpl a function is called from my js. Is there a way i can get a variable in my php file from that function? in my php file it's called $path with a path in it to an mp3 file. the javascript function should start a audio stream with that path... thanks in advance! I am trying to get a JavaScript variable into a PHP variable, I can do this the other way around using the hidden input method and using something like var phpvar = document.getElementById('qwerty').value; to grab the PHP variable from within it. My problem is getting a JavaScript variable into a PHP variable, what methods are out there? Thanks This has got to be possible, I have a chatbox script, which reads the person's rights by their username, which when displaying the chat username / text, I use javascript, so I need PHP to parse the javascript text, how can I do this? Code: [Select] <?php $user = 'user_node[0].firstChild.nodeValue;'; ?> That returns "user_node[0].firstChild.nodeValue;", I can't include <script> in the echo text, due to it's inside of a Javascript function already. I need it to do this: <?php $user = 'user_node[0].firstChild.nodeValue;'; ?> var user = '<?php echo getRank($user); ?>'; aka var user = '<?php echo getRank('Username'); ?>'; I can do the second part, PHP variable to Javascript variable, just not the first part. Any help is appreciated, thanks. Edit: echo "chat_div.innerHTML += userN2;"; returns "Username" $var = "chat_div.innerHTML += userN2;"; echo $var; returns chat_div.innerHTML += userN2; Just to simplify the problem. I am trying to build a website, whe
1) User logs in (UserA)
2) Inserting a name in the search box and pressing "Search", a list of all users matching that name is shown
3) The user selects a user (UserB) from that list (among several results)
4) By selecting the user (UserB) , a message box appears to insert text
5) The user(UserA) types the message
6) The user(UserA) presses the SUBMIT button and sends the message to the other user(UserB)
The problem i face is how to pass the variables from my PHP script to the JavaScript script. Its easy for me to get the values of input fiedls, select fields or any other DOM element value. But if the value i need to pass to Javascript file to perform an AJAX call isnt inside a DOM element, how do i do it?
For example, for me to determine the user that will send the message (userA), i will need several data. This data, i have them inside the PHP script as variables, but dont know how to pass them to Javascript file.
Getting the data from the URL, or from a hidden input field or any other DOM element, is a solution, but i want to know the way that is safer and better.
To summarize:
[PHP Script with necessary data]-->[pass necessary data from PHP to JavaScript file]-->[perform an AJAX call] --> [return data to PHP Script]
How do i do it?
Thanks in advance.
This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=326310.0 As the topic sais i have a problem trying to send variables to a javascript popup window, i think the problem is on line 38. I would very much appreciate some help Code: [Select] <html> <head> <script type="text/javascript"> function newPopup(url) { popupWindow = window.open(url,'popUpWindow','height=700,width=400,left=10,top=10,resizable=no,scrollbars=no,toolbar=yes,menubar=no,location=no,directories=no,status=yes') } </script> </head> <?php error_reporting(E_ALL); require_once 'GameQ.php'; $servers = array( 'server 1' => array('cs', 'd2o.warzone.nu', '27015'), 'server 2' => array('cs', 'd2o.warzone.nu', '27017'), 'server 3' => array('cs', 'wc3.warzone.nu', '27017'), 'server 4' => array('cs', 'aim.warzone.nu', '27015'), 'server 5' => array('cs', '83.255.249.204', '27025'), 'server 6' => array('tf2', 'tf2.warzone.nu', '27015'), 'server 7' => array('tf2', '83.255.249.200', '27015'), 'server 9' => array('cssource', 'css.warzone.nu', '27015'), 'server 10' => array('cssource', 'css.warzone.nu', '27017') ); $gq = new GameQ(); $gq->addServers($servers); $gq->setOption('timeout', 200); $gq->setFilter('normalise'); $gq->setFilter('sortplayers', 'gq_ping'); $results = $gq->requestData(); echo "<a href='steam://connect/d2o.warzone.nu:27015'>" . $results["server 1"]['gq_hostname'] . "</a><p>"; echo $results["server 1"]['gq_mapname'] . "<br>"; echo $results["server 1"]['gq_numplayers'] . "/" . $results["server 1"]['gq_maxplayers']; ?> // I think the problem is the line below this one <a href='JavaScript:newPopup("players.php?address=<?php echo="$results['server 1']['gq_address']"; ?>&port=<?php echo="$results['server 1']['gq_port']"; ?>");'> players online </a>"; <?php echo "<p><p>"; echo "<a href='steam://connect/d2o.warzone.nu:27017'>" . $results["server 2"]['gq_hostname'] . "</a><p>"; echo $results["server 2"]['gq_mapname'] . "<br>"; echo $results["server 2"]['gq_numplayers'] . "/" . $results["server 2"]['gq_maxplayers'] . " players online <p>"; echo "<p><p>"; echo "<a href='steam://connect/wc3.warzone.nu:27017'>" . $results["server 3"]['gq_hostname'] . "</a><p>"; echo $results["server 3"]['gq_mapname'] . "<br>"; echo $results["server 3"]['gq_numplayers'] . "/" . $results["server 3"]['gq_maxplayers'] . " players online <p>"; echo "<p><p>"; echo "<a href='steam://connect/aim.warzone.nu:27015'>" . $results["server 4"]['gq_hostname'] . "</a><p>"; echo $results["server 4"]['gq_mapname'] . "<br>"; echo $results["server 4"]['gq_numplayers'] . "/" . $results["server 4"]['gq_maxplayers'] . " players online <p>"; echo "<p><p>"; echo "<a href='steam://connect/83.255.249.204:27025'>" . $results["server 5"]['gq_hostname'] . "</a><p>"; echo $results["server 5"]['gq_mapname'] . "<br>"; echo $results["server 5"]['gq_numplayers'] . "/" . $results["server 5"]['gq_maxplayers'] . " players online <p>"; echo "<p><p>"; echo "<a href='steam://connect/tf2.warzone.nu:27015'>" . $results["server 6"]['gq_hostname'] . "</a><p>"; echo $results["server 6"]['gq_mapname'] . "<br>"; echo $results["server 6"]['gq_numplayers'] . "/" . $results["server 6"]['gq_maxplayers'] . " players online <p>"; echo "<p><p>"; echo "<a href='steam://connect/83.255.249.200:27015'>" . $results["server 7"]['gq_hostname'] . "</a><p>"; echo $results["server 7"]['gq_mapname'] . "<br>"; echo $results["server 7"]['gq_numplayers'] . "/" . $results["server 7"]['gq_maxplayers'] . " players online <p>"; echo "<p><p>"; echo "<a href='steam://connect/tf2.warzone.nu:27015'>" . $results["server 8"]['gq_hostname'] . "</a><p>"; echo $results["server 8"]['gq_mapname'] . "<br>"; echo $results["server 8"]['gq_numplayers'] . "/" . $results["server 8"]['gq_maxplayers'] . " players online <p>"; echo "<p><p>"; echo "<a href='steam://connect/css.warzone.nu:27015'>" . $results["server 9"]['gq_hostname'] . "</a><p>"; echo $results["server 9"]['gq_mapname'] . "<br>"; echo $results["server 9"]['gq_numplayers'] . "/" . $results["server 9"]['gq_maxplayers'] . " players online <p>"; echo "<p><p>"; echo "<a href='steam://connect/css.warzone.nu:27017'>" . $results["server 10"]['gq_hostname'] . "</a><p>"; echo $results["server 10"]['gq_mapname'] . "<br>"; echo $results["server 10"]['gq_numplayers'] . "/" . $results["server 10"]['gq_maxplayers'] . " players online <p>"; ?> </html> Hello everyone, I can get Test 2 to successfully operate the if statement using a variable variable. But when I try the same method using a session variable (Test 1) the if statement is not executed. Please could you tell me why the if statement in Test 1 is not being executed? Code: [Select] <?php # TEST 1 $_SESSION[test_variable] = "abcd"; $session_variable_name = "_SESSION[test_variable]"; if ($$session_variable_name == "abcd") { echo "<br>line 373, abcd<br>"; } # TEST 2 $test_variable = "efgh"; $test_variable_name = "test_variable"; if ($$test_variable_name == "efgh") { echo "<br>line 379, efgh<br>"; } ?> Many thanks, Stu does anyone know how to decode this XML variable value into string values? I also need to know the oposite way: creating variable values into xml. I've tried several code examples but they did filter the requested data. Code: [Select] $xml='<?xml version="1.0" encoding="utf-8"?> <elements> <text identifier="ed9cdd4c-ae8b-4ecb-bca7-e12a5153bc02"> <value/> </text> <textarea identifier="a77f06fc-1561-453c-a429-8dd05cdc29f5"> <value><![CDATA[<p style="text-align: justify;">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>]]></value> </textarea> <textarea identifier="1a85a7a6-2aba-4480-925b-6b97d311ee6c"> <value><![CDATA[<p style="text-align: justify;">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>]]></value> </textarea> <image identifier="ffcc1c50-8dbd-4115-b463-b43bdcd44a57"> <file><![CDATA[images/stories/red/cars/autobedrijf.png]]></file> <title/> <link/> <target/> <rel/> <lightbox_image/> <width><![CDATA[250]]></width> <height><![CDATA[187]]></height> </image> <text identifier="4339a108-f907-4661-9aab-d6f3f00e736e"> <value><![CDATA[Kramer 5]]></value> </text> <text identifier="ea0666d7-51e3-4e52-8617-25e3ad61f8b8"> <value><![CDATA[6000 RS]]></value> </text> <text identifier="90a18889-884b-4d53-a302-4e6e4595efa0"> <value><![CDATA[Eindhoven]]></value> </text> <text identifier="410d72e0-29b3-4a92-b7d7-f01e828b1586"> <value><![CDATA[APK Pick up and return]]></value> </text> <text identifier="45b86f23-e656-4a81-bb8f-84e5ea76f71f"> <value><![CDATA[15% korting op grote beurt]]></value> </text> <text identifier="3dbbe1c6-15d6-4375-9f2f-f0e7287e29f3"> <value><![CDATA[Gratis opslag zomerbanden]]></value> </text> <text identifier="2e878db0-605d-4d58-9806-8e75bced67a4"> <value><![CDATA[Gratis abonnement of grote beurt]]></value> </text> <text identifier="94e3e08f-e008-487b-9cbd-25d108a9705e"> <value/> </text> <text identifier="73e74b73-f509-4de7-91cf-e919d14bdb0b"> <value/> </text> <text identifier="b870164b-fe78-45b0-b840-8ebceb9b9cb6"> <value><![CDATA[040 123 45 67]]></value> </text> <text identifier="8a91aab2-7862-4a04-bd28-07f1ff4acce5"> <value/> </text> <email identifier="3f15b5e4-0dea-4114-a870-1106b85248de"> <value/> <text/> <subject/> <body/> </email> <link identifier="0b3d983e-b2fa-4728-afa0-a0b640fa34dc"> <value/> <text/> <target/> <custom_title/> <rel/> </link> <relateditems identifier="7056f1d2-5253-40b6-8efd-d289b10a8c69"/> <rating identifier="cf6dd846-5774-47aa-8ca7-c1623c06e130"> <votes><![CDATA[1]]></votes> <value><![CDATA[1.0000]]></value> </rating> <googlemaps identifier="160bd40a-3e0e-48de-b6cd-56cdcc9db892"> <location><![CDATA[50.895711,5.955427]]></location> </googlemaps> </elements>'; Hi Everyone, I have a training package that was developed by one of our departments, and I want to intregrate PHP into it so that it can post results of an exam to a DB. Basically, the way that it get's the score to the screen currently is to store the "score" value into a JS variable, and send it to screen using a <DIV ID='Score'> tag. Is there any way that I can extract the information out of that DIV tag into a PHP variable with just the score? I have tried: $score = '<div id="score"></div>' However, this brings the whole tag into the DB. Help is appreciated Thanks Matt I have created website and posted it on PHP server BUT, JavaScript is not working
============================================================= Hi. I have some code which needs to return a single variable from the function and stored as a variable within this page, so it can be echoed later on in the page. I couldn't get it to return as a variable, so i used "return compact();" to return the variable and "extract (myFunction());" to extract it to variables. However, when I turned on php's display errors and error reporting function, I got an error message saying "Warning: extract() [function.extract]: First argument should be an array in /my/web/site/index.php on line 6" (which is where my extract function is). This works fine with passing more than one variables through, is there another way pass one variable from a function to be stored as a variable on the page which called the function? Here is the function: Code: [Select] <?php //This is a list of numeric error codes against their text. this will return the error code as the variable $issue function checkLoginIssue() { //If there is an error code if (isset($_GET["issue"])) { //cycle through the list until the code is reached, return the text and break the switch switch ($_GET["issue"]) { case "1": $issue = '<p class="warning">Please log in to view this page</p>'; break; case "2": $issue = '<p class="warning">Wrong Username or Password</p>'; break; case "3": $issue = '<p class="warning">No user found with those details</p>'; break; } //return the variable in an array with a single value return compact('issue'); } } ?> And here is the code which calls the function: Code: [Select] <?php extract(checkLoginIssue()); ?> i dont understand what is wrong plz help me.
here is code
$name = "img/".rand(1,9999999).".png"; $myFile = $name; $fh = fopen($myFile, 'w') or die("can't open file"); $stringData = $html; fwrite($fh, $stringData); fclose($fh); $file=$name; $fst=file_get_contents($file); $im=imagecreatefromstring($fst); imagefilter($im, IMG_FILTER_GRAYSCALE); imagefilter($im, IMG_FILTER_NEGATE); //Convert to Grey Scale for($i=0;$i<123;$i++){ for($j=0;$j<50;$j++){ $px=imagecolorat($im,$i,$j); if($px<0x303030){ imagesetpixel($im,$i,$j,0); }else{ imagesetpixel($im,$i,$j,0xffffff); } } } $database = unserialize(@file_get_contents("db.txt")); if($database === false) $database = array(); // modify the database if needed if($_SERVER['REQUEST_METHOD'] == 'POST'){ if($_POST['submit'] == 'Add') $database[$_POST['ident']] = substr($_POST['letter'], 0, 1); if($_POST['submit'] == 'Del') unset($database[$_POST['ident']]); if($fh = @fopen('db111.txt', 'w+')){ fwrite($fh, serialize($database)); fclose($fh); } }else{ $newimage = true; } $width = 130; $height = 40; $captcha_gridstart =1; $captcha_gridspace =2; $letters = findletters($im, $width, $height, $captcha_gridstart, $captcha_gridspace); $count = count($letters); $cellw = ($count > 0) ? intval(100 / $count) : 0; //dispeckle the image and GET co-ordinates of the characters of captcha image and return them. function findletters($image, $width, $height, $gridstart, $gridspace){ $offsets = array(); $o = 0; $atstartx = true; for($x = 0; $x < $width; $x++){ $blankx = true; for($y = 0; $y < $height; $y++){ if(imagecolorat($image, $x, $y) == 0){ $blankx = false; break; } } if(!$blankx && $atstartx){ $offsets[$o]['startx'] = $x; $atstartx = !$atstartx; }else if($blankx && !$atstartx){ $offsets[$o]['endx'] = $x; $atstartx = !$atstartx; $o++; } } $count = $o; for($o = 0; $o < $count; $o++){ for($y = 0; $y < $height; $y++){ $blanky = true; for($x = $offsets[$o]['startx']; $x < $offsets[$o]['endx']; $x++){ if(imagecolorat($image, $x, $y) == 0){ $blanky = false; break; } } if(!$blanky){ $offsets[$o]['starty'] = $y; break; } } for($y = $height-1; $y > $offsets[$o]['starty']; $y--){ $blanky = true; for($x = $offsets[$o]['startx']; $x < $offsets[$o]['endx']; $x++){ if(imagecolorat($image, $x, $y) == 0){ $blanky = false; break; } } if(!$blanky){ $offsets[$o]['endy'] = $y; break; } } } for($o = 0; $o < $count; $o++){ $offsets[$o]['ident'] = ""; for($x = $offsets[$o]['startx'] + $gridstart; $x < $offsets[$o]['endx']; $x += $gridspace){ for($y = $offsets[$o]['starty'] + $gridstart; $y < $offsets[$o]['endy']; $y += $gridspace){ $offsets[$o]['ident'] .= ((imagecolorat($image, $x, $y) == 0) ? "0" : "1"); #echo $offsets[$o]['ident'].'<br>'; } } } return $offsets; } $a=""; foreach($letters as $letter){ $asciiletter = $database[$letter['ident']]; if(!empty($asciiletter)) { $a.=$asciiletter; } } |