Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

nabilfx

preg_match

Recommended Posts

Tenho um script para me enviar o email cadastrado em php por preg_match.

Mais a Arroba @ e o que vem escrito antes, fica invisível, O que esta escrito na frente aparece, tipo gmail.com

 

Como poderia arrumar isso para aparecer o email completo no registro online.

unnamed.png

 

Aqui esta o script.

<?php
 
    function Connect(){
        //Set global variables so they can be used in this function
        global $hostName; global $userName;
        global $password; global $database;
        $status = mysql_connect($hostName,$userName,$password); //Attempt to connect to Database
     
        if(!$status){echo 'Server Not Found'; exit;} //Hosting Server not found
        if(!@mysql_select_db($database)){echo 'Database Not Found'; exit;} //Database not found
        return $status; //Return link on established connection
    }
    function CheckKey($hash,$name){  //Check weather Md5 hash matches
        global $secretKey;
        $checkHash = md5($name.$secretKey);
        if(strcmp($checkHash,$hash) == 0){
            return 'pass'; //hash matches
        }else{
            return 'fail'; //hash failed
        }
    }
    function CleanInput($input){ //Sanitize user input
        $cleanInput = mysql_real_escape_string($input); //Use string escape
        if(preg_match('/[^@.a-z_\-0-9\s]/i',$cleanInput) == 1){ // Using regular expression
            echo 'Bad Input ==> ' . $input; exit; //Failed, exit to prevemt sql injection hacks
        }
        return $cleanInput; //Return clean input
    }
?>

Compartilhar este post


Link para o post
Compartilhar em outros sites

precisso que apareca a @ arroba e o que esta atras escrito.

Se coloco nabil@hotmail.com so aparece hotmail.com

Se coloco nabil@gmail.com so aparece gmail.com

 

So aparece o escrito que esta na frente da @ arroba

o escrito atras da arroba e a arroba @ fica invisível e não aparece no registro online.

 

deve ser o preg_match que esta errado, eu não to conseguindo arrumar

Compartilhar este post


Link para o post
Compartilhar em outros sites

tire o antigo prega_match /[^@.a-z_\-0-9\s]/i e coloquei o que me mandou /^@[a-z0-9\.a-z_\-0-9]+/i

 

ele registra mais continua sem aparecer a arroba @ e o escrito atras dela.

 

Sera q o problema esta em outro .php que veio junto. Comprei no Unity store, mais o criador não me responde para tentar resolver.

 

 

se vc quiser te mando os scripts restantes para vc ver

Compartilhar este post


Link para o post
Compartilhar em outros sites

aqui o código RegisterUser.php que registra o serverconect.php

<?php	include('ServerConnect.php');	$connection = Connect();//Attempt to Connect to MYSQL Server & DataBase		//Get variables from unity	$name = $_POST['name'];	$date = strtotime(date("Y-m-d"));	$tables = $_POST['tables'];	//Security Check	$hash = $_POST['hash'];	if(CheckKey($hash,$name) == 'fail'){ //Check if hash is valid		echo 'Security Failure'; exit;	}		//Make sure all input is sql injection safe	$name =  CleanInput($name);	$tables = CleanInput($tables);	//Split difficulty tables	$tablesBroken = explode(' ', $tables);	$arr = Array();	$i = 0;$x = 0;	foreach($tablesBroken as $table){ //Check if name is in any of our tables		$sql = "SELECT * FROM $table WHERE name = '$name'";		$result = mysql_query($sql) or Die('Query failed: ' . mysql_error()); 		$count = mysql_num_rows($result);		//Process Results : Tally up how many times we fing the name 		if($count > 0){ 			$arr[$i] = 1;			$x++;		}else{			$arr[$i] = 0;		}		$i++;	}	if($x == 0){ //Name not in use in any table		foreach($tablesBroken as $table){//Insert the user in all tables			$sql = "INSERT INTO $table (name,score,date)			VALUES('$name',0,'$date')";			$result = mysql_query($sql) or Die('Query failed: ' . mysql_error()); 		}echo 'Registration Complete'; exit;	}else if($x >= Count($tablesBroken)){//Name in use in all tables		echo 'Already Used'; exit; //exit	}else{//In use but not complete in all tables		for($c = 0; $c < Count($tablesBroken); $c++){			if($arr[$c] == 0){ //Insert name in tables where it is not present				$toTable = $tablesBroken[$c];				$sql = "INSERT INTO $toTable(name,score,date)				VALUES('$name',0,'$date')";				$result = mysql_query($sql) or Die('Query failed: ' . mysql_error()); 			}		}echo 'Registration Complete'; exit;	}?>

aqui o Database.php

<?php	include('ServerConnect.php');	$connection = Connect();//Attempt to Connect to MYSQL Server & DataBase	//Get variables from Unity	$mode = $_POST['mode'];	$table = $_POST['table'];	if($mode == 0){ //Create current table		$sql = "CREATE TABLE $table(id INT(10) AUTO_INCREMENT,		PRIMARY KEY(id),		name VARCHAR(25),		score INT(10),		date VARCHAR(25))"; //we keep date a varchar in the database		$result = mysql_query($sql) or Die('Query failed: ' . mysql_error()); 		echo $table.' Created'; exit;	}else if ($mode == 1){		//Delete scores below input score		$score = $_POST['score'];	    $sql = "DELETE FROM $table WHERE score < '$score'";		$result = mysql_query($sql) or Die('Query failed: ' . mysql_error()); 			echo 'Deleted'; exit;	}else if ($mode == 2){		//Delete scores below posted date		$date = strtotime($_POST['date']);		$sql = "DELETE FROM $table WHERE date < '$date'";		$result = mysql_query($sql) or Die('Query failed: ' . mysql_error()); 		echo 'Deleted'; exit;	}?>

