Register for your free account! | Forgot your password?

Go Back   elitepvpers > Coders Den > Coding Releases > Coding Snippets
You last visited: Today at 07:11

  • Please register to post and access all features, it's quick, easy and FREE!

Advertisement



[Collection/Sammelthread] Code-Snippets / Code-Schnipsel

Discussion on [Collection/Sammelthread] Code-Snippets / Code-Schnipsel within the Coding Snippets forum part of the Coding Releases category.

Closed Thread
 
Old   #1


 
MrSm!th's Avatar
 
elite*gold: 7110
Join Date: Jun 2009
Posts: 28,902
Received Thanks: 25,407
[Collection/Sammelthread] Code-Snippets / Code-Schnipsel

English:

Hello community,
since more and more code snippets are getting posted, we decided to open this thread. Please post them here from now on. If you feel your release might be too complex for this collection and needs an own thread, please contact a moderator first.

Please use this thread for code snippets only! There is a thanks button for saying thanks to helpful users. You may post constructive criticism or corrections though.

Your Coders Den staff

Deutsch:

Hallo Community,
da sich die Threads für kleinere Code-Ausschnitte in letzter Zeit gehäuft haben, haben wir entschlossen diesen Thread zu öffnen. Bitte postet Code-Schnipsel von nun an hier. Falls ihr denkt, dass euer Release zu komplex für diesen Thread ist und einen eigenen benötigt, kontaktiert bitte zuerst einen Moderator.

Bitte nutzt diesen Thread auschließlich für Code-Schnipsel! Es gibt einen Thanks-Button, um euch für sinnvolle Beiträge zu bedanken. Ihr dürft allerdings konstruktive Kritik und Korrekturen posten.

Euer Coders Den Staff
MrSm!th is offline  
Thanks
7 Users
Old 10/21/2013, 23:36   #2



 
Shawak's Avatar
 
elite*gold: 0
The Black Market: 259/0/0
Join Date: Apr 2010
Posts: 10,289
Received Thanks: 3,613
Dann fange ich mal mit etwas Kleinem an, hier eine Funktion um Bytes zu einem String in KB/MB/GB etc zu konvertieren.

Code:
        public string SizeString(long bytes)
        {
            string[] format = {"Bytes", "KB", "MB", "GB", "TB", "PB", "EB"};
            int i = 0;
            for (i = 0; i < format.Length && bytes >= 1024; i++)
                bytes = (100 * bytes / 1024) / 100;
            return string.Format("{0:F2} " + format[i], bytes);
        }
Shawak is offline  
Thanks
1 User
Old 10/21/2013, 23:59   #3

 
snow's Avatar
 
elite*gold: 724
Join Date: Mar 2011
Posts: 10,479
Received Thanks: 3,318
Dann auch mal direkt was von mir.
Das ganze war nur zur Übung, wenn ihr so was ernsthaft nutzen wollt, solltet ihr Master674b's Code nehmen ()

Das ganze ist ein kleiner EventHandler, mit dem Funktionen registriert werden können und anschließend aufgerufen werden können. War mal als Klasse für ein GUI-Framework gedacht.
Die Klasse lässt sich wie ein Container verwenden (for (auto& function : eventHandler) { function(arg0, arg1) } z.B.), ansonsten sollte der Code relativ selbsterklärend sein.

Code:
template <typename F>
class EventHandler;

template<typename F, typename ...Args>
class EventHandler<F(Args...)>
{
	typedef F (*Func)(Args...);
	std::vector<Func> functions;
public:
	void connect(Func f)
	{
		if (std::find(functions.begin(), functions.end(), f) == functions.end())
			functions.push_back(f);
	}
    
	void disconnect(Func f)
	{
		auto it = std::find(functions.begin(), functions.end(), f);
		if (it != functions.end())
		{
			functions.erase(it);
		}
	}
    
	EventHandler() { };
	EventHandler(const EventHandler& listener) : functions(listener.functions) { };
    
	F operator()(Args... args)
	{
		auto maxIndex = functions.size() - 1;
		if (functions.size() > 1)
		{
			for (size_t i = 0; i != maxIndex; ++i)
			{
				(functions[i])(args...);
			}
		}
		return functions[maxIndex](args...);
	}
    
	void clear()
	{
		functions.clear();
	}
    
	bool empty() const
	{
		return functions.empty();
	}
    
	auto size() const -> decltype(functions.size())
	{
		return functions.size();
	}
    
