PHP - Php Function Not Being Called
Here's some of my code. The fault is when AJAX sends the dataString to sendpm.php, it should call the function. But nothing is happening. If i put the sendprivatemessage query in sendpm.php page, the data is sent to mysql. What is the solution, so i don't have to put the query on sendpm.php?
jquery - some of it Code: [Select] $.ajax({ type: "POST", url: "/sendpm.php", data: dataString, success: function() { window.location.href = 'http://www.stackway.com/cp/messages=outbox'; } }); sendpm.php Code: [Select] include "database.php"; $to = $_POST['to']; $from = $_POST['from']; $subject = $_POST['subject']; $body = $_POST['body']; $database2 = new Database(); $database2->opendb(); $database2->sendprivatemessage($to,$from,$subject,$body); $database2->closedb(); sendprivatemessage function Code: [Select] function sendprivatemessage($to,$from,$subject,$body) { $insert = mysql_query("INSERT INTO privatemessage VALUES ('','$subject','$body','$to','$from','1',NOW(),'','','')",$this-connect); } Similar TutorialsI have 2 forms on a page, 1 with a selection of newly registered accounts and another that displays the information on the user. What I need to happen is when a user is selected from the first form, the second form is populated with the data. I'm trying to do this with a combination of php and javascript, however whenever a user is selected the function isn't being called at all as far as I can tell. Can anyone help me get this working please? Code: [Select] <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Fearless Bandits :: Admin Control Panel</title> </head> <body> <?php //Check for config file and initiate session. require("config.php"); session_start(); //Connect to DB if(!$con) die('Could not connect: ' . mysql_error()); mysql_select_db("$dbname") or die("Cannot select DB"); //Check user authorisation if(!isset($_COOKIE['user'])) { echo "Error: Cookies must be enabled. Please enable cookies in your browser and try again.<br>"; return; } else { $user=$_SESSION['user']; $sql="SELECT * FROM users WHERE username='$user' and access='2'"; $result=mysql_query($sql); $count=mysql_num_rows($result); if($count == 0) { echo "Error: Unauthorised access detected."; return; } } include("header.php"); echo "Admin Control Panel<br>"; //Check for mode, if no mode set to 0 if(isset($_GET['mode'])) $mode=$_GET['mode']; else $mode=0; //Display information based on mode switch($mode){ //Check for new applications case 1: echo "<a href=\"admin.php?mode=0\">Back</a><br>"; $sql="SELECT * FROM users WHERE newreg='1'"; $result=mysql_query($sql); $count=mysql_num_rows($result); $newuser = NULL; $newuid = NULL; $newapi = NULL; $newmember = 0; //If there is more than one load results into an array if($count > 0) { echo "There is at least 1 new user:<br>"; $i = 0; while($row=mysql_fetch_array($result)) { $newaccounts[$i] = $row['username']; $i++; } for($i=0; $i < $count; $i++) { echo "User " . $i . ": " . $newaccounts[$i] . "<br>"; } //Select user echo "<form name=\"selectuser\" action=\"\">"; echo "<select name=\"username\" onChange=\"newaccntsUpdate(this);\">"; echo "<option value=\"\" selected=\"selected\"></option>"; for($i=0; $i < $count; $i++) { echo "<option value=\"" . $newaccounts[$i] . "\">" . $newaccounts[$i] . "</option>"; } echo "</select><br>"; echo "</form>"; //Output array into form. echo "<form name=\"newaccnts\" method =\"post\" action=\"verify_admin.php?form=1\">"; echo "Username: <input name=\"newuser\" type=\"text\" id=\"newuser\" value=\"" . $_SESSION['newuser'] . "\">"; echo "UID: <input name=\"newuid\" type=\"text\" id=\"newuid\" value=\"" . $_SESSION['newuid'] . "\">"; echo "API: <input name=\"newapi\" type=\"text\" id=\"newapi\" value=\"" . $_SESSION['newapi'] . "\">"; if($newmember == 0) echo "Member: <input name=\"newmember\" type=\"checkbox\" id=\"newmember\" value=\"1\"><br>"; else echo "Member: <input name=\"newmember\" type=\"checkbox\" checked= \"checked\" id=\"newmember\" value=\"1\"><br>"; echo "<input name=\"submit\" type=\"submit\" value=\"Submit\">"; echo "</form>"; } break; //Select a mode default: echo "Please select a function below:<br>"; echo "<ul>"; echo "<li><a href=\"admin.php?mode=1\">Check for new applications</a></li>"; echo "<li><a href=\"admin.php?mode=2\">Modify an existing account</a></li>"; echo "<li><a href=\"admin.php?mode=3\">Reset a password</a></li>"; echo "<li><a href=\"admin.php?mode=4\">Delete an account</a></li>"; echo "<ul>"; break; } mysql_close($con); //Update newaccnts function. Pull user info from databse and then run javascript function newaccntsUpdate() { echo "newaccntsUpdate executed<br>"; //Error checking //Identify username $newuser=identifyUser(); //If username is NULL or blank return if($newuser == NULL || $newuser == "") return; $sql = ("SELECT * FROM users WHERE username='$newuser'"); $result = mysql_query($sql); $row = mysql_fetch_array($result); $_SESSION['newuser'] = $newuser; $_SESSION['newuid'] = $row['uid']; $_SESSION['newapi'] = $row['api']; $_SESSION['newmember'] = $row['member']; //Update form with details updateForm(); return; } ?> <script language = "Javascript"> //Identify which user has been selected function identifyUser() { $newuser = document.selectuser.username.value; alert('identifyUser executed'); //Error checking return($newuser); } //Update form function updateForm() { document.newaccnts.newuser.value = $newuser; document.newaccnts.newuid.value = $_SESSION['newuid']; document.newaccnts.newapi.value = $_SESSION['newapi']; alert('updateForm executed'); //Error checking return; } </script> </body> </html> I apologise if I've butchered the code, I'm still learning. Getting a bit desperate as I've tried a lot of things, so any help very appreicated! The concept im struggling with works like this: 1.) There are graphics of people on a page. There is a textbox to the right of the screen which outputs data that corresponds to the tutor. 2.) What i want is that when a user rolls his mouse over the picture, the data in the textbox immediately updates, which is done via php 3.) The issue is thus calling a php function within onmouseover="" from a javascript command. 4.) The function only changes the values that should be displayed (but doesnt work anyway) - is there a way to test whether a php function is being called correctly? And do i need to include some kind of page refresher? Thanks a lot for your help ****************************************** The code as I have it currently is this. ... Code: [Select] // Default setting to display a random persons data at page startup <? $username="removedforprivacy"; $password="removedforprivacy"; $database="tutors"; mysql_connect(localhost,$username,$password); @mysql_select_db($database) or die( "Unable to select database"); $query="SELECT * FROM tutors"; $result=mysql_query($query); $num=mysql_numrows($result); mysql_close(); $i=rand(0,5); $id=mysql_result($result,$i,"id"); $name=mysql_result($result,$i,"name"); $degree=mysql_result($result,$i,"degree"); $ib=mysql_result($result,$i,"ib"); $subjects=mysql_result($result,$i,"subjects"); $experience=mysql_result($result,$i,"experience"); $style=mysql_result($result,$i,"style"); $pic=mysql_result($result,$i,"pic"); ?> //This bit outputs all the graphics. Only the first immage calls the php updater function. $whichpic defines the flag for the person, which is passed to the updater function. </p> <p class="bodytext"><a href="" onclick="" onmouseout="MM_swapImgRestore()" onmouseover="<? php updater($whichpic=1); ?>"><img src="../Tutors/Photos/tim2.gif" name="Image15" width="100" height="100" border="0" id="Image15" /></a><a href="max.html" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('Image16','','../Tutors/Photos/max1.gif',1)"><img src="../Tutors/Photos/max2.gif" alt="max" name="Image16" width="100" height="100" border="0" id="Image16" /></a><a href="nico.html" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('Image17','','../Tutors/Photos/nico1.gif',1)"><img src="../Tutors/Photos/nico2.gif" alt="nico" name="Image17" width="100" height="100" border="0" id="Image17" /></a><a href="sasha.html" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('Image18','','../Tutors/Photos/sasha1.gif',1)"><img src="../Tutors/Photos/sasha2.gif" alt="sasha" name="Image18" width="100" height="100" border="0" id="Image18" /></a> </p> //Where the php data is output <p class="sideheader">FEATURED TUTOR</p> <p><img src="<? echo " $pic"; ?>" width="200" height="200"></p> <p><strong>Name: </strong> <? echo "$name"; ?></p> <p><strong>Degree: </strong> <? echo "$degree"; ?></p> <p><strong>IB: </strong> <? echo "$ib"; ?></p> <p><strong>Subjects Taught: </strong> <? echo "$subjects"; ?></p> <p><strong>Teaching Experience: </strong> <br /> <? echo "$experience"; ?> </p> <p><strong>Teaching Style:<br /> </strong><? echo "$style"; ?> .</strong> </p> <p><!-- end .sidebar2 --></p> </div> // The updater function to call, which changes the information displayed <? php function updater($whichpic) { $i = $whichpic; $id=mysql_result($result,$i,"id"); $name=mysql_result($result,$i,"name"); $degree=mysql_result($result,$i,"degree"); $ib=mysql_result($result,$i,"ib"); $subjects=mysql_result($result,$i,"subjects"); $experience=mysql_result($result,$i,"experience"); $style=mysql_result($result,$i,"style"); $pic=mysql_result($result,$i,"pic"); } ?> ERROR 0 Fatal error: Call to a member function execute() on a non-object ... i've tested the $mysqli and $stmt, both are objects, i have other requests that work well and are built the same way (copy - paste) all vars on the query are also ok. There are working functions over and under this part of my code, if i remove it everything works fine. Code: [Select] $query2 = "INSERT INTO TABLE_NAME(accountSmtp, passwordSmtp, merchantID, adsPrice, adsWidth, adsHeigh, adsAmount, email, emailFrom, adsSense) VALUES('$gmailUser', '$gmailPassword', '$merchantID', '$prix', '$width', '$height', '$adsAmount', '$email', '$from', '$sense')"; if (!$stmt = $mysqli->prepare($query2)) { printf("Erreur : %d.\n", $stmt->errno); print_r($query2); } /* execute statement */ $stmt->execute(); //close statement $stmt->close(); This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=346692.0 I've been trying to find tutorials/coding today related to controlling the ability to download files. The problem I think I'm having because I know it exists is I don't actually know what it's called. Below is kind of a basis for a tutorial or describing what I'm trying to do. I'm trying to find a tutorial or a how to on storing downloadable files either in a Mysql Database &/or on the file server system. I want to make it so that only users that are stored within the user database who have certain rights or a field can be able to download a file. Those users who don't have the proper permissions in the user table will not be able to and those who do when they go to download a file, will be able to. I know these scripts use PHP but am not really sure where to begin on my search because I don't even know what file permissions coding they are using. It's a little difficult for me to explain but, when a website loads another site (For example with Curl or something) How is the site able to keep a header or some part of original site 'attached' to the site they loaded..for example, say you're redirected, the site you redirected to loads, but you still see the site you redirected from header on at the top of the page. How is this done? What is it called? Do you need me to clear it up a bit better? I can try to find an example. Hi guys, What is it called when you have a long paragraph shoretend, With php of course, To make it like haljh;lajbsdg... For example, I have this paragraph: Code: [Select] Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus placerat consequat enim, pretium viverra massa cursus nec. Sed in pharetra magna. Aliquam egestas vehicula mi, sed pellentesque ligula suscipit a. Donec lectus velit, luctus sed lobortis vitae, sollicitudin in sem. Ut facilisis, velit in accumsan porttitor, libero neque molestie leo, ac vulputate eros libero eget mauris. Ut nec justo augue. How to I make it so PHP detects if it is too long and trims it down like: Code: [Select] Lorem ipsum dolor sit amet, consectetur adipiscing elit... If I can find what this is called then I can google it to find it and use it on my site. Thanks in advance! Hey guys, I am still kinda new to php and I can't seem to get this to work. Basically I am calling a script and first I need it retrieve certain values which is working fine, but then after that is called I need it to clear those values it just displayed. To do that I am using UPDATE but it doesn't seem to be calling the UPDATE part. Any ideas? Here is the code: Code: [Select] @mysql_select_db("$db_name") or die ("No DataBase Found"); $result = mysql_query("SELECT * FROM members WHERE id='$_POST[id]'"); while ($row = mysql_fetch_array($result)) { $message = $row['message']; $sender = $row['sender']; echo $message . "\n" . $sender; } mysql_query("UPDATE memebers SET message='' WHERE id='$_POST[id]'"); //These never get mysql_query("UPDATE memebers SET sender='' WHERE id='$_POST[id]'");//called or so it seems hi, i just wanted to know... $arr[0] $arr[1] $arr[2] also this $arr[1] would be called a value, but how are the numbers 0,1 and 2 called? are that keys? didn't know where else to post this question. This might be more than just a php question but here goes anyways. I have designed a php chat room page on my home Apache server just for a few friends & family. The problem I have is the only way for me to know if anyone is on the chat room page is if I'm actually viewing the php page. Is there a way that I can have the page alert me when someone accesses it? I was thinking something like activating a popup in my browser or even a beep so as long as I'm at my computer with my browser open that I will know someone has accessed the page. Hi all, I want to be able to have one file (configuration file i guess) where i set the phone number, address, staff names and positions, etc. and then have them display at different places on various pages. I thought they were inc files, but all i can find is the likes of headers and footers. Any help much appreciated. I just don't know what it's called, if someone can point me in the right direction, thanks. MsKazza Here is my code which i use to recieve uploaded files.
$filepath = $_SERVER['DOCUMENT_ROOT'] . "file/"; $fileunzippath = $filepath."unzipped/"; $exclude_list = array(".", "..", "...", "index.php", ".php", ".htaccess"); if($_FILES["zip_file"]["name"]) { $filename = $_FILES["zip_file"]["name"]; $source = $_FILES["zip_file"]["tmp_name"]; $type = $_FILES["zip_file"]["type"]; $name = explode(".", $filename); $accepted_types = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed'); foreach($accepted_types as $mime_type) { if($mime_type == $type) { $okay = true; break; } } $continue = strtolower($name[1]) == 'zip' ? true : false; if(!$continue) { $message = "The file you are trying to upload is not a .zip file. Please try again."; } $string = preg_replace(array('/\s/', '/\.[\.]+/', '/[^\w_\.\-]/'), array('_', '.', ''), $filename); $clean_name = strtr($string, array('Š' => 'S','Ž' => 'Z','š' => 's','ž' => 'z','Ÿ' => 'Y','À' => 'A','Á' => 'A','Â' => 'A','Ã' => 'A','Ä' => 'A','Å' => 'A','Ç' => 'C','È' => 'E','É' => 'E','Ê' => 'E','Ë' => 'E','Ì' => 'I','Í' => 'I','Î' => 'I','Ï' => 'I','Ñ' => 'N','Ò' => 'O','Ó' => 'O','Ô' => 'O','Õ' => 'O','Ö' => 'O','Ø' => 'O','Ù' => 'U','Ú' => 'U','Û' => 'U','Ü' => 'U','Ý' => 'Y','à' => 'a','á' => 'a','â' => 'a','ã' => 'a','ä' => 'a','å' => 'a','ç' => 'c','è' => 'e','é' => 'e','ê' => 'e','ë' => 'e','ì' => 'i','í' => 'i','î' => 'i','ï' => 'i','ñ' => 'n','ò' => 'o','ó' => 'o','ô' => 'o','õ' => 'o','ö' => 'o','ø' => 'o','ù' => 'u','ú' => 'u','û' => 'u','ü' => 'u','ý' => 'y','ÿ' => 'y')); $clean_name = strtr($clean_name, array('Þ' => 'TH', 'þ' => 'th', 'Ð' => 'DH', 'ð' => 'dh', 'ß' => 'ss', 'Œ' => 'OE', 'œ' => 'oe', 'Æ' => 'AE', 'æ' => 'ae', 'µ' => 'u')); $clean_name = preg_replace(array('/\s/', '/\.[\.]+/', '/[^\w_\.\-]/'), array('_', '.', ''), $clean_name); $target_path = $filepath.$clean_name; // change this to the correct site path if(move_uploaded_file($source, $target_path)) { echo "Source: ".$source."<br/>"; echo "Type: ".$type."<br/>"; echo "Filename: ".$filename."<br/>"; $zip = new ZipArchive(); $x = $zip->open($target_path); if ($x === true) { $zip->extractTo($fileunzippath.$clean_name); // change this to the correct site path $zip->close(); $exclude_list; $dir_path = $_SERVER['DOCUMENT_ROOT']; $dir_path .= "/file/unzipped/"; $directories = array_diff(scandir($fileunzippath.$clean_name), $exclude_list); foreach($directories as $entry) { if(is_dir($dir_path.$entry)) { if($entry != 'part0' || $entry !='part1') { rmdir($entry); } } } } $message = "Your .zip file was uploaded and unpacked."; } else { $message = "There was a problem with the upload. Please try again."; } }Specifically i want to highlight this part: $exclude_list; $dir_path = $_SERVER['DOCUMENT_ROOT']; $dir_path .= "/file/unzipped/"; $directories = array_diff(scandir($fileunzippath.$clean_name), $exclude_list); foreach($directories as $entry) { if(is_dir($dir_path.$entry)) { if($entry != 'part0' || $entry !='part1') { rmdir($entry); } } }When I upload a zip file containing 2 directories(one called 'part0', and one called 'bad'), they get unzipped correctly and it gives no errors, however the fake directories(not called part0 or part1) I put in there are still there. Any Help? Hello I have a php website. I am trying to trace (find out) which files are called when a page is displayed. For example on certain pages that get displayed it may call up to 6-7 files. I would like to know the name of the files and the order they are called. As through out the code there is a lot of include_once("global/global.libs.php"); Is there any may to easily trace this without having to go through page by page on the code and try to figure out what is happening. Essentially I just want the file name eg global/global.libs.php logged somewhere Thanks in advance Hi All, I am using the uploadify script available at http://uploadify.com/ Now I can get the file uploads working fine with the script below: Code: [Select] <?php session_start(); ?> <link href="/uploadify/uploadify.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="/uploadify/jquery-1.3.2.min.js"></script> <script type="text/javascript" src="/uploadify/swfobject.js"></script> <script type="text/javascript" src="/uploadify/jquery.uploadify.v2.1.0.min.js"></script> <input id="fileInput" name="fileInput" type="file" /> <script type="text/javascript">// <![CDATA[ $(document).ready(function() { $('#fileInput').uploadify({ 'uploader' : '/uploadify/uploadify.swf', 'script' : '/uploadify/uploadify.php', 'cancelImg' : '/uploadify/cancel.png', 'auto' : true, 'folder' : '<?php echo $_SESSION['filepath']."/downloads/"; ?>', 'multi' : true }); }); // ]]></script> The problem that I am having is that I also store the mysql connection details in session vars (they change depending on who logs in). I have tried a number of ways of "passing" these session vars to the uploadify.php file which does the grunt work of the uploading, but I can never seem to access them. I obviously dont want to pass them to the uploadify.php script through the js because that will show my credentials in the source code. So, the question is, how can I access these session vars in the called file. I assume its a combination of session_write_end() and session_start() but I havent got the right combination yet. Hi I call a function with values of 51 and 100 but the function receives values 1 and 50
<?php // EmilyMoor Version 1.0.0 05-07-2019 Desmond O'Toole. ini_set('display_errors', 1); error_reporting(E_ALL); require("../secure/SecureFunctions.php"); require("secure/SecureFunctionsEmilyMoor.php"); $page = "Emily Moor"; session_start(); $Browser = $_SERVER['HTTP_USER_AGENT']; if (!isset($_SESSION["PageValue"])) $_SESSION["PageValue"] = '1'; $_SESSION["PageValue"] = 2; // Keeps going back to 1 if($_SESSION["PageValue"] == 1) { $_SESSION["StartValue"] = 1; $_SESSION["EndValue"] = 50; } if($_SESSION["PageValue"] == 2) { $_SESSION["StartValue"] = 51; $_SESSION["EndValue"] = 100; } if($_SESSION["PageValue"] == 3) { $_SESSION["StartValue"] = 101; $_SESSION["EndValue"] = 150; } if($_SESSION["PageValue"] == 4) { $_SESSION["StartValue"] = 151; $_SESSION["EndValue"] = 200; } if($_SESSION["PageValue"] == 5) { $_SESSION["StartValue"] = 201; $_SESSION["EndValue"] = 250; } if($_SESSION["PageValue"] == 6) { $_SESSION["StartValue"] = 251; $_SESSION["EndValue"] = 300; } echo $_SESSION["PageValue"] . " - " . $_SESSION["StartValue"] . " - " . $_SESSION["EndValue"] . "<br>"; $qStationDetails = GetChanelInfo($_SESSION["StartValue"],$_SESSION["EndValue"]); $rs = mysql_fetch_array($qStationDetails) or die ("E3001-101A"); $Name = $rs['Description']; ?> function GetChanelInfo($StartCH, $EndCH) // E2004 { echo "Channels = " . $StartCH . " " . $EndCH . "<br>"; // values are 1 and 50 $sqlChanelInfo = "SELECT * FROM TV_EmilyMoor WHERE ID >= $StartCH and ID <= $EndCH"; echo $sqlChanelInfo . "<br />"; $qChanelInfo = mysql_query($sqlChanelInfo) or die ("E3004-01A"); return $qChanelInfo; }
Hello all, I have been working with PHP for almost a year now, so somewhat still new to it all. OK, this may be an Apache issue, but this involves a php script I wrote that tries to execute on pages that do NOT call it (via the include command). So, here is a little info on how I have set things up. I use WAMP Server to test php and MySQL code for myself (for fun and for practice) and for clients and their web sites. I run WAMP Server off of my laptop, so I can code on the go and because it is on my laptop, I decided to create a PHP & MySQL user authentication setup to keep out unwanted visitors, but allow trusted friends and fellow developers to view my work on client web sites. Let's say the authentication script is called "auth.php" and for all of the pages I want private, I include that script at the top of those pages, if the visitor is not logged in, redirect them to the login page, otherwise, let them view the page (provided their permission level is adequate). Now, for the client web sites that I am working on, I do not call auth.php anywhere on those pages. Now, the problem I notice is that when I visited a client's web site that I am working on (on my WAMP Server), I reviewed my Apache error log and it gave me a PHP error stating the following: Code: [Select] Maximum execution time of 60 seconds exceeded in E:\\wamp\\www\\assets\\auth.php on line 3, referer: http://192.168.1.4/Web_Projects/NCCCLP/home.php Of course I am able to view the client web site pages without having to login, however, the auth.php script tries to run nonetheless. So my question is, does anyone know why this is happening and if and how I can stop it? This is not a serious (urgent) issue, but it does clog up my error logs and so forth and I prefer to have as few errors as possible. Plus, I would just like to know why and how it is running without being called. Any and all help is greatly appreciated and if I need to provide anymore details or be more specific, please let me know. Also, if an issue like this has already been solved and I missed that thread, please let me know and have my apologies. Thanks in advance. Im using this code to call all the images in a folder: Code: [Select] $handle = opendir(dirname(realpath(__FILE__)).'/images/'); while($file = readdir($handle)){ if($file !== '.' && $file !== '..'){ echo '<img src="admin/img/uploads/'.$file.'" border="0" />'; } } My html says the images are present but they aren't visable on screen: Code: [Select] <div id="contentbody"> <img src="admin/img/uploads/send-button-sprite copy.png" border="0" /> <img src="admin/img/uploads/test" border="0" /> <img src="admin/img/uploads/counter.jpg" border="0" /> <img src="admin/img/uploads/send-button-sprite.png" border="0" /> </div> Any help is much appreciated! I have this script Code: [Select] <?php header("content-type: image/png"); include '../../api/config.php'; include "../../api/api.php"; $gamercard = getInfo($_GET['gamertag']); updateStats($gamercard['Gamertag'], "Nxe", 75); $type = $_GET['type']; switch ($type) { case "dark": $type = "dark.png"; break; case "light": $type = "light.png"; break; default: $type = "dark.png"; break; } $image = imagecreatefrompng("$type"); $img = imagecreatetruecolor(imagesx($image), imagesy($image)); $avatar_l = imagecreatefrompng($gamercard["Avatarpic-l"]); $avatar_body = imagecreatefrompng($gamercard["Avatarpic-body"]); imagecopy($img, $image, 0, 0, 0, 0, imagesx($image), imagesy($image)); imagecopy($img, $avatar_l, 64, 7, 0, 0, imagesx($avatar_l), imagesy($avatar_l)); imagecopy($img, $avatar_body, 175, -40, 0, 0, imagesx($avatar_body), imagesy($avatar_body)); for($i = 1; $i <=count($gamercard["RecentGames"]); $i++) { $gameimg = imagecreatefromjpeg($gamercard["RecentGames"][$i]["Icon"]); $x = ($i-1)*35 + 10; imagecopy($img, $gameimg, $x, 77, 0, 0, imagesx($gameimg), imagesy($gameimg)); } $ColorText = imagecolorallocate($img, 255, 255, 255); ImageTTFText($img, 10, 0, 10, 127, $ColorText, "font.ttf", $gamercard['Gamertag']); ImageTTFText($img, 10, 0, 135, 127, $ColorText, "font.ttf", $gamercard['Gamerscore']); imagepng($img); imagedestroy($img); ?> which is made to call the updateStats() function 1 time everytime the page loads. Heres the function (its in api.php) Code: [Select] function updateStats($gamertag, $type, $size) { $query = mysql_query("SELECT * FROM loadstats where Gamertag = '$gamertag' && Type = '$type'") or die(mysql_error()); $exists = mysql_num_rows($query); if ($exists == 0) { mysql_query("INSERT INTO loadstats (Gamertag, Type, Loads, Data) VALUES('$gamertag', '$type', '1', '$size' )") or die(mysql_error()); } else { $row = mysql_fetch_array($query); $newloads = $row['Loads'] + 1; $newdata = $row['Data'] + $size; mysql_query("UPDATE loadstats SET Loads = '$newloads' WHERE gamertag = '$gamertag' && Type = '$type'") or die(mysql_error()); mysql_query("UPDATE loadstats SET Data = '$newdata' WHERE gamertag = '$gamertag' && Type = '$type'") or die(mysql_error()); } } The wierd thing that is happening is, When i have the Header() set in the script, the updateStats() function appears to be called twice, but when the header is commented out, it is only called once. I can tell this by the change of data in the MYSQL database, the Loads value increases by 2 when the header is set, and it only creases by 1 when it isnt set. Any insight as to why this is happening would be greatly appreciated. Hi everyone!
I've been working on a php script to replace links that contain a query with direct links to the files they would redirect to. In this case I have to rewrite the xml with this script. Situation is not optimal, I'm running the chunk script because we're stuck with the execution time limit too. Export filter: This loops over a xml file and splits it into chunks <?php //ini_set('max_execution_time', 10); // ---- includes if ( ! defined('ABSPATH') ) { require_once( dirname( __FILE__ ) . '/wp-load.php' ); } // ---- end includes // console function vwaconsole($input) { $disabled = false; if ($disabled === false) { $a = print_r($input.'</br>'); $a = $input; echo "<script>console.log( '--log--: " . $a . "' );</script>"; } } //end console // settings // $chunk_size = 20; // $home = constant( 'ABSPATH' ); $xml_path = $home."/wp-content/uploads/wpallimport/files/Bastiaansen.xml"; if (fopen($xml_path,"r") != true) { vwaconsole("xml file does not exist"); exit(); } $xml = new DOMDocument(); $xml->formatOutput = true; $xml->preserveWhiteSpace = false; $xml->load($xml_path); // Main program // creates another file to be filled by sub scripts if (!empty($xml)) { vwaconsole("Running main program"); // backup xml first $date = "_".date("Y M D h i"); $date = str_replace(' ', '_', $date); $xpath = new DOMXpath($xml); $items = $xpath->query("//aanbiedingen//item"); $loopcount = 0; $processedamount = 0; $islast = 0; vwaconsole('total items: '.$items->length); vwaconsole('chunk size: '.$chunk_size); echo'<br>'; /* chunks processing: */ $chunkxml = new DOMDocument(); $chunkxml->formatOutput = true; $chunkxml->preserveWhiteSpace = false; $counter = 0; $chunkroot = null; foreach($items as $item) { //vwaconsole('processing item'); if ($chunkroot === null) { $chunkroot = $chunkxml->createElement('root'); $chunkxml->appendChild($chunkroot); //vwaconsole('created root'); } if (($processedamount + $chunk_size) > $items->length) { //vwaconsole("last chunk in progress..."); $islast = 1; } $chunkitem = $chunkxml->createElement($item->nodeName); $chunkroot->appendChild($chunkitem); //vwaconsole('appended child item to root'); foreach($item->childNodes as $spec) { //vwaconsole('processing specs in item'); $chunkspec = $chunkxml->createElement($spec->nodeName); $chunkitem->appendChild($chunkspec); $chunkspectext = $chunkxml->createTextNode($spec->nodeValue); $chunkspec->appendChild($chunkspectext); } $counter++; $processedamount++; if ($counter >= $chunk_size) { $chunkxml->save("wp-content/uploads/wpallimport/files/chunks_bast/bast_chunk_".$loopcount.".xml"); vwaconsole("saved array chunk"); $output = `php export_filter_chunk_processor.php $loopcount $islast `; vwaconsole($output); vwaconsole("creating new array chunk"); $chunkxml = new DOMDocument(); $chunkxml->formatOutput = true; $chunkxml->preserveWhiteSpace = false; $loopcount++; $counter = 0; $chunkroot = null; } if ($items->length === $processedamount) { $chunkxml->save("wp-content/uploads/wpallimport/files/chunks_bast/bast_chunk_".$loopcount.".xml"); vwaconsole("finished saving last chunk"); } } // merge documents later.. /* $newxml = new DOMDocument("1.0", "utf-8"); $newxml->formatOutput = true; $newxml->preserveWhiteSpace = false; $itemContainer = $newxml->createElement('aanbiedingen'); $newxml->appendChild($itemContainer); //$newxml->save("wp-content/uploads/wpallimport/files/TEMP_Bastiaansen.xml"); */ vwaconsole("main ending"); exit(); } else { //vwaconsole("xml is empty ?! exiting"); exit(); } ?>
Export chunk processor: The xml was split by the previous script. This one takes one of the chunks and calls get_headers() , sending a link containing a query multiple of this script run at same time. The queries are then picked up by the last php file. <?php //ini_set('max_execution_time', 10); // console function vwaconsole($input) { $disabled = false; if ($disabled === false) { $a = print_r($input.'</br>'); $a = $input; echo "<script>console.log( '--log--: " . $a . "' );</script>"; } } //end console //echo'<br>'; print_r("called chunk processor > Chunk processor started. "); //echo'<br>'; $loopcount=$argv[1]; $islast=$argv[2]; if ($loopcount === null || $islast === null) { print_r("CHUNK PROCESSOR ERROR > loop count is empty"); exit(); } else { print_r("CHUNK PROCESSOR variables set. loop count: ".$loopcount." is last: ".$islast."<br>"); } if ( ! defined('BAST_ROOT_DIR') ) { define('BAST_ROOT_DIR', __DIR__); } $home = constant( 'BAST_ROOT_DIR' ); $xml_path = $home."/wp-content/uploads/wpallimport/files/chunks_bast/bast_chunk_".$loopcount.".xml"; if (fopen($xml_path,"r") != true) { print_r("chunk file was not found at path: ".$xml_path); exit(); } $xmlChunk = new DOMDocument(); //$xmlChunk = new DOMDocument(); $xmlChunk->formatOutput = true; $xmlChunk->preserveWhiteSpace = false; $xmlChunk->load($xml_path); if (empty($xmlChunk)) { print_r("chunk data is empty, exiting"); exit(); } else { print_r("got chunk data <br>"); } $xpath = new DOMXpath($xmlChunk); $item = $xpath->query("//root//item"); //$items = $xmlChunk->getElementsByTagName('//root//item'); foreach ($item as $node) { echo'new item: <br>'; foreach ($node->childNodes as $spec) { //vwaconsole("processing spec: ".$spec->nodeName); if (($spec->nodeName == 'itemlink')) { $memValue = $spec->nodeValue; //setting new url spec node $spec->nodeValue = processItemLink($memValue); // add new itemfoto nodes to xml } elseif(($spec->nodeName == 'itemfoto1')) { $memValue = $spec->nodeValue; $imgurls = array(); $first = true; for ($i = 1; $i < 50; $i++) { if ($first === false) { $memValue = str_replace('bast_get_itemfoto_id='.strval($i-1), 'bast_get_itemfoto_id='.strval($i), $memValue); } vwaconsole("trying to get a itemfoto with id: ".strval($i)." link: " .$memValue); $triedFotoUrl = processItemLink($memValue); vwaconsole("tried url: ".$triedFotoUrl); if($triedFotoUrl !== $memValue) { $imgurls[] = $triedFotoUrl; } else { vwaconsole("tried url and processed url are equal. end of loop. No new images left or error happened."); break; } $first = false; } //remove the old single itemfoto from xml $spec->parentNode->removeChild($spec); // add sorted nodes from image array if (!empty($imgurls)) { sort($imgurls, SORT_NATURAL); print_r('<br> after sort;'); print_r($imgurls); print_r('<br>'); $arlength = count($imgurls); for($x = 0; $x < $arlength; $x++) { $newItemFoto = $xml->createElement('itemfoto'.strval($x+1)); $newItemFotoText = $xml->createTextNode($imgurls[$x]); $newItemFoto->appendChild($newItemFotoText); $node->appendChild($newItemFoto); } unset($imgurls); } } } echo'<br>'; } //returns string url //follow the query url from xml, return a direct link or returns input on failure. query is processed in Bastiaansen.php. function processItemLink($url) { if (!empty($url)) { $headers = get_headers($url, 1); if(!empty($headers['Location'])) { vwaconsole('test returning header location: '.$headers['Location']); return $headers['Location']; } else { vwaconsole("header empty ?!?! can't convert query"); } } return $url; } $xmlChunk->save("wp-content/uploads/wpallimport/files/chunks_bast/bast_chunk_test_".$loopcount.".xml"); ?>
When the chunk processor calls a query link with get_headers(), the query will be noticed by the next script, the query converter: <?php if ( ! defined('ABSPATH') ) { require_once( dirname( __FILE__ ) . '/wp-load.php' ); } // ---- vars $machineID = $_GET['bast_get_machine_id']; $itemlink = $_GET['bast_get_itemlink']; $itemfoto_id = $_GET['bast_get_itemfoto_id']; if (!empty($itemlink)) { $request = 'bast_get_itemlink'; $value = $itemlink; } elseif (!empty($itemfoto_id)) { $request = 'bast_get_itemfoto_id'; $value = $itemfoto_id; } // ---- end vars if (empty($machineID)) { echo 'please enter query ?bast_get_machine_id=(number) first'; exit(); } if (empty($request) || empty($value)) { echo 'Valid query request would be: bast_get_itemlink <br>'; echo 'Valid query request would be: bast_get_itemfoto_id <br>'; exit(); } // register custom query options function sm_register_query_vars( $vars ) { // get the right custom field names $vars[] = $request; $vars[] = 'pa_'.$request; return $vars; } add_filter( 'query_vars', 'sm_register_query_vars' ); //returns null or string url function fetch($machineID,$request,$value) { $return = null; $args = array( 'orderby' => 'meta_value_num', 'meta_key' => 'bast_get_machine_id', 'meta_type' => 'NUMERIC', 'post_type' => 'product', 'posts_per_page' => -1, 'order' => 'ASC', 'meta_query' => array( array( 'key' => 'bast_get_machine_id', 'type' => 'NUMERIC', 'value' => $machineID, 'compare' => 'EXISTS', ) ) ); $wp_query = new WP_Query($args); if ( $wp_query->have_posts() ) { while ( $wp_query->have_posts() ) { $wp_query->the_post(); apply_filters( 'the_content', 'filter_post_content' ); echo 'found product " '.get_the_title().' " on machine ID '.$machineID.'<br>'; echo 'requested: '.$request.'<br>'; if ($request === 'bast_get_itemlink') { // product url $return = get_permalink(get_the_ID()); break; } elseif ($request === 'bast_get_itemfoto_id') { // image attachment $attachments = get_posts(array( 'post_type' => 'attachment', //'post_mime_type' => 'image', 'posts_per_page' => -1, 'post_parent' => get_the_ID() //'exclude' => get_post_thumbnail_id() )); // as the requested value should be 1, but the array starts at 0.. remove 1 from value if (!empty($attachments) && ($attachments != false) && !empty($attachments[$value-1]) && ($attachments[$value-1] != false) ) { $return = wp_get_attachment_image_src( $attachments[$value-1]->ID, 'full')[0]; echo 'attachment found'; } else { echo 'attachment empty...'; } echo 'total amount of images found on this machine: '.count($attachments); break; } break; } /* Reset Post Data after loop */ wp_reset_postdata(); } else { echo 'query on machine ID '.$machineID.' found no product. Exit.'; } return $return; } function filter_post_content( $content ) { // Check if we're inside the main loop in a single post page. if ( is_single() && in_the_loop() && is_main_query() ) { return $content; } return $content; } $finaldestination = fetch($machineID,$request,$value); if (empty($finaldestination)) { exit(); } //echo 'destination set: '.$finaldestination.'<br>'; header("Location: ".$finaldestination, true, 302); ?>
|