aqui o SendHighScores.php

<?php	include('ServerConnect.php');	$connection = Connect(); //Attempt to Connect to MYSQL Server & DataBase		//Get variables from Unity	$table = $_POST['table'];	$name = $_POST['name'];	$score = $_POST['score'];	$updating = $_POST['updating'];	$date = strtotime(date("Y-m-d")); //Get Time	//Security Check	$hash = $_POST['hash'];	if(CheckKey($hash,$name) == 'fail'){ //Check if hash is valid		echo 'Security Failure'; exit;	}		//Make sure all input is sql injection safe	$name =  CleanInput($name);	$table = CleanInput($table);	$score =  CleanInput($score);	$updating =  CleanInput($updating);	//Run Query (inser or update)	if($updating == 0){ //Free entry So make new row		$sql = "INSERT INTO $table (name,score,date)		VALUES('$name','$score','$date')";	}else{ //We are updating a previously registered user		$sql = "UPDATE $table SET score = '$score',		date = '$date' WHERE name = '$name'";	}	$result = mysql_query($sql) or Die('Query failed: ' . mysql_error()); 		//Now update our table, by ordering it by descending score	$sql = "ALTER TABLE $table ORDER BY score DESC,id DESC";	$result = mysql_query($sql) or Die('Query failed: ' . mysql_error()); 		echo 'Accepted';?>

aqui o GetHighScores.php

<?php	include('ServerConnect.php');	$connection = Connect();//Attempt to Connect to MYSQL Server & DataBase		//Get variables from unity	$table = $_POST['table'];	$scope = $_POST['scope'];	$limit = $_POST['limit'];	//Security Check	$hash = $_POST['hash'];	if(CheckKey($hash,$table) == 'fail'){ //Check if hash is valid		echo 'Security Failure'; exit;	}		//Make sure all input is sql injection safe	$table = CleanInput($table);	$scope =  CleanInput($scope);	$limit =  CleanInput($limit);	//Create a Query For The Right Table	if($scope == 'AllTime'){ //Get All scores		$sql = "SELECT * FROM $table LIMIT 0,$limit";	}else{ //Get scores posted today		$date = strtotime(date("Y-m-d")); //Today's date		$sql = "SELECT * FROM $table WHERE date = '$date' LIMIT 0,$limit";	}	$result = mysql_query($sql) or Die('Query failed: ' . mysql_error());	//1.Build a string of all scores to send back	$info = "";	while($found = mysql_fetch_array($result)){		$info = $info .'@'. $found['name'] .':'. $found['score'];	}	echo $info;?>

Compartilhar este post


Link para o post
Compartilhar em outros sites

Continuo sem entender. Verifique como está sendo gravado no banco, pode ser algum problema na hora de exibir.

Compartilhar este post


Link para o post
Compartilhar em outros sites

aqui o HighScore.js que veio junto. e tudo que quem, vc consegue ver algo que possa mudar, para o display sair email completo.

#pragma strict
import System.Security.Cryptography;
import System.Text;

@script ExecuteInEditMode()

enum TrackingType{FreeEntry,TrackProgress}
var trackType : TrackingType = TrackingType.FreeEntry;
enum DeveloperType{debug,live}
var developmentMode : DeveloperType = DeveloperType.live;