	auto begin() const -> decltype(functions.begin())
 	{
		return functions.begin();
	}
    
	auto end() const -> decltype(functions.end())
	{
		return functions.begin();
	}
    
	EventHandler operator+(Func f)
	{
		EventHandler copy(*this);
		copy += f;
		return copy;
	}
    
	EventHandler& operator+=(Func f)
	{
		connect(f);
		return *this;
	}
    
	EventHandler operator-(Func f)
	{
		EventHandler copy(*this);
		copy -= f;
		return copy;
	}
    
	EventHandler& operator-=(Func f)
	{
		disconnect(f);
		return *this;
	}
};
Verwendung:

Code:
    
   auto lambdaEventHandler = [](int i, int j) -> int { return 2 * j + i; };
    
    EventHandler<int(int, int)> handler;
    handler += someFunctionAddress;
    handler += lambdaEventHandler;
    
    std::cout << handler(3, 4) << std::endl; // output = 11
die zuletzt hinzugefügte Funktion liefert am Ende den return-Wert.

Verwendung als EventHandler für GUI-Events:

Code:
   
Button b("buttonTitle");
b += [](const Element& element, EventInformation information) { std::cout << "Click!" << std::endl; };

// in our message loop
WORD reason = 0x1337;
b.ButtonEvent(reason); // calls eventHandler(*this, EventInformation());
Feedback gerne gesehen, wie gesagt, war nur ein schnelles Projekt.
Verwendung komplett erlaubt usw., alles cool.
snow is offline  
Thanks
1 User
Old 10/22/2013, 10:49   #4



 
Sedrika's Avatar
 
elite*gold: 18
The Black Market: 103/0/0
Join Date: Sep 2009
Posts: 20,174
Received Thanks: 14,475
Hier eine kleine Funktion um nach vorkommen zwischen zwei Text Bereichen zu suchen.
Code:
        public static String[] GetSubstring(string strBegin, string strEnd, string strSource, bool includeBegin, bool includeEnd)
        {
            string[] result = { "", "" };
            int iIndexOfBegin = strSource.IndexOf(strBegin);
            if (iIndexOfBegin != -1)
            {
                if (includeBegin)
                    iIndexOfBegin -= strBegin.Length;
                strSource = strSource.Substring(iIndexOfBegin + strBegin.Length);
                int iEnd = strSource.IndexOf(strEnd);
                if (iEnd != -1)
                {
                    if (includeEnd)
                        iEnd += strEnd.Length;
                    result[0] = strSource.Substring(0, iEnd);
                    if (iEnd + strEnd.Length < strSource.Length)
                        result[1] = strSource.Substring(iEnd + strEnd.Length);
                }
            }
            else
                result[1] = strSource;
            return result;
        }
Sedrika is offline  
Old 10/22/2013, 15:29   #5
 
XxharCs's Avatar
 
elite*gold: 34
Join Date: Apr 2011
Posts: 1,475
Received Thanks: 1,228
Eine Funktion die Überprüft ob das Programm als Administrator ausgeführt wurde.

Code:
BOOL IsAdministrator(VOID)
{
    SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
    PSID AdministratorsGroup;

    if( !AllocateAndInitializeSid(&NtAuthority,2,SECURITY_BUILTIN_DOMAIN_RID,
        DOMAIN_ALIAS_RID_ADMINS,0, 0, 0, 0, 0, 0,&AdministratorsGroup))
    {
        return FALSE;
    }

    BOOL IsInAdminGroup = FALSE;

    if(!CheckTokenMembership(NULL,AdministratorsGroup,&IsInAdminGroup))
    {
       IsInAdminGroup = FALSE;
    }

    FreeSid(AdministratorsGroup);
    return IsInAdminGroup;
}
Mögliche Verwendung:
Code:
if(IsAdministrator()==FALSE)
{
	MessageBoxA(0, "Please start it as admin !", "Error", MB_ICONERROR);
	return 1;
}
XxharCs is offline  
Thanks
4 Users
Old 10/25/2013, 21:54   #6

 
snow's Avatar
 
elite*gold: 724
Join Date: Mar 2011
Posts: 10,479
Received Thanks: 3,318
Ich hab mich mal an eine Datenbankabfrage für einen Login gewagt.
Basiert auf MySQLi, durch das prepared Statement sollte man sicherer vor irgendwelchen Injections sein, escapen ist somit nicht nötig, kann man natürlich trotzdem machen.
Keine Fehlerbehandlung, kein Auffangen von Fehlern, habe ich hier entfernt da das bei mir zu projektspezifisch ist.
durch $_REQUEST kann sowohl mit GET als auch mit POST gearbeitet werden.

