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.
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.
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;
?>
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.
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:
//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.
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.
// 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 MSSQL( true ); $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 MSSQL( true, true ); $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.
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);
}
}
> 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 ){
//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)){
//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; }
//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:
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!)