private var secretKey : String = "test";
var sendScoreURL : String = "http://nfx.comuv.com/.../SendHighScores.php?";
var getScoresURL : String = "http://nfx.comuv.com/.../GetHighScores.php?";
var resetScoresURL : String = "http://nfx.comuv.com/.../ResetHighScores.php?";
var registerUserURL : String = "http://nfx.comuv.com/.../RegisterUser.php?";
var getUserScoreURL : String = "http://nfx.comuv.com/.../GetUserScore.php?";
var DatabaseToolsURL : String = "http://nfx.comuv.com/.../DatabaseTools.php?";
//Modules Done
class Module{
	var showStatus : boolean = true;
	var showScores : boolean = true;
	var showUserScore : boolean = true;
	var showSendScore : boolean = true;
	var showDifficultySwitch : boolean = true;
	var showScopeSwitch : boolean = true;
}
var displayOptions : Module;
//Class That contains 
class Mode{
	var displayName : String = "Easy";
	var playerPrefsName : String = "Easy";
	var databaseName : String = "Easy";
}
var difficultyModes : Mode[];
var startDifficultyMode : int = 0;
private var modeIndex : int = 0;
//Score Scope
private var scoreScopeText : String = "Global";//AllTime,Daily
private var currentScope : String = "AllTime";
class ScoreScopeSettings{
	var dailyName : String = "Daily";
	var allTimeName : String = "Global";
}
var scoreScope : ScoreScopeSettings;
//Get HighScores Fields(keep the same lenght)
private var serverHighScores : String[] = new String[0];
private var scrollView : Vector2;
var scoreType : String = "Points";
var maxHighScores : int = 100;
//Send HighScores Fields
private var serverHighScoreName : String = "";
var maxNameCharacters : int = 20;
//Reset  HighScores Fields
var resetNames : int = 100;
var minResetScore : int = 100;
var maxResetScore : int = 1000;
//Bad Names
var blockBadNames : boolean = true; //Block names from bas names list
var badNamesList : TextAsset;  //List Of bad names
//PlayerPrefsName
var existingNamePlayerPrefs : String = "playerName";
//Rects
var sendScoresOffsetRect : Rect = new Rect(450,150,250,30);
var getScoresOffsetRect : Rect = new Rect(450,100,100,25);
var scoreScopeOffsetRect : Rect = new Rect(300,100,100,25);
var messageOffsetBox : Rect = new Rect(450,-150,250,25);
var localScoreOffsetRect : Rect = new Rect(450,-105,250,25);
var serverScoreOffsetRect : Rect = new Rect(450,-60,250,40);
var scoresListOffsetRect : Rect = new Rect(150,150,380,350);
private var baseRect : Rect = new Rect(Screen.width * .5F,Screen.height * .5F,100F,100F);
//status
private var year : int = 2012;
private var month : int = 9;
private var day : int = 1;
private var debugScore : int = 0;
private var deleteScore : int = 0;
private var localScore : int = 0;
private var serverScore : int = 0;
private var serverRank : int = 0;
private var status : String = ""; //Status of Server Operations
private var runningHsServer : int = 0; //Are we doing server side operations
private var runningTrack : int = 0; //Are we seeking player status
//skin
var skin : GUISkin;

function DatabaseTools(mode : int ,tables : Mode[]){
	if(runningHsServer == 1){status = "Still Running"; return;}
	runningHsServer = 1; status = "Running";
	//0 = create tables
	var hsFm : WWWForm = new WWWForm();
	hsFm.AddField("mode",mode);
	for(var md : Mode in tables){
		hsFm.AddField("table",md.databaseName);	
		var hs : WWW = new WWW(DatabaseToolsURL,hsFm);
		yield hs;
		if(hs.text.Equals("Created")){status = "Database Created";}
		else{status = "Error Occured";}
		Debug.Log(hs.text);
	}
	//Stop Running
	runningHsServer = 0;
	SynchTable();
}

function DatabaseTools(mode : int,table : String){
	if(runningHsServer == 1){status = "Still Running"; return;}
	runningHsServer = 1; status = "Running";
	//Modes
	// 1 = delete by score
	// 2 = delete by date
	var hsFm : WWWForm = new WWWForm();
	hsFm.AddField("mode",mode);
	if(mode == 1){
		hsFm.AddField("table",table);
		hsFm.AddField("score",deleteScore);
	}else if(mode == 2){
		hsFm.AddField("table",table);
		hsFm.AddField("date",year+"/"+month+"/"+day);
	}
	var hs : WWW = new WWW(DatabaseToolsURL,hsFm);
	yield hs;
	if(hs.text.Equals("Created")){status = "Database Created";}
	if(hs.text.Equals("Deleted")){status = table +" Entries Cleaned";}
	
	else{status = "Error Occured";}
	Debug.Log(hs.text);
	//Stop Running
	runningHsServer = 0;
	SynchTable();
}

function ResetHighScores(table : String,mode : String){
	if(runningHsServer == 1){status = "Still Running"; return;}
	runningHsServer = 1; status = "Running";
	//
	var hsFm : WWWForm = new WWWForm();
	hsFm.AddField("table",table);
	hsFm.AddField("mode",mode);
	hsFm.AddField("count",resetNames);
	hsFm.AddField("min",minResetScore);
	hsFm.AddField("max",maxResetScore);
	var hs : WWW = new WWW(resetScoresURL,hsFm);
	yield hs;
	//Update
	status = hs.text;
	//Running
	runningHsServer = 0;
	SynchTable();
}

function GetUserScore(table : String,name : String){
	runningTrack = 1;//We are seeking user stats
	//
	serverRank = 0;
	serverScore = 0;
	//Get User Score
	var hsFm : WWWForm = new WWWForm();
	hsFm.AddField("name",name);
	hsFm.AddField("table",table);
	hsFm.AddField("hash",GetHash(name));
	var hs : WWW = new WWW(getUserScoreURL,hsFm);
	yield hs;
	Debug.Log(hs.text);
	if(hs.text != "Not Found" && !hs.text.Contains("Query failed")){
		var userData : String[] = hs.text.Split(':'[0]);
		//Process Results
		if(userData[1] != null)serverRank = int.Parse(userData[1]);
		if(userData[2] != null)serverScore = int.Parse(userData[2]);
	}
	else if(hs.text == "Not Found"){
		PlayerPrefs.SetInt("nameRegistered",0);
	}
	runningTrack = 0;
}