Verwendung wie immer ohne Garantie und was weiß ich, dafür gibts aber auch kein Copyright.
Falls was grob falsch ist: Bitte Bescheid geben, das ist mein erster eigener PHP-Code.

Code:
<?php

	if (!isset($_REQUEST['user']) || !isset($_REQUEST['password']))
	{
		echo "error";
		return;
	}

	// init
	$user = $_REQUEST['user'];
	$password = $_REQUEST['password'];
	$sqlConnection = new mysqli("localhost", "root", "password", "database");
	
	// prepare + execute statement
	$statement = $sqlConnection->prepare("SELECT * FROM table WHERE username = ? AND password = ? LIMIT 1");
	$statement->bind_param('ss', $user, $password);
	$statement->execute();
	
	// get the result
	$result = $statement->get_result();
	$row = $result->fetch_assoc();
	$output = $row['column'];
	
	// clean up
	$statement->close();
	$sqlConnection->close();

	echo $output;
?>
snow is offline  
Old 10/26/2013, 21:27   #7
 
XxharCs's Avatar
 
elite*gold: 34
Join Date: Apr 2011
Posts: 1,475
Received Thanks: 1,228
Eine Funktion die einen Tastendruck simuliert. Dabei wird MapVirtualKey, INPUT,KEYBDINPUT und SendInput verwendet.

Code:
void sendKey(int vk, BOOL bExtended) {

	KEYBDINPUT  kb = {0};
	INPUT       Input = {0};
	int scan = MapVirtualKey(vk, 0);

	/* Generate a "key down" */
	if (bExtended) { kb.dwFlags  = KEYEVENTF_EXTENDEDKEY; }
	kb.wVk  = vk;
	Input.type  = INPUT_KEYBOARD;
	Input.ki  = kb;
	Input.ki.wScan = scan;
	SendInput(1, &Input, sizeof(Input));

	/* Generate a "key up" */
	ZeroMemory(&kb, sizeof(KEYBDINPUT));
	ZeroMemory(&Input, sizeof(INPUT));
	kb.dwFlags  =  KEYEVENTF_KEYUP;
	if (bExtended) { kb.dwFlags |= KEYEVENTF_EXTENDEDKEY; }
	kb.wVk = vk;
	Input.type = INPUT_KEYBOARD;
	Input.ki = kb;
	Input.ki.wScan = scan;
	SendInput(1, &Input, sizeof(Input));

	return;
}
XxharCs is offline  
Old 10/28/2013, 02:47   #8
 
Che's Avatar
 
elite*gold: 120
Join Date: Aug 2010
Posts: 7,448
Received Thanks: 2,756
Code:
array_walk($_GET, create_function('&$value', 'return $value=htmlspecialchars(mysql_escape_string($value));'));
array_walk($_POST, create_function('&$value', 'return $value=htmlspecialchars(mysql_escape_string($value));'));
Nettes Snippet um PHP Scripte allgemein deutlich sicherer zu machen. Im Grunde genommen nimmt man so (sofern geschickt im Haupt-Script eingebaut) ganz bequem jeglichen Nutzern sämtliche Möglichkeiten XSS- oder SQLi-Attacken durchzuführen.
Che is offline  
Old 10/29/2013, 22:24   #9
 
​Tension's Avatar
 
elite*gold: 110
Join Date: Jun 2013
Posts: 599
Received Thanks: 510
Da ich so eine Funktion gerade brauche und sie nicht im Netz gefunden habe, habe ich mir eine selbst geschrieben.
Was sie macht: Sucht nach einem Byte Array in einem Byte Array.
Code:
Code:
FindData proc input:DWORD, search:DWORD, len:DWORD, s_len:DWORD
	LOCAL cnt:DWORD, result:DWORD, i:DWORD, j:DWORD
	mov i, 0
	mov cnt, 0
	@main_loop:
		pushad
		mov cnt, 0
		mov eax, dword ptr ds:[input]
		add eax, i
		movzx edx, byte ptr ds:[eax]
		mov eax, dword ptr ds:[search]
		add eax, cnt
		movzx ecx, byte ptr ds:[eax]
		cmp edx, ecx
		jne @Next
		mov j, 0
		@second_loop:
			mov eax, dword ptr ds:[input]
			add eax, i
			add eax, j
			movzx edx, byte ptr ds:[eax]
			mov eax, dword ptr ds:[search]
			add eax, cnt
			movzx ecx, byte ptr ds:[eax]
			cmp edx, ecx
			jne @Next
			mov edx, i
			mov result, edx
			inc cnt
			mov edx, s_len
			inc j
			cmp j, edx
			jl @second_loop
			jmp @End
		@Next:
		popad
		mov edx, len
		inc i
		cmp i, edx
		jl @main_loop
	@End:
	mov eax, result
	ret

