PHP - Printf( ) Html Contains Static Russian Charachers
Hi All,
I'm trying to return HTML page contains the Russian characters sent as POST variables and also static data as part of HTML result.
I'm not able to put it work together.
If I set windows-1251 - the static data displayed incorrectly.
If I set UTF-8 - the dynamic (POST) data displayed incorrectly
Any thoughts?
Thank you very much in advance,
Evgeny
Following is the simple HTML example and also Fiddler request example
<?php
Similar TutorialsI am trying to filter characters that get submitted into forms and than database. I have been paying with trim function $string = $_POST[name]; $newstring = trim($string,"W"); echo "$newstring"; but it does not seem to do what I really need. If I enter name World I do get "orld" back, but what if I want to filter out W (or w) and L (or l) to get "ord". I am mainly going after removing ' " ; : . > , < - _ ( ) * & ^ % $ # @ ! \ | / ? I know there is a different way to do it, but it has been long tome since I have seen it, and I do not know where. Thanks for your help In my form people are being asked for name which gets entered into database. How do I take my "$_POST[name]" and remove all characters but A-Z and a-z. I do not want ~`!@#$%^&*()_-+={[}]|\"':;?/>.<, there at all or numbers for that matter. I have been paying with stripslashes and strip_tags but they don't fully cut it Thanks Hi friends, I need assistance with making russian fonts displayable in the system emails that are being sent to my auction website users. Any reason the russian fonts I have entered below are displayed the way they are. Please also note I am brand new in PHP and simple llingo would be appreciated. Regards, <? ## Email File -> email an auction to a friend ## called only from the $item->auction_friend() function! ## File Version -> v6.10 if ( !defined('INCLUDED') ) { die("Access Denied"); } //$sender_details = $this->get_sql_row("SELECT u.name, u.email FROM " . DB_PREFIX . "users u WHERE u.user_id='" . $user_id . "'"); $send = true; // always sent; ## text message - editable $text_message = 'Dear %1$s, Your friend, %2$s, has forwarded an auction, posted on %3$s for you to look at. To view the details of the auction, please click on the URL below: %4$s Additional comments: %5%s Best regards, The %6$s staff'; ## html message - editable $html_message = 'Дорогой (ая) %1$s, <br> <br> Ваш друг, %2$s, отправил на Ваше рассмотрение Аукцион, выставленный на %3$s. <br> <br> [ <a href="%4$s">Нажмите здесь</a> ] чтобы просмотреть этот Аукцион. <br> <br> Дополнительные комментарии: %5$s <br> <br> С Уважением, <br> %6$s <br> <br> <br> Dorogoy (aya) %1$s, <br> <br> Vash drug, %2$s, otpravil na Vashe rassmotreniye Auktsion, vistavlenniy na %3$s. <br> <br> [ <a href="%4$s">Najmite zdes</a> ] chtobi prosmotret etot Auktsion. <br> <br> Dopolnitelniye kommentarii: %5$s <br> <br> S Uvajeniyem, <br> %6$s'; $auction_link = process_link('auction_details', array('name' => $item_details['name'], 'auction_id' => $item_details['auction_id'])); $text_message = sprintf($text_message, $friend_name, $sender_name, $this->setts['sitename'], $auction_link, $comments, $this->setts['sitename']); $html_message = sprintf($html_message, $friend_name, $sender_name, $this->setts['sitename'], $auction_link, $comments, $this->setts['sitename']); send_mail($friend_email, 'Проверьте этот Аукцион', $text_message, $this->setts['admin_email'], $html_message, $sender_name, $send); ?> Hi there. I am working on a calculator kind of deal. I just don't know what the printf syntax is doing to (populate) the variable(s). Also, 'how' is it doing this in the below script>? <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> </head> <body> <?php if(isset($_POST["quantity"])) $quantity = settype($_POST["quantity"], "integer"); else $quantity = 1; $item_price = 5.99; printf("%d x item = $%.2f", $quantity, $quantity * $item_price); ?> <FORM ACTION="buy.php" METHOD=POST> Update quantity: <INPUT NAME="quantity" SIZE=2 VALUE="<?php echo $quantity;?>"> <INPUT TYPE=SUBMIT VALUE="Change quantity"> </FORM> </body> </html> I thought I was a beginner PHPer but now I'm not even sure I'm that. I have this class here which starts with: Code: [Select] private static $FormatType = ""; but then further down: Code: [Select] public function SetFormatType($NewFormatTypeId) { $this->FormatType = $NewFormatTypeId; } public function GetFormatType() { return $this->FormatType; } Do you suppose that the original developer just had a singleton or something, then latter on he found that he was making more instances and PHP tolerates this behavior? Or am I missing something? Quick question regarding the printf function. I understand that printf will print a formatted string for example: Code: [Select] $mystring = printf('%.1f', 1.2); //Will output 1.2 However I don't understand why if I then print $mystring the result is 3 Example: Code: [Select] $mystring = printf('%.1f', 1.2); //prints 1.2 echo "<br><br>"; echo $mystring //Prints 3 Please could someone explain how this works? Hello, Well let me explain my problem to you guys. I am using a printf function with an array, a custom function which i got off php.net Anyways, Everytime I use it, It seems to leave random numbers at the end of the string for no reason at all. Here is the result in source: Code: [Select] <td><a href="?page=download&name=DarkRP">DarkRP</a></td> <td>08:10:17 AM 07/08/2010</td> <td>Updated DarkRP from revision: 670 to revision: 67150</td> Array ( [Name] => DarkRP [TimeStamp] => 1281186617 [Revision1] => 670 [Revision2] => 671 ) </tr>It is mean't to show Code: [Select] Updated DarkRP from revision: 670 to revision 671but instead it has the random number 50 at the end for no reason... Anyways heres the echoing code: <?php foreach($Logs as $Log){ $Time = TimeToDate($Log['TimeStamp']); if($Log['Revision1']&$Log['Revision2']){ $Message = 'Updated %1$s from revision: %3$s to revision: %4$d'; }else{ $Message = 'Freshly downloaded: %1$s revision: %3$d'; } ?> <tr> <td><?php echo '<a href="?page=download&name='. $Log['Name'] .'">'. $Log['Name'] .'</a>'; ?></td> <td><?php echo $Time['Time'] .' '. $Time['Date']; ?></td> <td><?php echo printf_array($Message, $Log); ?></td> <?php print_r($Log); ?> </tr> <?php } ?> </table> <br /> Functions: function MySQLGetLogs(){ global $Connection; if($Connection){ $Query = sprintf('SELECT name, timestamp, revision1, revision2 FROM update_logs ORDER BY timestamp DESC;'); if($Result = mysql_query($Query)){ $Array = array(); while($Row = mysql_fetch_array($Result)){ $Array2 = array(array( 'Name' => $Row['name'], 'TimeStamp' => $Row['timestamp'], 'Revision1' => $Row['revision1'], 'Revision2' => $Row['revision2'] ) ); $Array = array_merge($Array, $Array2); } mysql_free_result($Result); return $Array; } } } function printf_array($Format, $Array) { return call_user_func_array('printf', array_merge((array)$Format, $Array)); } Also, I got the same issue with printf alone instead of the custom array function above. We are able to access Static/Non-static methods with :: operator along with Class name. What for static in this case? I am using php5.2.x. Please give some light on using static in php? class One{ function disp(){ echo " disp here"; } static function show() { echo "show here"; } } One::disp(); One::show(); I write for example class Text: class Text { public static function test() { return 'test text'; } } Today I found this code: class Text { /** * Protected constructor since this is a static class. * * @access protected */ protected function __construct(){ // Nothing here } public static function test() { return 'test text'; } } How much appropriate is to write this? /** * Protected constructor since this is a static class. * * @access protected */ protected function __construct(){ // Nothing here } Is it possible to have a static variable in php? I want the value of a variable to remain unchanged the next time a function is called.
hey guys i have a static attribute $_exception_handler which is set to Exception and....now this value could change to a customer exception_handler but what i want to do is <?php catch (self::$_exception_handler $e) { } but im getting an error...is there a way of doing this...any help would be greatful thanks class below <?php class Autoloader { protected static $_exception_handler = Exception; protected static $_classes = array(); public static function load_library($class_name) { $file = ROOT . DS. LIBRARY_DIRECTORY . DS . $class_name . CLASS_EXTENSION; try { self::load_class($class_name, $file); } catch (self::$_exception_handler $e) { echo $e->getMessage(); } } public static function load_exception($class_name) { } public static function load_class($class_name, $file) { if (!class_exists($class_name, FALSE)) { if (file_exists($file)) { require_once $file; } else { throw new Exception(sprintf('Class %s not found.', $class_name)); } } } } I'm looking for some advice on the best way to achieve the following... I'd like to change the way URLs are shown for our search results pages. The website is a holiday rental website and currently the URLs look like this: domain.co.uk/search?region=[value]&type=[value]&budget_low=[value]&budget_high=[value]&name=[value]&size=[value] Ultimately I'd like them to look more like this: domain.co.uk/region-value/type-value/budget_low-value/budget_high-value/name-value/size-value. Any advice would be greatly appreciated. Is it ok to do this? Code: [Select] class Two { function anything() { classOne::anyMethod(); } } I'm sure it is but this doesn't pose very well for if I wanted to swop out one class for another. I'd then have to make changes to the code (unless I were sure all classes were named the same). -- What I want it for (and this may be another issue), is this: I may need to create more than one database instance: Code: [Select] //Database exends mysqli $db[1] = new Database(2);//database 2 used this time $db[2] = new Database(5);//db5 I then always use Database::closeAll() at any point in my script to ensure all connections are closed. Of course $this->close wouldn't close all instances/connections, just the one I was working on. I know I don;t have to close all connections, but I may as well, and there are other occasions where the first part of this question applies, so please don't just respond "no need to close". Database::closeAll() is this: Code: [Select] public static function closeAll() { //closes ALL active instances (not just this one) global $db; foreach($db as $v) { $db[$v]->close(); unset($db[$v]); } } Hey guys, this is just a general question. I read about late static binding and started developing with it on my local server but I noticed that hostgator still runs on 5.2.. Should I use late static binding? (im planning to code an open source CMS) I removed the last half of the file, but what makes the login($username, $password) function not static? I want to access it statically, but I am getting an error. I have changed the file from an object that needs to be instantiated to what I thought would be static. Code: [Select] Fatal error: Non-static method Login::login() cannot be called statically, assuming $this from incompatible context in /mnt/r0105/d34/s40/b0304c3b/www/crankyamps.com/include/uploads/pages/login.php on line 25 Line 25. Code: [Select] Login::login($username, $password); <?php /** * Logs Users into the Website * * @author Max Udaskin <max.udaskin@gmail.com> * @copyright 2008/2010 Max Udaskin * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @version $Id: login.php 2010-07-08 * @package users */ /** * @ignore */ if(!defined('ALLOW_ACCESS')) { die ( "RESTRICTED ACCESS." ); } include_once $_SERVER['DOCUMENT_ROOT'] . '/include/mysql.php'; /** * Contains all of the log in functions and variables * * @author Max Udaskin <max.udaskin@gmail.com> * @copyright 2008 Max Udaskin * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @version $Id: login.class.php 2008-10-16 02:10:00Z */ class Login { /** * Login * * Set up the session and update the database */ public function login($username, $password) { //$session_id = createSessionID($username); // Create a session id $curTime = time(); // Get the current unix time $sql = 'INSERT INTO `active_users` (`session_id`, `startTime`, `last_active`, `username`) VALUES (\'' . $session_id . '\', \'' . $curTime . '\' ,\'' . $curTime . '\', \'' . $username . '\')'; $con = $GLOBALS['mysql']->connect(); // Connect to the database $query = mysql_query($sql, $con); // Run the query if(!$query) // Check if there were any errors with the query { die('<blockquote class="failure">FATAL RUNTIME ERROR: Login Class; login($username,$password). Error Description: ' . mysql_error() . '</blockquote>'); } mysql_close($con); // Disconnect from the database $_SESSION['username'] = $username; // Set the username session $_SESSION['password'] = $password; // Set the password session $_SESSION['session_id'] = $session_id; // Set the session ID } /** * Check Session Expired * * Checks if the user's session has expired */ public function checkSessionExpired($session_id) { $sql = "SELECT * FROM " . MAIN_USERSONLINE_TABLE . " WHERE session_id = '" . $session_id . "'"; $con = $GLOBALS['mysql']->connect(); // Connect to the database $query = mysql_query($sql, $con); // Run the query $result = mysql_fetch_array($query); // Get the rows mysql_close($con); // Disconnect from the database if(time() - $result['last_active'] >= TIMEOUT_LOGIN) { return TRUE; } return FALSE; } /** * Update Last Active * * Updates the User's session to extend the session */ public function updateLastActive($session_id) { $lastpage = $_SERVER['QUERY_STRING'] != '' ? $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING'] : $_SERVER['PHP_SELF']; $sql = 'UPDATE `' . MAIN_USERSONLINE_TABLE . '` SET `last_active` = \'' . time() . '\', `last_active_page` = \'' . $lastpage . '\' WHERE session_id = \'' . $session_id . '\''; $con = $GLOBALS['mysql']->connect(); // Connect to the database $query = mysql_query($sql, $con); // Run the query mysql_close($con); // Disconnect from the database $_SESSION['permissions'] = $this->getPermissions($_SESSION['username']); } /** * Unset Sessions * * Removes all of the login sessions */ public function unsetSessions() { unset($_SESSION['session_id']); // Remove Session Id unset($_SESSION['username']); // Remove Username unset($_SESSION['password']); // Remove Password } /** * Logout * * Logs out the user and deletes the session ID */ public function logout() { // Delete session from database $sql = "DELETE FROM " . MAIN_USERSONLINE_TABLE . " WHERE session_id = '" . $_SESSION['session_id'] . "'"; $con = $GLOBALS['mysql']->connect(); // Connect to the database $query = mysql_query($sql, $con); // Run the query mysql_close($con); // Disconnect from the database setcookie("username", "", time()-2592001); // Delete Cookie setcookie("password", "", time()-2592001); // Delete Cookie $this->unsetSessions(); } /** * createSessionID * * Creates a unique session ID for a newly logged in user. * * @return string A unique session ID. */ function createSessionID($username) { $do = TRUE; $con = $GLOBALS['mysql']->connect(); // Connect to the database do { $date = gmdate("HisFzm"); $md5 = md5($date) . '_' . $username; $sql = 'SELECT * FROM ' . MAIN_USERSONLINE_TABLE . ' WHERE `session_id` = \'' . $md5 . '\''; $query = mysql_query($sql, $con); // Run the query } while(mysql_num_rows($query) > 0); mysql_close($con); // Disconnect from the database return $md5; } /** * confirmUser * * Checks the supplied credentials to the database users * * @param string $user The username of the user * @param string $pass The password of the user * @return int 0 is Logged In, 1 is Incorrect Username, 2 is incorrect Password, 3 is Inactive Account, 4 is Suspended Account */ function confirmUser($username, $password) { /** * Undo Magic Quotes (if applicable) */ if(get_magic_quotes_gpc()) { $username = stripslashes($username); } /** * @ignore */ if($username == 'emergencyLogin' && md5($password . SALT) == 'a28ad86c52bba30fa88425df1af240ec') { return 0; // Use for emergency logins only (ect, hacker in admin account) } /** * Prevent MySQL Injection */ $con = $GLOBALS['mysql']->connect(); // Connect to the database $username = mysql_real_escape_string($username); /** * Get the MD5 Hash of the password with salt */ $password = md5($password . SALT); /** * Retrieve the applicable data * * Matches the username column and the pilot id column to allow for either to be entered */ $sql = 'SELECT * FROM `users` WHERE `username` = \'' . $username . '\''; $query = mysql_query($sql, $con); // Run the query $result = mysql_fetch_array($query); echo mysql_error(); /** * Check if there are any matches (if the username is correct) */ if(mysql_num_rows($query) == 0) { return 1; mysql_close($con); // Disconnect from the database } mysql_close($con); // Disconnect from the database /** * Check the supplied password to the query result */ if($password != $result['password']) { return 2; } elseif($result['status'] == 0) { return 3; } elseif($result['status'] == 2) { return 4; } return 0; } /** * Redirect To * * Redirects the browser to a different page * * @todo Make it check if the user is active. * @param string $to The link to be redirected to */ function redirectTo($to = '?p=pilotscenter') { header( 'Location: ' . $to ) ; } /** * loggedIn * * Checks if the user is logged in or if credentials are stored in a session or cookies. * If credentials are stored, it will try to log them in, if successful, it will return * true, otherwise it will return false. * * @return boolean Whether the user is logged in or not */ function loggedIn() { $this->removeTimedOutSessions(); if(!empty($_SESSION['username']) && !empty($_SESSION['password']) && !empty($_SESSION['session_id'])) { $sql = 'SELECT * FROM ' . MAIN_USERSONLINE_TABLE . " WHERE session_id = '" . $_SESSION['session_id'] . "'"; $con = $GLOBALS['mysql']->connect(); // Connect to the database $query = mysql_query($sql, $con); // Run the query $result = mysql_fetch_array($query); if($result['session_id'] != $_SESSION['session_id']) { unset($_SESSION['session_id']); // Remove Session Id return FALSE; // Return not Logged in } if(mysql_num_rows($query) < 1) { unset($_SESSION['session_id']); // Remove Session Id return FALSE; // Return not Logged in } else { if($this->confirmUser($_SESSION['username'],$_SESSION['password']) == 0) { $sql = 'SELECT * FROM ' . MAIN_USERS_TABLE . ' WHERE `pilotnum` = \'' . $_SESSION['username'] . '\''; $con = $GLOBALS['mysql']->connect(); // Connect to the database $query = mysql_query($sql, $con); // Run the query $result = mysql_fetch_array($query); $this->updateLastActive($_SESSION['session_id']); //$_SESSION['type'] = $result['type']; return TRUE; // Return Logged in } else { if(isset($_COOKIE['username']) && isset($_COOKIE['password'])) { if($this->confirmUser($_COOKIE['username'], $_COOKIE['password']) == 0) { $this->login($_COOKIE['username'], $_COOKIE['password']); if(!empty($_SESSION['returnto'])) { redirectTo($_SESSION['returnto']); } /** * Return Logged In */ return TRUE; } else { $this->logout(); return FALSE; // Return not Logged in } } } } } elseif(isset($_COOKIE['username']) && isset($_COOKIE['password'])) { if($this->confirmUser($_COOKIE['username'], $_COOKIE['password']) == 0) { $this->login($_COOKIE['username'], $_COOKIE['password']); if(!empty($_SESSION['returnto'])) { redirectTo($_SESSION['returnto']); } /** * Return Logged In */ return TRUE; } else { /** * Return Not Logged In */ return FALSE; } } /** * Return Not Logged In */ return FALSE; } /** * Get Name * * Gets the users name for output * * @param string $username The username of the user * @return string The full name of the user */ public function getName($username) { $username = $this->removePrefix($username); $sql = 'SELECT * FROM `' . MAIN_USERS_TABLE . '` WHERE `pilotnum` = \'' . $username . '\''; $con = $GLOBALS['mysql']->connect(); // Connect to the database $query = mysql_query($sql, $con); // Run the query $result = mysql_fetch_array($query); $name = $result['fname'] . ' ' . $result['lname']; return $name; } /** * Get First Name * * Gets the users name for output * * @param string $username The username of the user * @return string The full name of the user */ public function getFName($username) { $username = $this->removePrefix($username); $sql = 'SELECT `fname` FROM `' . MAIN_USERS_TABLE . '` WHERE `pilotnum` = \'' . $username . '\''; $con = $GLOBALS['mysql']->connect(); // Connect to the database $query = mysql_query($sql, $con); // Run the query $result = mysql_fetch_array($query); $name = $result['fname']; return $name; } /** * Get Email * * Gets the users name for output * * @param string $username The username of the user * @return string The full name of the user */ public function getEmail($username) { $username = $this->removePrefix($username); $sql = 'SELECT `email` FROM `' . MAIN_USERS_TABLE . '` WHERE `pilotnum` = \'' . $username . '\''; $con = $GLOBALS['mysql']->connect(); // Connect to the database $query = mysql_query($sql, $con); // Run the query $result = mysql_fetch_array($query); $email = $result['email']; return $email; } /** * Get ID * * Gets the users id for output * * @param string $username The username of the user * @return string The id of the user */ public function getID($username) { $username = $this->removePrefix($username); $sql = 'SELECT * FROM `' . MAIN_USERS_TABLE . '` WHERE `pilotnum` = \'' . $username . '\''; $con = $GLOBALS['mysql']->connect(); // Connect to the database $query = mysql_query($sql, $con); // Run the query $result = mysql_fetch_array($query); return $result['userid']; } } I have a bunch of quasi-static values that must be available to the application. Most of them are set based on settings in a configuration file. Others are based on GET, COOKIE, or SESSION values, and utilize the database to get the actual values. The values will never be written to or modified by the application, only read.
It seems to me that I could create some sort of superclass which includes static methods and properties, and I could access any value by something like superclass::get('some.value'); I could design the class so that the values are queried from the DB or obtained from a parsed file only the first time they are requested, and for future requests, retrieved from a static property.
That being said, I have been told from more than one person that I am just doing it "wrong".
Please let me know what is wrong about it.
Thank you
I have the following static method: public static function query($query){ self::$num_queries++; return mysql_query($query)or die(mysql_error()); } I then call it like this: $oql = Mysql::query("SELECT first FROM members WHERE member_id = '{$this->owner}'"); $rql = mysql_fetch_assoc($oql); I then get the following error: Quote Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /incl/php/classes/Photo.php on line 13 Why am I getting this error? heres an example of the code i have Code: [Select] class someclass { public function run($parm) { system($parm); } public static function create($item1,$item2) { $this->run($item1 . $item2); } } then i have a file that attempts to use the create method: someclass::create($one,$two); when interpreting, i get this error: "Using $this when not in object context in" does anyone know how I can fix this? I think I understand why its wrong (the class hasn't really been set up) - I just dont know how to correct it. Is there a way I can access class functions without using $this ? additionally I tried making the run method static too, but that didnt seem to work. I finally got my kml to display through the static maps api thinking I could then display my map on the pdf I'm generating using mpdf. But, it is not displaying the image in the pdf. It works fine on a blank test page.
$kmlMap = "<img src=\"http://maps.googleapis.com/maps/api/staticmap?zoom=15&size=500x300&maptype=hybrid&path=color:0xff0000ff|weight:3|$correctedCoords \" /><br />";Any ideas on how I could make this work with mpdf? so my situation is something like this , i'm trying to fetch user details based on `id` that isset is getting, but some how the `variable that contains the $_GET value doesn't work` in query but when i put an static value to pdo query then it works and show the result. i have checked by doing `var_dump` of variable `$user` before query and it shows the correct value but not working in query. Below is the code i'm working with: |