function GetHighScores(table : String,scope : String,limit : int){
	if(runningHsServer == 1){status = "Still Running"; return;}
	runningHsServer = 1; status = "Running";
	//Get HighScores
	serverHighScores = new String[maxHighScores];
	for(var st : int = 0;st<serverHighScores.Length;st++){
		serverHighScores[st] = "Loading....";
	}	
	var hsFm : WWWForm = new WWWForm();
	hsFm.AddField("table",table);
	hsFm.AddField("scope",scope);
	hsFm.AddField("limit",limit);
	hsFm.AddField("hash",GetHash(table));
	var hs : WWW = new WWW(getScoresURL,hsFm);
	yield hs;
	
	if(hs.text.Length > 0){
		serverHighScores = hs.text.Split('@'[0]);
		status = "Found "+table+" HighScores";
		Debug.Log("Found HighScores: " + scope+" :" +table);
	}else{
		status = "No "+scope+" Scores";
		Debug.Log("No "+scope+" Scores");
	}
	//Stop Running
	runningHsServer = 0;
	//Get User Stats If Tracking is On & We are Registered
	if(trackType == TrackingType.TrackProgress && PlayerPrefs.GetInt("nameRegistered") == 1){
		StartCoroutine(GetUserScore(difficultyModes[modeIndex].databaseName,serverHighScoreName));
	}
}

function SendHighScores(table : Mode,name : String,score : int,difficultyModesSet : Mode[]){
	if(runningHsServer == 1){status = "Still Running"; return;}
	runningHsServer = 1; status = "Running";
	//Check If We Have Beat Our Own Score First
	if(developmentMode == DeveloperType.live){
		if(PlayerPrefs.GetInt(table.playerPrefsName) <= PlayerPrefs.GetInt("sent"+table.playerPrefsName)){
			status = table.displayName + " Score Previously Submitted"; 
			runningHsServer = 0;
			return;		
		}
	}
	//Trim
	if(name.Length > maxNameCharacters){
		runningHsServer = 0;
		status = "Name Too Long"; return;	
	}
	//Scan & Check Name
	if(blockBadNames && CheckName(name).CompareTo("offensive") == 0){
		runningHsServer = 0;
		status = "Chosen Name Is Offensive"; return;	
	}
	var updating : int = 0; //0 = no we are making a free entry/1 = updating entry
	var newRegistration : int = 0; //We are doing a new registration
	if(trackType == TrackingType.TrackProgress){
		if(PlayerPrefs.GetInt("nameRegistered") == 0){ // We are not yet registred
			newRegistration = 1;
			status = "Registering User";
			var finalResult : String = "";
			var tables : String = "";
			for(var m : int = 0; m < difficultyModesSet.Length; m++){//Create a list of tables to send
				if(m < difficultyModesSet.Length -1){
					tables += difficultyModesSet[m].databaseName + " ";	
				}else{
					tables += difficultyModesSet[m].databaseName;		
				}
			}
			var rsFm : WWWForm = new WWWForm();
			rsFm.AddField("name",name);
			rsFm.AddField("tables",tables);
			rsFm.AddField("hash",GetHash(name));
			var rs : WWW = new WWW(registerUserURL,rsFm);
			yield rs;
			Debug.Log(rs.text+" : "+table.displayName);
			finalResult = rs.text;
			if(finalResult.Equals("Already Used")){
				runningHsServer = 0;
				status = "Name Already Used"; return;
			}else if(finalResult.Equals("Registration Complete")){//We Registered Now Update Score
				PlayerPrefs.SetInt("nameRegistered",1);	
				PlayerPrefs.SetString("registeredName",name);
			}else{
				runningHsServer = 0;
				status = finalResult; return;
			}
		}
		updating = 1; //We need to update entry now
	}
	//SEND OR UPDATE SCORE
	status = "Running"; //Run Again
	var hsFm : WWWForm = new WWWForm();
	hsFm.AddField("table",table.databaseName);
	hsFm.AddField("name",name);
	hsFm.AddField("score",score);
	hsFm.AddField("updating",updating);
	hsFm.AddField("hash",GetHash(name));
	var hs : WWW = new WWW(sendScoreURL,hsFm);
	yield hs;
	Debug.Log(hs.text+" : "+table.displayName);
	//Process Results
	if(hs.text.Contains("Accepted")){
		//Update Score For Anti Spamming
		PlayerPrefs.SetInt("sent"+table.playerPrefsName,PlayerPrefs.GetInt(table.playerPrefsName));
		if(newRegistration == 1){
			status = "Registered & " + table.displayName +" Score Submitted"; 	
		}else{
			status = "New "+ table.displayName +" Score Submitted";
		}
	}
	//Stop Running
	runningHsServer = 0;
	yield new WaitForSeconds(1); //Wait A Second Before Synch
	SynchTable();
}

function SynchTable(){//Update
	StartCoroutine(GetHighScores(difficultyModes[modeIndex].databaseName,currentScope,maxHighScores));	
}
function CheckName(usedName : String) : String{ //Make sure imput name is clean
	var names : String[] = badNamesList.text.Split('\n'[0]); 
	for(var n : String in names){
		if(usedName.Trim().ToLower().IndexOf(n.Trim().ToLower()) > -1){
			return "offensive";
		}
	}
	return "clean";
} 
function GetHash(usedString : String): String{ //Create a Hash to send to server
	var md5 : MD5 = MD5.Create();
	var bytes : byte[] = Encoding.ASCII.GetBytes(usedString+secretKey);
	var hash : byte[] = md5.ComputeHash(bytes);
	
	var sb : String = "";
	for(var i : int = 0; i < hash.Length; i++){
	    sb += hash[i].ToString("x2");
	}
	return sb;
}