FindData endp
Anwendung:
Code:
//1 Parameter: Byte Array in welchem gesucht wird
//2 Parameter: Byte Array welches gesucht werden soll
//3 Parameter: Länge des Parameter 1
//4 Parameter: Länge des Parameter 2
invoke FindData, addr szTest, addr szABC, 11, 3
Das return-value ist der Index, wo das "Such-Array" anfängt.
​Tension is offline  
Old 10/31/2013, 11:44   #10

 
Ravenstorm's Avatar
 
elite*gold: 0
The Black Market: 100/0/0
Join Date: Jan 2010
Posts: 13,150
Received Thanks: 3,206
PHP Code:
$friendlyString preg_replace('/^-+|-+$/'''strtolower(preg_replace('/[^a-zA-Z0-9]+/''-'$string))); 
Einfache Methode um einen String (Bsp. URL) in einen url freundlichem String zu verwandeln.

Bsp.:

Quote:
YOLO SWAG OF DOOM => yolo-swag-of-doom
Fire in the backyard => fire-in-the-backyard
Ravenstorm is offline  
Thanks
1 User
Old 10/31/2013, 17:13   #11



 
Shawak's Avatar
 
elite*gold: 0
The Black Market: 259/0/0
Join Date: Apr 2010
Posts: 10,289
Received Thanks: 3,613
Hier mal "verbesserte" Versionen von $_GET, $_REQUEST und $_POST.
Die Funktionen erlauben das definieren einer Variable ohne vorher zu überprüfen ob z.B. der GET Parameter gesetzt wurde, indem sie einfach null zurückgeben.

Code:
	function REQUEST($attr, $mysqlEscape = false) {
		if(isset($_REQUEST[$attr]))
			return SpecialChars($_REQUEST[$attr]);
	}
	
	function GET($attr, $mysqlEscape = false) {
		if(isset($_GET[$attr]))
			return SpecialChars($_GET[$attr], $mysqlEscape);
	}
	
	function POST($attr, $mysqlEscape = false) {
		if(isset($_POST[$attr]))
			return SpecialChars($_POST[$attr], $mysqlEscape);
	}
	
	function SpecialChars($str, $mysqlEscape = false) {
		$ret = htmlspecialchars($str);
		return ($mysqlEscape ? mysql_real_escape_string($ret) : $ret);
	}
Beispiel:

Code:
$var = null;
if(isset($_GET['param']))
  $var = $_GET['param'];
Wird zu:
Code:
$var = GET('param', true); // true für ein mysql_escape_string
Lg
Shawak is offline  
Old 11/06/2013, 00:26   #12



 
Sedrika's Avatar
 
elite*gold: 18
The Black Market: 103/0/0
Join Date: Sep 2009
Posts: 20,174
Received Thanks: 14,475
Hier mal eine injection sichere SQL Klasse für MS-SQL.

Klasse:
PHP Code:
 <?php
    
class MSSQL
    
{
        public 
$query null;
        public 
$fetch null;
        protected 
$fetca;
        protected 
$mfetc;
    
        public function 
__construct ($fetch false$multi false)
        {
            
$fetch $this->fetca true $this->fetca false;
            
$multi $this->mfetc true $this->mfetc false;
        }
        
        public function 
Escape($arg)
        {
            foreach (
$arg as $value)
                
is_numeric($value) ? $return[] = $value $return[] = "0x".bin2hex$value );
            return 
$return;
        }

        public function 
Query()
        {
            if( !
func_num_args() )
                return 
false;
                
            
$arg func_get_args();
            
            
$query $arg[0];
            unset(
$arg[0]);
            
            if( 
count$arg ) )
                
