Jump to content

kicken

Gurus
  • Posts

    4,695
  • Joined

  • Last visited

  • Days Won

    177

Everything posted by kicken

  1. No, you can't just add arguments. You can inline the array's if you want, but if your number of replacements gets large it's more readable to have them separate. str_replace(array(' ', '-'), array('cars', 'bikes'), $row['model']);
  2. No. -- and ++ work on the variable directly. Using the variable that you apply the ++/-- to elsewhere in the same statement generally falls under the category 'Undefined Behavior'. This means the computer can do whatever it wants and it'll be considered a valid response to the operation. I'm not sure if php defines this behavior or not. I know for instance C does not. The statement $a = $a--; could be interpreted as multiple different actions sequences, which each would have separate outputs. Assume $a=10 to start with, it could be: $a=10; $tmp = $a; //save the value of $a for use later. $a = $a - 1; // the -- operation $a = $tmp; //use the previous value of $a //final result is $a = 10. The -- is essentially nullified. or it could be run as: $a = 10; $a = $a; //Use the current $a; $a = $a - 1; //run the -- operation //final result is $a=9.
  3. You can use phpinfo() to check. Just make a page with the following: <?php phpinfo(); ?> The search the output for the 'magic_quotes_gpc' directive and see what the values are. While it's possible to disable it at runtime, it does not do any good. By the time your script is executed, PHP will already have collected the input data and run the magic quotes process so changing the setting has no effect.
  4. First, your examples are backwards. $a++ / $a-- is a postfix increment (or decrement). The ++ or -- comes after (post) the variable. ++$a / --$a is a prefix increment (or decrement). The ++ or -- comes before (pre) the variable. Prefix increment causes the variables value to be incremented and then returned. eg: $a=10; $b = ++$a; //is the same as $a = 10; $a = $a + 1; $b = $a; Postfix increment causes the varaibles value to be returned, then incremented after. $a = 10; $b = $a++; //is the same as $a = 10; $b = $a; $a = $a + 1; Decrement is the exact same, but subtracting one rather than adding one.
  5. I assume you want to know if the user is on cable, dsl, wifi, dial-up, etc? That's not something an IP will tell you. Some ISP's give hints about that in their reverse dns of an ip, but that's not something you can rely on, and it may not really even be accurate. You'd have to have a database on your end that could map ip ranges to connection type. Creating such a database would mean having to find out who owns what IP blocks, and what services they provide with those IPs. I have no idea if such a DB already exists that you might download/buy. Google may know.
  6. mysql_real_escape_string() is sufficient. stripslashes is unnecessary unless your host has magic_quotes_gpc enable and you need to undo that prior to processing the data. If that is the case, you should have a little script to do that as part of your script startup and which is run on every page (usually put in a file and included on ever page). You'll want to save your mysql_real_escape_string until your ready to put the value into SQL. Do all your validations and other checks prior to escaping it, as escaping it can introduce characters or conditions that may cause an otherwise valid string to fail validation. Optionally, if your validation process will ensure that a string will cause no problems (eg, if you validate a string contains only 'a'-'z' or only '0'-'9') you could skip the mysql_real_escape_string call, but continuing to do it will not hurt either.
  7. Using url re-writing, or some other method in which your requests are all routed through a single script which parses the url to grab whatever data is necessary and sends it to another script internally. In apache the easy way to do this is mod_rewrite. IIS also has a URL Rewriter module you can install. Stored procedures save a step of the DB engine having to compile the SQL and develop an execution plan. It can do this ahead of time and then just run it each time the procedure is called. For simple things like updating a user's last login time or just getting their info, this is not going to make a difference at all. For more complicated actions which involve several queries in can be beneficial. For instance, if you have a report which needs to run a number of different queries and combine the results a procedure may help. The main benefit of a procedure is to keep a task isolated in sql and it can make it easier to re-use the same process in multiple places in the code. Some places also use procedures as a way to enforce certain data requirements by only allowing an application to access the DB via a procedure, not allowing it to access the tables directly.
  8. You should be able to pull out a GUID and then use it in another query without any problem. I do that in various places in our application code with no problems at all. Just make sure your generating a valid query and that your GUID is formatted correctly when being insert into the query. The GUID should be formatted such as: '0856B94A-2BF4-476B-AFA2-44F4CCF022AF', optionally including braces on the ends: '{0856B94A-2BF4-476B-AFA2-44F4CCF022AF}' PHP Should receive it as a string without any need to explicitly convert it, and sql server should accept it in string form in a query.
  9. I spent a little time fixing up the code I had written for websockets to handle the updated protocol. Here's the code, if anyone finds it useful. It is based around PHP's Stream's api rather than the socket extension. It's not a full and complete implementation, but should be enough to get things started for anyone really interested in websockets. WebSocketConnection.class.php: <?php require __DIR__.DIRECTORY_SEPARATOR.'WebSocketMessage.class.php'; require __DIR__.DIRECTORY_SEPARATOR.'ILogger.interface.php'; class WebsocketConnection { private $mReadBuffer; protected $mProtoType; protected $mProtoVersion; protected $mState; protected $mReceivedClose; protected $mSentClose; protected $mCloseStartedOn; protected $mStream; protected $mRequestUri; protected $mHeaders; protected $mLoggers; const HANDSHAKE=1; const ESTABLISHED=2; const CLOSING=3; const CLOSED=4; const PROTO_HYBI='hybi'; const PROTO_HIXIE='hixie'; public function __get($nm){ throw new Exception('Unknown property '.$nm); } public function __set($nm,$v){ throw new Exception('Unknown property '.$nm); } public function __construct(){ $this->mState = self::CLOSED; $this->mReadBuffer = null; $this->mStream = null; $this->mHeaders=array(); $this->mRequestUri=''; $this->mLoggers=array(); $this->mReceivedClose=false; $this->mSentClose=false; $this->mCloseStartedOn=0; } public function addLogger(ILogger $logger){ $this->mLoggers[]=$logger; } private function log($str){ foreach ($this->mLoggers as $l){ $l->log($str); } } public function GetStream(){ return $this->mStream; } public function IsConnected(){ return $this->mState == self::ESTABLISHED || $this->mState == self::CLOSING; } /** * Fill the read buffer from the stream * */ protected function fillReadBuffer(){ $r = array($this->mStream); $w = $e = null; while (stream_select($r, $w, $e, 0, 0) > 0){ $this->log('Reading data from stream'); $data = fread($this->mStream, 1024); if (strlen($data)==0){ //Reading 0 data means the stream has been closed $this->Close(true); return; } $this->mReadBuffer .= $data; //$this->log('Read data: '.$data); $r = array($this->mStream); $w = $e = null; } } protected function WriteStream($str){ fwrite($this->mStream, $str); } /** * Locates the first instance of a set of strings * Returns the position in $str, optionally returns the length * of the string found in $oLen */ protected function indexOfFirst($str, $findArr, &$oLen=null){ $posArr = array(); foreach ($findArr as $f){ $posArr[] = array(strpos($str, $f), strlen($f)); } $finalPos = false; $oLen = null; foreach ($posArr as $p){ if ($p[0] !== false){ if ($finalPos === false || $finalPos > $p[0]){ $finalPos = $p[0]; $oLen = $p[1]; } } } return $finalPos; } /** * Read up to (and including) the next \r\n from the input buffer * Returns false if a full line cannot be read. * */ protected function readLine(&$line){ $pos = $this->indexOfFirst($this->mReadBuffer, array("\r\n", "\n", "\r"), $len); if ($pos !== false){ $end = $pos+$len; $line = substr($this->mReadBuffer, 0, $end); $this->mReadBuffer = substr($this->mReadBuffer, $end); return true; } return false; } /** * Reads exactly the specified number of bytes */ protected function readExactly($bytes, &$output){ if (strlen($this->mReadBuffer) > $bytes){ $output = substr($this->mReadBuffer, 0, $bytes); $this->mReadBuffer = substr($this->mReadBuffer, $bytes); return true; } return false; } /** * Peeks at the buffer by reading the requested data but not removing it from the buffer. * */ protected function peekExactly($bytes, &$output){ if (strlen($this->mReadBuffer) > $bytes){ $output = substr($this->mReadBuffer, 0, $bytes); return true; } return false; } /** * Read the opening handshake from other stream resources * */ protected function readHeaders(){ $endOfHeaders=false; do { $this->fillReadBuffer(); $curHeader=array(); while (!$endOfHeaders && $this->readLine($line)){ $line = rtrim($line, "\r\n"); if ($line==''){ $endOfHeaders=true; } else { if (substr($line, 0, 3) == 'GET'){ $resourceStart = strpos($line, ' ')+1; $resourceEnd = strpos($line, ' ', $resourceStart); $this->mRequestUri = substr($line, $resourceStart, $resourceEnd-$resourceStart); } else { if (!ctype_space($line[0])){ if (!empty($curHeader)){ $this->mHeaders[$curHeader[0]] = $curHeader[1]; } $pos = strpos($line, ':'); $curHeader[0] = rtrim(strtoupper(substr($line, 0, $pos))); $curHeader[1] = ltrim(substr($line, $pos+1)); } else { $curHeader[1] .= ' '.ltrim($line); } } } } } while (!$endOfHeaders); if ($curHeader){ $this->mHeaders[$curHeader[0]] = $curHeader[1]; } } /** * Upgrades the connection, processing the opening handshake and enabling the websocket. * */ public function DoUpgrade($stream){ if (!is_resource($stream)){ throw new InvalidArgumentException('Stream must be specified and must be a resource'); } $this->mStream = $stream; if (function_exists('stream_set_read_buffer')){ stream_set_read_buffer($this->mStream, 0); } stream_set_write_buffer($this->mStream, 0); stream_set_timeout($this->mStream, 2, 0); return $this->ProcessHandshake(); } protected function ProcessHandshake(){ $this->readHeaders(); $this->log('Headers are: '.print_r($this->mHeaders, true)); $responseCode = 101; $acceptKey = null; if (isset($this->mHeaders['SEC-WEBSOCKET-KEY1']) && isset($this->mHeaders['SEC-WEBSOCKET-KEY2'])){ $this->mProtoType = self::PROTO_HIXIE; $this->mProtoVersion = 76; } else if (isset($this->mHeaders['SEC-WEBSOCKET-KEY'])){ $this->mProtoType = self::PROTO_HYBI; $this->mProtoVersion = 17; } else { $this->log('Unknown websocket protocol.'); throw new Exception('Unknown websocket protocol'); } if (isset($this->mHeaders['SEC-WEBSOCKET-VERSION'])){ $this->mProtoVersion = intval($this->mHeaders['SEC-WEBSOCKET-VERSION']); } if ($this->mProtoType==self::PROTO_HIXIE){ while (!$this->readExactly(8, $last8)){ $this->fillReadBuffer(); } $keys = array(null, null, $last8); try { foreach (array($this->mHeaders['SEC-WEBSOCKET-KEY1'], $this->mHeaders['SEC-WEBSOCKET-KEY2']) as $n=>$val){ $digits = ''; $spaces = 0; for ($i=0; $i<strlen($val); $i++){ $c = $val[$i]; if (ctype_digit($c)){ $digits .= $c; } else if (ctype_space($c)){ $spaces++; } } if ($spaces==0){ throw new Exception('No spaces found in key. Must be at least one.'); } $keys[$n] = floatval(floatval($digits)/$spaces); } $finalKey = pack('N2a8', intval($keys[0]), intval($keys[1]), $keys[2]); $acceptKey = md5($finalKey, true); } catch (Exception $e){ $this->log('Unable to generate accept key.'); $responseCode=400; break; } } else { $key = trim($this->mHeaders['SEC-WEBSOCKET-KEY']); $key = $key.'258EAFA5-E914-47DA-95CA-C5AB0DC85B11'; $acceptKey = base64_encode(sha1($key, true)); } if (!isset($this->mHeaders['UPGRADE']) || strcasecmp($this->mHeaders['UPGRADE'], 'websocket') != 0){ $this->log('No or Bad upgrade header'); $this->log('$this->mHeaders[uPGRADE] = '.$this->mHeaders['UPGRADE']); $this->log('strcasecmp = '.strcasecmp($this->mHeaders['UPGRADE'], 'websocket')); var_dump($this->mHeaders['UPGRADE']); $responseCode = 400; } /*if (isset($this->mHeaders['SEC-WEBSOCKET-PROTOCOL'])){ $requestedProtos = explode(',', $this->mHeaders['SEC-WEBSOCKET-PROTOCOL']); $hasValidProto = false; foreach ($requestedProtos as $p){ if ($this->mServer->IsValidProtocol($p)){ $hasValidProto = true; } } if (!$hasValidProto){ $responseCode = 406; break; } }*/ if (!$acceptKey){ $responseCode=500; } $origin = isset($this->mHeaders['ORIGIN'])?$this->mHeaders['ORIGIN']:'null'; $resource = sprintf('ws://%s%s', $this->mHeaders['HOST'], $this->mRequestUri); $this->log('Response Code is '.$responseCode); switch ($responseCode){ case 101: $response = "HTTP/1.1 101 Upgraded\r\n"; $response .= "Upgrade: WebSocket\r\n"; $response .= "Connection: Upgrade\r\n"; $response .= "Sec-WebSocket-Origin: {$origin}\r\n"; $response .= "Sec-WebSocket-Location: {$resource}\r\n"; if (isset($this->mHeaders['SEC-WEBSOCKET-PROTOCOL'])){ $response .= "Sec-WebSocket-Protocol: {$this->mHeaders['SEC-WEBSOCKET-PROTOCOL']}\r\n"; } if ($this->mProtoType==self::PROTO_HIXIE){ $response .= "\r\n{$acceptKey}"; } else { $response .= "Sec-WebSocket-Accept: {$acceptKey}\r\n"; $response .= "\r\n"; } break; case 400: $response = "HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n"; break; case 406: $response = "HTTP/1.1 406 Not Acceptable\r\nConnection: close\r\n\r\n"; break; case 500: default: $response = "HTTP/1.1 500 Internal Server Error\r\nConnection: close\r\n\r\n"; break; } $this->WriteStream($response); if ($responseCode == 101){ $this->mState = self::ESTABLISHED; return true; } else { fclose($this->mStream); $this->mStream = null; $this->mState = self::CLOSED; return false; } } public function Close($force=false){ if (!$this->mCloseStartedOn){ $this->mCloseStartedOn=time(); $this->log('Starting close at: '.$this->mCloseStartedOn); } if ($force || ($this->mSentClose && $this->mReceivedClose) || time()-$this->mCloseStartedOn > 10){ if ($this->mStream) fclose($this->mStream); $this->mState = self::CLOSED; $this->mStream = null; $this->log('Shutdown stream, socket is closed.'); } else { $this->mState = self::CLOSING; if (!$this->mSentClose){ $this->log('Sending close frame.'); $m = new WebSocketMessage(WebSocketMessage::TYPE_CLOSE); $this->SendMessage($m); } } } public function GetMessage(){ $this->fillReadBuffer(); $m = $this->ReadMessage(); if ($m && $m->Type == WebSocketMessage::TYPE_CLOSE){ $this->mReceivedClose = true; $this->Close(); $m = null; } return $m; } public function SendMessage(WebSocketMessage $msg){ if ($this->mProtoType == self::PROTO_HYBI){ $this->sendHybiMessage($msg); } else { $this->sendHixieMessage($msg); } if ($msg->Type == WebSocketMessage::TYPE_CLOSE){ $this->mSentClose=true; $this->Close(); } } protected function ReadMessage(){ $buff = $this->mReadBuffer; $ret=null; if ($this->mProtoType == self::PROTO_HYBI){ $ret=$this->readHybiMessage($buff); } else { $ret=$this->readHixieMessage($buff); } if ($ret){ $this->mReadBuffer = $buff; } return $ret; } protected function readHixieMessage(&$buffer){ $ret = null; if (strlen($buffer) > 0){ $type = ord($buffer[0]); if (($type & 0x80) == 0x80 && isset($buffer[1])){ $length = 0; $byteNum=1; do { $lenByte=ord($buffer[$byteNum++]); $length = ($length*128)+($lenByte&0x7F); } while (isset($buffer[$byteNum]) && ($lenByte&0x80)==0x80); if ($type == 0xFF && $length == 0){ $ret = new WebSocketMessage(WebSocketMessage::TYPE_CLOSE, null); $buffer = substr($buffer, min(strlen($buffer),2)); } else if ($length > 0){ $length = min(strlen($buffer),$length); $buffer = substr($buffer, $length); } } else if (($type&0x80) == 0){ $payload=array(); $byteNum=1; while (isset($buffer[$byteNum]) && ord($buffer[$byteNum]) != 0xFF){ $payload[] = $buffer[$byteNum++]; } if ($type == 0){ $ret = new WebSocketMessage(WebSocketMessage::TYPE_TEXT, implode('', $payload), count($payload)); $buffer = substr($buffer, $byteNum+1); } } } return $ret; } protected function readHybiMessage(&$buffer){ $ret = null; do { if (strlen($buffer) > 2){ $bytes = substr($buffer, 0, 2); $buffer = substr($buffer, 2); $byte = ord($bytes[0]); $flags = ($byte&0xF0)>>4; $opcode = $byte&0x0F; $byte = ord($bytes[1]); $ismasked = ($byte&0x80)>>7; $payloadLen = $byte&0x7F; $this->log(sprintf("Flags: %d; Opcode: %d; Masked: %d; Length: %d", $flags, $opcode, $ismasked, $payloadLen)); $validLen=false; switch ($payloadLen){ case '126': if (strlen($buffer) > 2){ $payloadLenBytes = substr($buffer, 0, 2); $buffer = substr($buffer, 2); $payloadLen = unpack('nlen', $data); $payloadLen = $payloadLen['len']; $validLen=true; } break; case '127': if (strlen($buffer) > { $payloadLenBytes = substr($buffer, 0, ; $buffer = substr($buffer, ; $data = unpack("Nhi/Nlo", $payloadLenBytes); $payloadLen = ($data['hi']<<32)|$data['lo']; $validLen=true; } break; default: /* $payloadLen is itself. */ } if ($opcode == 0x8){ //Disable mask on closing frames $ismasked=0; } if ($ismasked && strlen($buffer) > 4){ $maskKey = substr($buffer, 0, 4); $buffer = substr($buffer, 4); $this->log('Mask key: '.$maskKey); } else if ($ismasked){ break; //No mask given, but one should be given. } if (strlen($buffer) >= $payloadLen){ $payload = substr($buffer, 0, $payloadLen); $buffer = substr($buffer, $payloadLen); //$this->log('Payload (pre-mask): '.$payload); if ($ismasked){ $payload = $this->applyMask($payload, $payloadLen, $maskKey); //$this->log('Payload (post-mask): '.$payload); } $ret = new WebsocketMessage($opcode, $payload, $payloadLen); if ($flags&0x8 == 0){ $obj = $this->readHybiMessage($buffer); if ($obj){ $ret->Data .= $obj->Data; $ret->DataLength += $obj->DataLength; $buffer = $newBuffer; } } } } } while (false); return $ret; } protected function applyMask($payload, $payloadLen, $mask){ $newPayload=''; for ($i=0; $i<$payloadLen; $i++){ $keyByte = unpack('cchar', $mask[$i%4]); $keyByte = $keyByte['char']; $newPayload .= chr(ord($payload[$i]) ^ $keyByte); } return $newPayload; } protected function sendHybiMessage($msg){ $len = $msg->DataLength; if ($len > 125){ $len = 126; } $packet = pack('cc', 0x80 | $msg->Type, 0x00 | $len); if ($len == 126){ $packet .= pack('n', $msg->DataLength); } $packet .= $msg->Data; $this->WriteStream($packet); } protected function sendHixieMessage($msg){ if ($msg->Type == WebSocketMessage::TYPE_CLOSE){ $packet = chr(0xff).chr(0x00); } else { $utf8 = iconv('ISO-8859-1', 'UTF-8', $msg->Data); $packet = chr(0).$utf8.chr(0xFF); } $this->WriteStream($packet); } } ILogger.interface.php <?php interface ILogger { public function Log($str); } WebSocketMessage.class.php <?php class WebSocketMessage { public $Data; public $DataLength; public $Type; const TYPE_TEXT = 0x1; const TYPE_BINARY = 0x2; const TYPE_CLOSE = 0x8; public function __construct($Type, $Data='', $Len=null){ $this->Data = $Data; $this->Type = $Type; $this->DataLength = $Len?:strlen($Data); } public function __get($nm){ throw new Exception('Unknown property '.$nm); } public function __set($nm,$v){ throw new Exception('Unknown property '.$nm); } } And a sample server script: <?php require 'WebSocketConnection.class.php'; class EchoLogger implements ILogger { public function log($str){ echo rtrim($str), "\r\n"; } } $server=stream_socket_server('tcp://0.0.0.0:8010'); echo "Listening for connections\r\n"; while ($client=stream_socket_accept($server)){ $ws = new WebsocketConnection(); $ws->addLogger(new EchoLogger()); echo "Upgrading connection\r\n"; if ($ws->DoUpgrade($client)){ echo "Upgrade complete, entering loop\r\n"; do { $r = array($ws->GetStream()); $w = $e = null; if (stream_select($r, $w, $e, 10, 0) > 0){ if ($m = $ws->GetMessage()){ $m->Data = md5($m->Data); $m->DataLength = strlen($m->Data); $ws->SendMessage($m); } } } while($ws->IsConnected()); } else { echo "Upgrade failed\r\n"; } }
  10. Yes, what you want is a factory pattern. Your Root class does not extend any of the classes, it is it's own separate class. So your diagram would look like: Base Class | Root Class /\ | / \ | Class A Class B | Root class just uses an instance of either a or b, and decides which one at runtime based on some condition. Our payment stuff is setup such as: interface IPaymentGateway { public function ProcessCreditCard($params); //... } class PaypalPaymentGateway implements IPaymentGateway { public function ProcessCreditCard($params){ //Paypal methods here } } class PaygistixPaymentGateway implements IPaymentGateway { public function ProcessCreditCard($params){ //Paygistix methods here } } class PaymentGateway { public static function GetImplementation($impl){ switch ($impl){ case 'paypal': return new PaypalPaymentGateway(); case 'paygistix': return new PaygistixPaymentGateway(); default: throw new InvalidArgumentException('Invalid payment gateway type'); } } } In the site config file we have a constant defined: PAYMENT_GATEWAY_IMPL which specifies which gateway to use. Then in the code where we need to do a payment: $pg = PaymentGateway::GetImplementation(PAYMENT_GATEWAY_IMPL);
  11. Try echoing back the Sec-WebSocket-Origin: and Sec-WebSocket-Location: headers. Just send them in the response with the same values that were sent to you. I seem to recall chrome not accepting unless they were sent when I was working on it before.
  12. I was messing with Websockets toward the middle of the year and had developed some php scripts to manage them. I went to pull them up to post as an example, found out they don't work anymore because the protocol changed. I looked at updating it, didn't have the time though. Not sure how much more it will be changing, Hopefully it gets nailed down soon. I believe the current spec is http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17. The 'version 8' in the header maybe corrisponds to http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-08. I'd probably look at the newest and implement it, probably will still work with what chrome has implemented.
  13. I don't really know what your asking. Your code seems ok. You have a lot of if's since seem to not want to show any field that is blank. Not much of any better way to do that though, just have to deal with it if you want that level of appearance control. You could just have the field be empty but still shown, which would remove a lot of the if's and clean up the code a bit. You can still get rid of the number of echo's by just going in and out of php mode, depends on which style you like best I guess when it comes down to it. Neither is really any better or worse than the other. <!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" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>PDI NCMR - View</title> <link rel="stylesheet" type="text/css" href="CSS/view.css" /> </head> <body> <div id="logo"> <img src="images/PDI_Logo_2.1.gif" alt="PDI Logo" /> </div> <?php require_once('connectvars.php'); // Connect to the database $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); // Grab the profile data from the database if (!isset($_GET['id'])) { $query = "SELECT * FROM ncmr WHERE id = '$id'"; } else { $query = "SELECT * FROM ncmr WHERE id = '" . $_GET['id'] . "'"; } $data = mysqli_query($dbc, $query); $row = mysqli_fetch_array($data); if (!$row){ echo '<p class="error">Please contact the web administrator, there seems to be an error!</p>'; } else { $row['ncmrsr'] = trim($row['ncmrsr']); $row['ncmrsc'] = trim($row['ncmrsc']); ?> <h3 id="NCMR2">Non-Conforming Materials Report (NCMR: <?php echo $row['NCMR_ID']?>)</h3> <form id="all"> <fieldset> <?php if (!empty($row['Added_By'])) { ?><div id="ab"><tr><td><span class="b">Added By: </span></td><td><?php echo $row['Added_By']?></td></tr></div> <?php } ?> <?php if (!empty($row['Added_By_Date'])) { ?><div id="abd"><tr><td><span class="b">On: </span></td><td><?php echo $row['Added_By_Date']?></td></tr></div> <?php } ?> <div id="box"> <div id="box1"> <?php if (!empty($row['Nexx_Part'])) { ?><div id="np"><tr><td><span class="b">Nexx Part: </span></td><td><?php echo $row['Nexx_Part'];?></td></tr></div><?php } ?> <?php if (!empty($row['Nexx_Rev'])) { ?><div id="nr"><tr><td><span class="b">Nexx Rev: </span></td><td><?php echo $row['Nexx_Rev'];?></td></tr></div><?php } ?> <?php if (!empty($row['Nexx_Part_Description'])) { ?><div id="npd"><tr><td><span class="b">Nexx Part Description: </span></td><td><?php echo $row['Nexx_Part_Description'];?></td></tr></div><?php } ?> <?php if (!empty($row['NCMR_Qty'])) { ?><div id="ncqt"><tr><td><span class="b">NCMR Qty: </span></td><td><?php echo $row['NCMR_Qty'];?></td></tr></div><?php } ?> <div id ="JSI"> <?php if (!empty($row['JO'])) { ?><div id="JO"><tr><td><span class="b">JO: </span></td><td><br /><?php echo $row['JO'];?></td></tr></div><?php } ?> <?php if (!empty($row['SN'])) { ?><div id="SN"><tr><td><span class="b">SN: </span></td><td><br /><?php echo $row['SN'];?></td></tr></div><?php } ?> <?php if (!empty($row['INV'])) { ?><div id="INV"><tr><td><span class="b">INV: </span></td><td><br /><?php echo $row['INV'];?></td></tr></div><?php } ?> </div> </div> <div id="box4"> <?php if (empty($row['ncmrsr']) && empty($row['ncmrsc'])) { ?> <div id="ncmrsr"><tr><td><span class="b">NCMR Supplier Response:<br /></span></td><textarea name="ncmrsr" rows="6" cols="85" ></textarea></tr></div><br /> <div id="ncmrsc"><tr><td><span class="b">NCMR Supplier Comment:<br /></span></td><textarea name="ncmrsr" rows="6" cols="85" ></textarea></tr></div><br /> <?php } else { ?> <?php if (!empty($row['ncmrsr'])) { ?><div id="ncmrsr"><tr><td><span class="b">NCMR Supplier Response: </span></td><td><?php echo $row['ncmrsr']; ?></td></tr></div><?php } ?> <?php if (!empty($row['ncmrsc'])) { ?><div id="ncmrsc"><tr><td><span class="b">NCMR Supplier Comment: </span></td><td><?php echo $row['ncmrsc']; ?></td></tr></div><?php } ?> <?php } ?> </div> </div> </div> </fieldset> </form> <?php } //!$row ?> </body> </html>
  14. You can do the whole thing in one file. I prefer to actually. You do not have to wrap all the html in PHP echo statements though. If you have big chunks of html the easiest thing to do is just exit php mode and put the html. Re-enter php mode as necessary. Put all your main processing code at the top of the page: <?php if (count($_POST) > 0){ //process the form here } ?> <html> <head></head> <body> <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <p>Name: <input type="text" name="name" value="<?php echo isset($_POST['name'])?$_POST['name']:''; ?>"></p> </form> </body> </html>
  15. Do you watch the output of the PHP server script while testing? Can you see it output a message when the connection is accepted and when data is received? I see your binding to localhost, note that Wireshark will not capture packets going across localhost without some hacks. It'd be easier to probably rely on output from the server script, or setup the server on a different host so your connecting via LAN/Internet and wireshark can see the packets.
  16. I'd say the clause "redistribute the source code." is probably just from someone using a generic license intended to be used with compiled software. In terms of non compiled software such as JS, the intent would probably be more along the lines of you can use it, but you can't offer up the JS code alone, such as say in a "free scripts" type of site. Only the author could really give you a definite answer as to what they intend though. Only an attorney could tell you what your legally allowed to do with the stated license terms.
  17. Without seeing the code behind it, can't really say much about why you see what you do. If you php script doesn't hold the socket open, probably it's being closed before the handshake can be sent. Such as if your doing like $client = socket_accept($server); socket_close($client); //or just ending script the socket will open then close immediately, without giving a chance for anything to be sent.
  18. I take it that means there is HTML above this block of PHP code? You can't call session_start after you have sent output (which includes anything, even blank space) which is outside of <?php ?> tags. Reason is session-start() has to send headers for the cookie, and sending output causes the headers to be sent which means you can't send any new headers after that point. You need to move your processing code to be at the top of the script, before any other output. see also, the sticky on header errors
  19. Your error is not because your calling nameGen from within nameGen. That is perfectly legal (but you need to be careful not to cause an endless loop). Your problem is because your declaring the function nameGen inside of a for loop, so on the first iteration of that loop it declares the function. On the second iteration it attempts to declare it again, but it's already been declared so you receive that error. Move the function declaration out of the for loop, then just call it from inside the loop.
  20. Do one query that returns the data you need, then group it in php for display. ex a query like select * from customers inner join orders on customers.customerNumber=orders.customerNumber order by customers.customerNumber then process it like: $customers=array(); while ($row=/*fetch row*/){ $custNo = $row['customerNumber']; if (!isset($customers[$custNo])){ $customers[$custNo]=array( 'name' => $row['customerName'], /* .. other customer info fields */ 'orders' => array() ); } $customers[$custNo]['orders'][] = $row; } print_r($customers);
  21. Don't know if they are using this, but this is how one would change the url without reloading the page: MDN: Manipulating the browser history
  22. You want: $qry = "SELECT LAST_INSERT_ID() as newId"; $res = mysql_query($qry); $row = mysql_fetch_assoc($res); //now $row['newId'] holds your value
  23. Assuming your server is properly configured to execute PHP files (rather than serve them as is), none of your actual PHP code (including PHP comments) will be visible to the end user.
  24. You can try doing a HEAD request with get_headers() and then find the Content-Length: header. If that fails you can fall back to a file_get_contents/strlen() combo to get the size.
  25. Not quite like what you'd get in say PHP or another language, but they are closer than anything else one could do with just Javascript. I'm not sure what kind of abilities Flash has for sockets, never used it. Websockets need a special type of server to listen but there are projects out there that you can use to 'websock-ify' a protocol so that you can connect to it via a websocket through a proxy program.
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.