function Start(){
	status = "";
	runningHsServer = 0;
	runningTrack = 0;
	StopAllCoroutines();
	//Name Operations
	if(existingNamePlayerPrefs != ""){
		serverHighScoreName = PlayerPrefs.GetString(existingNamePlayerPrefs);
	}
	//Get Base
	startDifficultyMode = Mathf.Clamp(startDifficultyMode,0,difficultyModes.Length-1); //To avoid runtime errors
	modeIndex = startDifficultyMode;
	//Set Initial Settings
	scoreScopeText = scoreScope.allTimeName;
	currentScope = "AllTime";
	//Get Scores
	SynchTable();	
}
	
function OnGUI(){
	if(skin)GUI.skin = skin;
	//Set Base Rect
	baseRect = new Rect(Screen.width * .5F,Screen.height * .5F,100F,100F);
	//Update User Score
	localScore = PlayerPrefs.GetInt(difficultyModes[modeIndex].playerPrefsName);
	//Status Box
	if(displayOptions.showStatus){
		GUI.Box(new Rect(baseRect.x - messageOffsetBox.x,baseRect.y - messageOffsetBox.y,
		messageOffsetBox.width,messageOffsetBox.height),status);
	}
	if(displayOptions.showUserScore){
		//Local Score Box
		GUI.Box(new Rect(baseRect.x - localScoreOffsetRect.x,baseRect.y - localScoreOffsetRect.y,localScoreOffsetRect.width,localScoreOffsetRect.height)
			,"Local "+difficultyModes[modeIndex].displayName+" Score : "+localScore+" "+scoreType);
		if(trackType == TrackingType.TrackProgress){
			if(PlayerPrefs.GetInt("nameRegistered") == 1){
				if(runningTrack == 0){
					GUI.Box(new Rect(baseRect.x - serverScoreOffsetRect.x,baseRect.y - serverScoreOffsetRect.y,serverScoreOffsetRect.width,serverScoreOffsetRect.height)
						,"Global "+difficultyModes[modeIndex].displayName+" Score : "+serverScore+" "+scoreType +"\n"
					+ "Global Rank: "+serverRank);
				}else{
					GUI.Box(new Rect(baseRect.x - serverScoreOffsetRect.x,baseRect.y - serverScoreOffsetRect.y,
						serverScoreOffsetRect.width,serverScoreOffsetRect.height),"Seeking Stats");	
				}
			}else{
				GUI.Box(new Rect(baseRect.x - serverScoreOffsetRect.x,baseRect.y - serverScoreOffsetRect.y,
					serverScoreOffsetRect.width,serverScoreOffsetRect.height),"Send Score To Register");	
			}
		}
	}
	if(displayOptions.showDifficultySwitch){
		//Get & Show High Scores
		if(GUI.Button(new Rect(baseRect.x - getScoresOffsetRect.x,baseRect.y - getScoresOffsetRect.y,
			getScoresOffsetRect.width,getScoresOffsetRect.height),""+difficultyModes[modeIndex].displayName)){
			if(modeIndex < difficultyModes.Length - 1){
				modeIndex++;
			}else{modeIndex = 0;}
			//Update	
			StartCoroutine(GetHighScores(difficultyModes[modeIndex].databaseName,currentScope,maxHighScores));
			localScore = PlayerPrefs.GetInt(difficultyModes[modeIndex].playerPrefsName);
		}
	}
	if(displayOptions.showScopeSwitch){
		//Set Scope
		if(GUI.Button(new Rect(baseRect.x - scoreScopeOffsetRect.x,baseRect.y - scoreScopeOffsetRect.y,
			scoreScopeOffsetRect.width,scoreScopeOffsetRect.height),""+scoreScopeText)){
			if(scoreScopeText.Equals(scoreScope.allTimeName)){
				scoreScopeText = scoreScope.dailyName;
				currentScope = "Daily";
			}else{
				scoreScopeText = scoreScope.allTimeName;
				currentScope = "AllTime";
			}
			
			StartCoroutine(GetHighScores(difficultyModes[modeIndex].databaseName,currentScope,maxHighScores));
		}
	}
	if(displayOptions.showSendScore){
		//Send Scores
		GUILayout.BeginArea(new Rect(baseRect.x - sendScoresOffsetRect.x,baseRect.y - sendScoresOffsetRect.y,
			sendScoresOffsetRect.width,sendScoresOffsetRect.height));
		GUILayout.BeginHorizontal();
		if(trackType == TrackingType.TrackProgress && PlayerPrefs.GetInt("nameRegistered") == 1){
			serverHighScoreName = PlayerPrefs.GetString("registeredName");
			GUILayout.Box(serverHighScoreName,GUILayout.Width(150),GUILayout.Height(30));
		}else{
			serverHighScoreName = GUILayout.TextField(serverHighScoreName,GUILayout.Width(150));	
		}
		if(GUILayout.Button("Send")){
			StartCoroutine(SendHighScores(difficultyModes[modeIndex],serverHighScoreName,localScore,difficultyModes));
		}
		GUILayout.EndHorizontal();
		GUILayout.EndArea();
	}
	//Display Scores
	if(displayOptions.showScores){
		GUILayout.BeginArea(new Rect(baseRect.x - scoresListOffsetRect.x,baseRect.y - scoresListOffsetRect.y,
			scoresListOffsetRect.width,scoresListOffsetRect.height));
		scrollView = GUILayout.BeginScrollView(scrollView);
			for(var x : int = 1;x<serverHighScores.Length;x++){
				if(x > maxHighScores){break;}
				if(serverHighScores[x] != null){
					var score : String[] = serverHighScores[x].Split(':'[0]); //Split the Score From PHP set Up
					if(score.Length > 1){
						GUILayout.BeginHorizontal();
						GUILayout.Label(x.ToString()+": ");
						GUILayout.Space(10);
						GUILayout.Label(score[0],GUILayout.Width(200),GUILayout.Height(30));
						GUILayout.FlexibleSpace();
						GUILayout.Label(score[1]+" "+scoreType,GUILayout.Width(150),GUILayout.Height(30));
						GUILayout.EndHorizontal();
					}
				}else{
					GUILayout.Label(serverHighScores[x] +" "+scoreType,GUILayout.Width(100));
				}
			}
		GUILayout.EndScrollView();
		GUILayout.EndArea();
	}
	//Editor Tools
	if(developmentMode == DeveloperType.debug){
		EditorTools();
	}
}
	