$query vsprintf$query$this->Escape$arg ) );
        
            
$this->query mssql_query($query);
            
            if( 
$this->fetca )
            {
                if( 
$this->mfetc )
                    while( 
$fetch mssql_fetch_array$this->query ) )
                        
$this->fetch[] = $fetch;
                else
                    
$this->fetch[] = mssql_fetch_array$this->query );
            }
            
            if( 
is_resource$this->query ) )
                
mssql_free_result$this->query );
            
            return 
true;
        }
        
        public function 
m_fetch()
        {
            
$return null;            
            
$i 0;            
            while( isset( 
$this->fetch[$i] ) )
            {
                
$return[] = $this->fetch[$i];
                
$i++;
            }
            return 
$return;
        }
    }
?>
Anwendung:
PHP Code:
// Update / Insert / Delete Commands
$SQL = new MSSQL();
$Query "USE [EXAMPLE_DBF] UPDATE [EXAMPLE_TBL] SET [EXAMPLE_COLUMN_1] = %s, [EXAMPLE_COLUMN_2] = %s";
$SQL->Query$Query"example value 1""example value 2" );

// Get value
$SQL = new MSSQLtrue );
$Query "USE [EXAMPLE_DBF] SELECT * FROM [EXAMPLE_TBL] WHERE [EXAMPLE_COLUMN] = %s";
$result $SQL->Query$Query"test" ) ? $SQL->fetch[0]["COLUMN"] : false;

// Get multiple values
$SQL = new MSSQLtruetrue );
$Query "USE [EXAMPLE_DBF] SELECT * FROM [EXAMPLE_TBL] WHERE [EXAMPLE_COLUMN] = %s";
$result $SQL->Query$Query"test" ) ? $SQL->m_fetch() : false
Selbst wenn man einen INSERT Befehl so manipulieren würde, dass shutdown an den Server gesendet wird, würde dieser diesen nicht mehr als Befehl sondern als Zeichenkette interpritieren und somit wären Injections geblockt.

Anmerkung: Bei einzelnen rückgabewerten ist $result eine einfache Variable und bei mehreren ist es ein array. Falls ein Rückgabewert vorhanden ist, wird dieser gesetzt ansonsten ist $result false. Diesen könnte man auf valität abfragen mit
PHP Code:
if ( $result )
{
// Dein code

Auf wunsch kann ich das ganze noch einmal für MySQL umschreiben.
Sedrika is offline  
Old 11/06/2013, 08:02   #13



 
Shawak's Avatar
 
elite*gold: 0
The Black Market: 259/0/0
Join Date: Apr 2010
Posts: 10,289
Received Thanks: 3,613
Eine Klasse zum Ermitteln von Zeitdifferenzen in PHP.

Code:
	class TimeDiff {
		private $Diff;
		public function __construct() {
			$this->Reset();
		}
		public function Reset() {
			$this->Diff = microtime(true);
		}
		public function Get() {
			return round(microtime(true) - $this->Diff, 4);
		}
	}
Verwendung:

Code:
	$diffTotal = new TimeDiff();
	
	$diff = new TimeDiff();
	$str = '';
	for($i = 0; $i < 1 * 1000 * 1000; $i++)
		$str .= 'test';
	echo 'Test took ' . $diff->Get() . ' seconds<br>';
	
	$diff->Reset();
	$str = '';
	for($i = 0; $i < 10 * 1000 * 1000; $i++)
		$str .= 'test';
	echo 'Another took ' . $diff->Get() . ' seconds<br>';
	
	echo 'Together they took ' . $diffTotal->Get() . ' seconds<br>';
Beispielausgabe:

Code:
Test took 0.1256 seconds
Another took 2.8481 seconds
Together they took 2.9738 seconds
Lg
Shawak is offline  
Thanks
2 Users
Old 11/12/2013, 15:08   #14
 
elite*gold: 25
Join Date: Sep 2011
Posts: 5,536
Received Thanks: 1,266
> Im Grunde ein einfacher Language Parser der Strings aus einer Datei zieht
> Demo als Anhang

PHP Code:
<?php

/**
 * Lingovo is an easy to use class to get strings out of a file.
 * You can use this class as Translation system.
 * @package Lingovo
 * @author Pascal Krason (Padrio) <>
 * @version 0.1
 */
class Lingovo
{
    

    
/**
     * Directory where the translation files are stored.
     * @var string 
     * @access private
     */
    
private $langDir;
    
    
/**
     * Translated string will be stored here
     * @var array 
     * @access private
     */
    
public $strings = array();
    
    
    
/**
     * Special strings like the author or version of the file will be stored here
     * @var array 
     * @access private
     */
    
public $specialStrings = array();
    
    
/**
     * This array inlcudes informations about actions and error messages if they get thrown
     * Actually this variable is currently unused.
     * @var array
     * @access private
     */
    
private $debug = array();
    
    
/**
     * Content of a Translation File wil be stored here
     * @var string
     * @access private
     */
    
private $fileContent;
    
    
/**
     * If 0 a requested string will be just returned, if 1 it will be displayed through an echo
     * This can be set globally or in the function for itself.
     * @var bool
     * @access public
     */
    
public $defaultDisplayMode 0;
    
    
    
/**
     * Load a Translation file
     * @param type $file    File wich will be loaded, this can be only a file (if $langDir is defined) or the full path to the file
     * @return boolean      TRUE if file could be loaded and splitted into the arrays and FALSE if something fails.
     */
    
public function load$file ){
        
        
//Fetch file content        
        
$this->fileContent $this->getContent($file);
        
        
//check if file content could be fetched
        
if($this->fileContent === false){
            
$this->error('could not load file: unknown error.');
            return 
false;
        }
        
        
//Split every line and add to the array
        
$stringArray explode("\n"$this->fileContent);
        
        
//Check every line
        
foreach($stringArray as $value){
            
            
//Check if actual line is not empty
            
if(!empty($value)){
                
                
//check what type this line is
                
switch(substr($value01)){
                    
                    case 
'@':
                        
                        
$splitted explode('='$value);
                        
                        
$this->specialStrings[str_replace('@'''$splitted[0])] = $splitted[1];
                        
                    break;
                    
                    case 
'$':
                        
                        
//Split string (Will bre improoved with preg_match() in 0.2)
                        
$string explode('='$value);
                        
                        
//Replace first char ($)
                        
$string[0] = str_replace('$'''$string[0]);
                        
                        
//Count if the char "=" is more then once in the string
                        
if(substr_count($value'=') > 1){
                            
                            
//get first item and merge rest of the array
                            
$this->strings[$string[0]] = $this->_array_merge($string);
                            
                        }else{
                            
                            
//If not just add normally
                            
$this->strings[$string[0]] = $string[1];
                            
                        }
                        
                        
                    break;
                }
                
            }
            
        }
        
        return 
true;
        
    }
    
    
/**
     * Sets the directory where the language files will be stored
     * @param type $dir     Dir where the files are stored
     * @param type $filter  Replace the separators with DIRECTORY_SEPARATOR
     * @return boolean      Returns true if directory coul´d be set, False if an error occures
     */
    
public function setDir$dir$filter true ){
        
        
//Check whether parameter is empty
        
if(empty($dir)){
            
$this->error('Could not set directory: parameter "$dir" is empty.');
            return 
false;
        }
        
        
//Check if directory exists
        
if(!file_exists($dir)){
            
$this->error('Could not set directory: directory does not exist.');
            return 
false;
        }
        
        
//Check if $dir is a directory
        
if(!is_dir($dir)){
            
$this->error('Could not set directory: '$dir .' is not a valid directory.');
            return 
false;
        }
        
        
//If separator filter is turned true, set directory where files will be stored , but replace the directory separators with the right one.
        
if($filter == false){
            
            
//Check which separator is given and replace with the right one
            
if( strpos($dir'/') != false ){
                
$this->langDir str_replace('/'DIRECTORY_SEPARATOR$dir);
            }else{
                
$this->langDir str_replace('\\'DIRECTORY_SEPARATOR$dir); //chr(134) is the backslash, this needs to be used - otherwise the backslash will escape the string falsewise
            
}
            
        }else{
            
            
$this->langDir $dir;
            
        }
        
        
//Check if ends with a seprator
        
if(substr($this->langDir, -1) != '/' AND substr($this->langDir, -1) != '\\'){ //chr(134) is the backslash, this needs to be used - otherwise the backslash will escape the string falsewise
            
$this->langDir $this->langDir DIRECTORY_SEPARATOR;
        }
        
        return 
true;
        
    }
    
    
/**
     * Get a special string (mostly just informations about the language file like author, language, version etc)
     * @param type $string          Which string to return
     * @param type $displayMode     Displaymode, if not set by user will use default value
     * @return boolean              Request string if succed, else FALSE on fail.
     */
    