function EditorTools(){
	GUILayout.BeginHorizontal();
	GUILayout.Label("",GUILayout.Width(Screen.width - 230));
	GUILayout.FlexibleSpace();
	GUILayout.BeginVertical();
	GUILayout.Space(100);
	GUILayout.Box("CREATE",GUILayout.Width(200));
	if(GUILayout.Button("Create Tables",GUILayout.Width(200))){
		StartCoroutine(DatabaseTools(0,difficultyModes));
	}
	GUILayout.Box("MANAGE",GUILayout.Width(200));
	if(GUILayout.Button("Reset All "+difficultyModes[modeIndex].displayName,GUILayout.Width(200))){
		StartCoroutine(ResetHighScores(difficultyModes[modeIndex].databaseName,"Reset"));	
	}
	if(GUILayout.Button("Delete All "+difficultyModes[modeIndex].displayName,GUILayout.Width(200))){
		StartCoroutine(ResetHighScores(difficultyModes[modeIndex].databaseName,"Delete"));
	}
	if(GUILayout.Button("Delete Below Score: " +difficultyModes[modeIndex].displayName ,GUILayout.Width(200))){
		StartCoroutine(DatabaseTools(1,difficultyModes[modeIndex].databaseName));	
	}
	GUILayout.BeginHorizontal();
	GUILayout.Box(""+deleteScore,GUILayout.Width(50));
	deleteScore = Mathf.CeilToInt(GUILayout.HorizontalSlider(deleteScore,1,maxResetScore,GUILayout.Width(150)));
	GUILayout.EndHorizontal();
	//
	if(GUILayout.Button("Delete Below Date: "+difficultyModes[modeIndex].displayName,GUILayout.Width(200))){
		StartCoroutine(DatabaseTools(2,difficultyModes[modeIndex].databaseName));	
	}
	GUILayout.BeginHorizontal();
	GUILayout.Label(""+year,GUILayout.Width(30));
	year = Mathf.CeilToInt(GUILayout.HorizontalSlider(year,2012,2013,GUILayout.Width(30)));
	GUILayout.Label(""+month,GUILayout.Width(20));
	month = Mathf.CeilToInt(GUILayout.HorizontalSlider(month,1,12,GUILayout.Width(40)));
	GUILayout.Label(""+day,GUILayout.Width(20));
	day = Mathf.CeilToInt(GUILayout.HorizontalSlider(day,1,31,GUILayout.Width(40)));
	GUILayout.EndHorizontal();
	GUILayout.Box("TEST DATA",GUILayout.Width(200));
	if(GUILayout.Button("Null Registration",GUILayout.Width(200))){
		PlayerPrefs.SetInt("nameRegistered",0);	
		PlayerPrefs.SetString("registeredName","");
	}
	//
	GUILayout.BeginHorizontal();
	GUILayout.Box("Score: "+PlayerPrefs.GetInt(difficultyModes[modeIndex].playerPrefsName),GUILayout.Width(100));
	PlayerPrefs.SetInt(difficultyModes[modeIndex].playerPrefsName,Mathf.CeilToInt(GUILayout.HorizontalSlider(PlayerPrefs.GetInt(difficultyModes[modeIndex].playerPrefsName),1,maxResetScore,GUILayout.Width(100))));
	GUILayout.EndHorizontal();
	//
	GUILayout.EndVertical();
	GUILayout.EndHorizontal();
}

Compartilhar este post


Link para o post
Compartilhar em outros sites

É Simples!

 

Segue exemplo:

  
<?php

$email = 'nabil@hotmail.com';

#======APENAS O NOME========#
$name = preg_replace('/@.*?$/', '', $email);
echo $name;