public function getSpecialString$string$displayMode NULL ){
        
        
//Check if first parameter($string) was given
        
if(empty($string)){
            
$this->error('Could not get special string: first parameter($string) is empty.');
            return 
false;
        }
        
        
//Check if displayMode is set by user, if not set to default
        
if($displayMode === NULL){
            
$displayMode $this->defaultDisplayMode;
        }
        
        
//check if array key (special string) exists
        
if(!isset($this->specialStrings[$string])){
            
$this->error('Could not get special string: string not found.');
            return 
FALSE;
        }
        
        switch(
$displayMode){
        
            case 
Mode::_RETURN:
                return 
$this->specialStrings[$string];
            break;
        
            case 
Mode::_ECHO:
                echo 
$this->specialStrings[$string];
            break;
        
            default:
                
$this->error('Could not get special string: mode not found');
                return 
false;
            break;
        
        }
        
    }
    
    
/**
     * Return a String from the file
     * @param type $string          String to display
     * @param type $data            Replaced vars in the string, just set parameter as empty array if there is nothing to replace and you need to change the Dislay Mode
     * @param type $displayMode     Method to display, If Null it will check the defaultDisplayMode variable which is default set to 0. If this Variable is set to 0 the string will be just returned, if 1 it will be returned through a echo 
     * @return boolean              Oppending on the Display Mode, If succed it will display the string if displayMode or defaultDisplayMode is set to 0, or a TRUE if its set to 1. On Error it will return a FALSE.
     */
    
public function getString$string$data NULL$displayMode NULL ){
        
        
//Check if first parmeter($string) is empty
        
if(empty($string)){
            
$this->error('Could not get string: $string is empty');
            return 
false;
        }
        
        
//Check if string the user searches for exists
        
if(empty($this->strings[$string])){
            
$this->error('Could not get string: could not find string('$string .')');
            return 
false;
        }
        
        
//Check if Mode was given by User, if not set by default
        
if($displayMode == NULL){
            
$displayMode $this->defaultDisplayMode;
        }
        
        
//Check if strings needs to be formatted
        
if(is_array($data)){
            
            
$prepared $this->replace_vars($this->strings[$string], $data);
            
        }else{
            
            
$prepared $this->strings[$string];
            
        }
        
        
//return oppending on display mode
        
switch($displayMode){
            case 
Mode::_ECHO:
                
                echo 
$prepared;
                return 
true;
                
            break;
        
            case 
Mode::_RETURN:
                
                return 
$prepared;
                
            break;
        
            default:
                
$this->error('Could not get string: mode not found');
                return 
false;
            break;
        }
        
    }
    
    
    
/**
     * Get a content of a file and return it.
     * @param type $file    File from which the content will be loaded.
     * @return boolean      Requested content of a file or FALSE if an error occures.
     */
    
private function getContent$file ){
        
        
//Check if file exists
        
if(!file_exists($this->langDir $file)){
            
$this->error('Could not fetch file: file('$this->langDir $file .') not found.');
            return 
false;
        }
        
        
//Fetch Content
        
$content file_get_contents($this->langDir $file);
        
        
//Check if content were fetched correctly
        
if($content === false){
            
$this->error('Coult not fetch file: unknown error.');
            return 
false;
        }else{
            return 
$content;
        }
        
    }
    
    
/**
     * This function will be improved in version 0.2 or 0.3
     * Actually its a bit useless
     * @param type $message     Message to display
     * @throws Exception        Just a standart exception with a message
     */
    
private function error$message ){
        
        throw new 
Exception$message );
        
    }
    
    
/**
     * Merges array to a string while not using the first item, just the rest of the array
     * @param array $arr    Array to merge
     * @return type         Merged array as string
     */
    
private function _array_merge( array $arr ){
        
        
//Define new empty string
        
$new '';
        
        
//go through the array und put everything in a string up on the first key.
        
for($i 0$i <= count($arr); $i++){
            
            
//Check if actual item is not the first
            
if($i != 0){
                
                
//Add array content to string
                
$new .= $arr[$i];
                
            }
            
        }
        
        
//Return the finished string
        
return $new;
        
    }
    
    
/**
     * Replace Vars in a string
     * @param type $string  String with strings to replace
     * @param type $replace Array with data to replace in the string. e.g. array('string_in_language_file' => 'replace with me');
     */
    