#======EMAIL COMPLETO========#
echo '<pre>';
preg_match('/[a-z\d._%+-]+@[a-z\d.-]+\.[a-z]{2,4}\b/i', $email,$match);
print_r($match) ;

?>

Compartilhar este post


Link para o post
Compartilhar em outros sites

em qual parte coloco? e qual deleto por favor

<?php
 
    function Connect(){
        //Set global variables so they can be used in this function
        global $hostName; global $userName;
        global $password; global $database;
        $status = mysql_connect($hostName,$userName,$password); //Attempt to connect to Database
     
        if(!$status){echo 'Server Not Found'; exit;} //Hosting Server not found
        if(!@mysql_select_db($database)){echo 'Database Not Found'; exit;} //Database not found
        return $status; //Return link on established connection
    }
    function CheckKey($hash,$name){  //Check weather Md5 hash matches
        global $secretKey;
        $checkHash = md5($name.$secretKey);
        if(strcmp($checkHash,$hash) == 0){
            return 'pass'; //hash matches
        }else{
            return 'fail'; //hash failed
        }
    }
    function CleanInput($input){ //Sanitize user input
        $cleanInput = mysql_real_escape_string($input); //Use string escape
        if(preg_match('/[^@.a-z_\-0-9\s]/i',$cleanInput) == 1){ // Using regular expression
            echo 'Bad Input ==> ' . $input; exit; //Failed, exit to prevemt sql injection hacks
        }
        return $cleanInput; //Return clean input
    }
?>

Compartilhar este post


Link para o post
Compartilhar em outros sites

@nabilfx,

 

Essa é a função que limpa os dados enviados "Sanitize user input"

function CleanInput($input){ //Sanitize user input
        $cleanInput = mysql_real_escape_string($input); //Use string escape
        if(preg_match('/[^@.a-z_\-0-9\s]/i',$cleanInput) == 1){ // Using regular expression
            echo 'Bad Input ==> ' . $input; exit; //Failed, exit to prevemt sql injection hacks
        }
        return $cleanInput; //Return clean input
    }

Veja como funciona e adicione o que eu postei da maneira que achar melhor.

 

 

Lembrando que a intenção do fórum é ajudar e não entregar a solução pronta.

 

 

Abraço =)

Compartilhar este post


Link para o post
Compartilhar em outros sites

coloquei o script assim, mais da um erro. Posso te mandar o packague que comprei na unity store, pra vc ver?

function CleanInput($input){ //Sanitize user input        $email = 'nabil@hotmail.com';                #======APENAS O NOME========#        $name = preg_replace('/@.*?$/', '', $email);        echo $name;                #======EMAIL COMPLETO========#        echo '<pre>';        preg_match('/[a-z\d._%+-]+@[a-z\d.-]+\.[a-z]{2,4}\b/i', $email,$match);        print_r($match) ;            ?>

No mysql os email esta se registrando, deve ser o dis[play que tem algo errado?

 

 

mira.png

Compartilhar este post


Link para o post
Compartilhar em outros sites

  • Conteúdo Similar

    • Por Rafael_Ferreira
      Não consigo carregar a imagem do captcha do meu formulário. Foi testado com o xampp e easyphp. Também não carregou a imagem de outros captcha. 
       
       
    • Por luiz monteiro
      Olá, tudo bem?
       
      Estou melhorando meu conhecimento em php e mysql e, me deparei com o seguinte. A tabela da base de dados tem um campo do tipo varchar(8) o qual armazena números. Eu não posso alterar o tipo desse campo. O que preciso é fazer um select para retornar o números que contenham zeros a direita ou a esquerda.
      O que tentei até agora
       
      Ex1
      $busca = $conexao->prepare("select campo form tabela where (campo = :campo) ");
      $busca->bindParam('campo', $_REQUEST['campo_form']);
       
      Se a direita da string $_REQUEST['campo_form'] termina ou inicia com zero ou zeros, a busca retorna vazio.
      Inseri dados numéricos, da seguinte maneira para testar: 01234567;  12345670: 12345678: 12340000... entre outros nessa coluna. Todos os valores que não terminam ou não iniciam com zero ou zeros, o select funciona.
       
       
      Ex2
      $busca = $conexao->prepare("select campo form tabela where (campo = 0340000) ");
      Esse número está cadastrado, mas não retorna.
       
      Ex3
      $busca = $conexao->prepare("select campo form tabela where (campo = '02340001' ) ");
      Esse número está cadastrado, mas não retorna.
       
       
      Ex4
      $busca = $conexao->prepare("select campo form tabela where (campo like 2340000) ");
      Esse número está cadastrado, mas não retorna.
       
      Ex5
      $busca = $conexao->prepare("select campo form tabela where (campo like '12340000') ");
      Esse número está cadastrado, mas não retorna.
       
      Ex6
      $busca = $conexao->prepare("select campo form tabela where (campo like '"12340000"' ) ");
      Esse número está cadastrado, mas não retorna.
       
       
      Ex7
      $busca = $conexao->prepare("select campo form tabela where (campo like :campo) ");
      $busca->bindParam('campo', $_REQUEST['campo_form'])
      Não retorna dados.
       
      O  $_REQUEST['campo_form'] é envio via AJAX de um formulário. 
      Usei o gettype para verificar o post, e ele retorna string.
      Fiz uma busca com número 12345678 para verificar o que o select retorna, e também retrona como string.
       
      Esse tipo de varchar foi usado porque os números que serão gravados nesse campo,  terão zeros a direita ou na esquerda. Os tipos number do mysql não gravam zeros, então estou usando esse. O problema é a busca.
      Agradeço desde já.
       
       
    • Por daemon
      Boa tarde,
       
      Eu tenho uma rotina que faz uma leitura do arquivo .xml de vários sites.

      Eu consigo pegar o tópico e a descrição, e mostrar a imagem que esta na pagina do link.
      Para isso utilizo esta função:
      function getPreviewImage($url) { // Obter o conteúdo da página $html = file_get_contents($url); // Criar um novo objeto DOMDocument $doc = new DOMDocument(); @$doc->loadHTML($html); // Procurar pela tag meta og:image $tags = $doc->getElementsByTagName('meta'); foreach ($tags as $tag) { if ($tag->getAttribute('property') == 'og:image') { return $tag->getAttribute('content'); } } // Se não encontrar og:image, procurar pela primeira imagem na página $tags = $doc->getElementsByTagName('img'); if ($tags->length > 0) { return $tags->item(0)->getAttribute('src'); } // Se não encontrar nenhuma imagem, retornar null return null; } // Uso: $url = "https://example.com/article"; $imageUrl = getPreviewImage($url); if ($imageUrl) { echo "<img src='$imageUrl' alt='Preview'>"; } else { echo "Nenhuma imagem encontrada"; }  
      Mas estou com um problema, esta funcão funciona quando coloco em uma pagina de teste.php. Preciso mostrar em uma página inicial diversas fotos de todos os links. (No caso acima só funciona 1).
    • Por violin101
      Caros amigos, saudações.
       
      Por favor, me permita tirar uma dúvida com os amigos.

      Tenho um Formulário onde o Usuário digita todos os Dados necessários.

      Minha dúvida:
      --> como faço após o usuário digitar os dados e salvar, o Sistema chamar uma Modal ou mensagem perguntando se deseja imprimir agora ?

      Grato,
       
      Cesar
    • Por Carcleo
      Tenho uma abela de usuarios e uma tabela de administradores e clientes.
      Gostaria de uma ajuda para implementar um cadastro
       
      users -> name, login, passord (pronta) admins -> user_id, registratiom, etc.. client -> user_id, registratiom, etc...
      Queria ajuda para extender de user as classes Admin e Client
      Olhem como estáAdmin
      <?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Admin extends User {     use HasFactory;            protected $fillable = [         'name',         'email',         'password',         'registration'     ];      private string $registration;     public function create(         string $name,          string $email,          string $password,         string $registration     )     {         //parent::create(['name'=>$name, 'email'=>$email, 'password'=>$password]);         parent::$name = $name;         parent::$email = $email;         parent::$password = $password;         $this->registration = $registration;     } } User
      <?php namespace App\Models; // use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Illuminate\Database\Eloquent\Relations\BelongsToMany; class User extends Authenticatable {     /** @use HasFactory<\Database\Factories\UserFactory> */     use HasFactory, Notifiable;     static string $name;     static string $email;     static string $password;     /**      * The attributes that are mass assignable.      *      * @var list<string>      */     protected $fillable = [         'name',         'email',         'password',     ];          /**      * The attributes that should be hidden for serialization.      *      * @var list<string>      */     protected $hidden = [         'remember_token',     ];     /**      * Get the attributes that should be cast.      *      * @return array<string, string>      */     protected function casts(): array     {         return [             'email_verified_at' => 'datetime',             'password' => 'hashed',         ];     }          public function roles() : BelongsToMany {         return $this->belongsToMany(Role::class);     }       public function hasHole(Array $roleName): bool     {                 foreach ($this->roles as $role) {             if ($role->name === $roleName) {                 return true;             }         }         return false;     }         public function hasHoles(Array $rolesName): bool     {                 foreach ($this->roles as $role) {             foreach ($rolesName as $rolee) {             if ($role->name === $rolee) {                 return true;             }          }         }         return false;     }         public function hasAbility(string $ability): bool     {         foreach ($this->roles as $role) {             if ($role->abilities->contains('name', $ability)) {                 return true;             }         }         return false;     }     } Como gravar um Admin na tabela admins sendo que ele é um User por extensão?
      Tentei assim mas é claro que está errado...
      public function store(Request $request, Admin $adminModel) {         $dados = $request->validate([             "name" => "required",             "email" => "required|email",             "password" => "required",             "registration" => "required"         ]);         $dados["password"] =  Hash::make($dados["password"]);                  $admin = Admin::where("registration",  $dados["registration"])->first();                  if ($admin)              return                    redirect()->route("admin.new")                             ->withErrors([                                 'fail' => 'Administrador já cadastrados<br>, favor verificar!'                   ]);                            $newAdmin = $adminModel->create(                                    $dados['name'],                                    $dados['email'],                                    $dados['password'],                                    $dados['registration']                                 );         dd($newAdmin);         $adminModel->save();         //$adminModel::create($admin);                  return redirect()->route("admin.new")->with("success",'Cadastrado com sucesso');     }  
×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.