private function replace_vars$string$replace = array() ){
        
        
//Define a new Array
        
$temp = array();
        
        
//Go through array
        
foreach($replace as $key => $value){
            
            
//Set var to replace in string as key, and Value as value to replace with.
            
$temp['%' $key '%'] = $value;
            
        }
        
        
//Return the formatted string.
        
return str_replace(array_keys($temp), array_values($temp), $string);
        
    }
    
}

/*
 * Just used for constants
 */
class Mode
{
    
    const 
_RETURN 0;
    const 
_ECHO   1;
    
}
Download + Dokumentation ebenfalls hier vorhanden:
Attached Files
File Type: rar demo.rar (4.6 KB, 5 views)
IchVerabschiedeMich is offline  
Thanks
1 User
Old 11/14/2013, 15:14   #15


 
Kentika's Avatar
 
elite*gold: 0
The Black Market: 120/0/0
Join Date: Sep 2011
Posts: 5,498
Received Thanks: 1,114
Eine einfache Suche:
PHP Code:
<?php
   $db 
= new PDO('mysql:host=localhost;dbname=<DBNAME>''<USERNAME>''PASSWORD');

   
$stmt $db->prepare("SELECT * FROM table WHERE description LIKE '%:searchParam%'"); 
   
$stmt->bindParam(":searchParam"$searchParam);
   
$stmt->execute();

   
// Fetch & Result
   
$result $stmt->fetchAll();

   
// Ausgabe
   
foreach($result as $row) {
       
print_r($row);
   }
?>
Man hätte es schöner machen können aber naja
Kentika is offline  
Closed Thread


Similar Threads Similar Threads
Warrock - Code Snippets
07/03/2013 - WarRock - 1090 Replies
Aloha Wie bereits aus dem alten Thread bekannt, könnt ihr hier -> eure Sourcecodes releasen( Funktionen, Basen etc ) -> um Hilfe zu Sourcecodes bitten -> Nach Sourceodes fragen Damit das nicht wieder, wie beim alten Thread in einem totalem Spam und Flamechaos endet, gibt es auch hier wieder Regeln an die sich jeder hält. Ich werde diesen Thread besonders im Auge behalten und bei Verstößen entsprechend agieren
[S]PSN MW3 1x collection code egal welche [B]10€ PSC CODE
04/12/2013 - Consoles Trading - 0 Replies
Hallo, Topic regelt, nur trusted user oder psn code first ..!!! Egal welches schnell bitte .. !! Nur codes keine psn accounts mit dem pack !
Code-Schnipsel: Überprüfen ob 16:9/4:3 und Mobil/Computer
04/07/2013 - Web Development - 9 Replies
Guten Tag liebe elitepvpers Community, ich bräuchte einen Überprüfung ob der Benutzer eine 16:9 oder eine 4:3 Auflösung nutzt, außerdem eine Überprüfung auf Tablet und Handy. Ich hoffe ihr könnt mir da weiterhelfen. Mit freundlichen Grüßen
[GTA SA][Sammelthread / Collection] Code Snippets & Short Questions
12/12/2012 - Grand Theft Auto - 4 Replies
GTA Collection Hallo, auch wenn diese Section eher inaktiv ist, dachte ich mir, es sei sinnvoll, wenn man schnell einen Überblick über Fragen etc hat. Ebenso mit Code Schnipseln und dem ganzen Kram. Ich würde den Thread täglich updaten und die Direktlinks zu den Fragen & Antworten hier in eine Tabelle eintragen. Das läuft in etwa so: Questions Question/Frage | Author/Autor | Answer/Antwort | Author/Autor | MTA/SAMP/GTA SP x | x | x | x | x
WarRock EU - Code Snippets
07/12/2012 - WarRock - 7490 Replies
Hi Leute, in diesem Thread könnt ihr: -> Nach Sourcecodes fragen(Beispiel unten) -> Eure Sourcecodes posten(Wenn sie nicht von euch sind mit Credits!) -> Fragen ob eure Source evtl. einen Fehler hat -> Fragen was welcher Fehler bedeuted -> Sourcecodes entnehmen(Bitte beim Release dann Credits angeben!)



All times are GMT +1. The time now is 07:11.


Powered by vBulletin®
Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.
SEO by vBSEO ©2011, Crawlability, Inc.
This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Support | Contact Us | FAQ | Advertising | Privacy Policy | Terms of Service | Abuse
Copyright ©2025 elitepvpers All Rights Reserved.