I'm working on a domain shortening service called "sHTTP". It uses a MySQL database to store the shortened URLs. I can't insert them though.
Here's my code:
function db(){
$link = mysqli_connect('sqlserver', 'user', 'pass', 'db') or die(mysqli_error());
return $link;
}
$url = mysqli_real_escape_string(db(), $_POST['url']);
$ip = $_SERVER['REMOTE_ADDR'];
function checkexists($name){
// check if shttp exists
$q = mysqli_num_rows(mysqli_query(db(),"SELECT name FROM shttp WHERE name = '$name'"));
if($q > 0){
return true;
} else {
return false;
}
}
function generateRandStr($length){
// generate string for placeholder name
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
if(checkexists($name)){
die('sHTTP name exists already!');
}
if($_POST['url'] == ''){
die('No URL entered!');
}
if(!$_POST['name']){
$name = generateRandStr(5);
}else{
$name = mysqli_real_escape_string(db(), $_POST['name']);
}
//THIS IS MY MAIN PROBLEM HERE GUISE
$query = "INSERT INTO shttp(name, url, ip) VALUES ($name, $url, $ip)";
//Y U NO WORKING
$exe = mysqli_query(db(), "INSERT INTO shttp (name, url, ip) VALUES ($name, $url, $ip)");
if(!$exe){
//I'M GETTING THE DIE HALP
die('Error: Could not be processed');
} else {
echo 'sHTTP created!<br>URL: <a href=http://shttp.tk/ '.$name.'>http://shttp.tk/'.$name.'</a>';
}
I'm getting the "Error: Could not be processed" I set up.
Also, my DB table is this:
name varchar(255)
url varchar(255)
ip varchar(255)
I believe that's how I set it up in my code as well.
If anyone can help, I would appreciate it. Thank you for your time.
You need to use quote for the string values as
$query = "INSERT INTO shttp(name, url, ip) VALUES ('$name', '$url', '$ip')" ;
Related
I need to check duplicate files from a path and need to insert the file name in a table if it is new and then insert all records of it accordingly into another table. Do not insert or step forward if file already exists.
Here is my code where i can't bring the file path with '/' into the DB. Can anyone assist? Thanks in advance.
File Path with '/' is not passing using $open = fopen('$cont[$x]','r');
<?php
//include ("connection.php");
$conn = new mysqli('localhost','root','','demo');
$path = _DIR_ . DIRECTORY_SEPARATOR ."*.{txt}";
$cont = glob($path, GLOB_BRACE);
//print_r($content);
$arrlength = count($cont);
for($x = 0; $x < $arrlength; $x++){
// $sql = "INSERT INTO `file_record` (`file_name`) VALUES ('$cont[$x]') ";
$dup = mysqli_query($conn,"SELECT * FROM file_record WHERE file_name = '$cont[$x]' ");
if(mysqli_num_rows($dup)>0)
{
echo "File already Exists";
}
else {
$insert = "INSERT INTO `file_record` (`file_name`) VALUES ('$cont[$x]') ";
// $conn->query($insert);
if (mysqli_query($conn,$insert)) {
$open = fopen('$cont[$x]','r');
while (!feof($open))
{
$content = fgets($open);
$carry = explode(",",$content);
list($name,$city,$postcode,$job_title) = $carry;
$sql = "INSERT INTO `employee` (`name`, `city`, `postcode`, `job_title`) VALUES ('$name','$city','$postcode','$job_title')";
$conn->query($sql);
}
fclose($open);
echo 'inserted';
} else {
echo 'Not inserted';
}
}
}
?>
I try to insert the variable randomString into the table user2 into the column code, but it wont work. All other values are in the table, but the generated string wont. The column code have the type varchar(8). Where is my mistake?
<?php
session_start();
$message = array();
if (!empty($_POST)) {
if(isset($_POST['f']['country']) )
{
$country = $_POST['f']['country'];
}
function generateRandomString($length = 8) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
$randomString = generateRandomString();
if (
empty($_POST['f']['username']) ||
empty($_POST['f']['password']) ||
empty($_POST['f']['password_again']) ||
empty($_POST['f']['email']) ||
empty($_POST['f']['firstname']) ||
empty($_POST['f']['lastname']) ||
empty($_POST['f']['phone']) ||
empty($_POST['f']['town']) ||
empty($_POST['f']['street']) ||
empty($_POST['f']['zip'])
) {
$message['error'] = 'Es wurden nicht alle Felder ausgefüllt.';
} else if ($_POST['f']['password'] != $_POST['f']['password_again']) {
$message['error'] = 'Die eingegebenen Passwörter stimmen nicht überein.';
} else {
unset($_POST['f']['password_again']);
$salt = '';
for ($i = 0; $i < 22; $i++) {
$salt .= substr('./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', mt_rand(0, 63), 1);
}
$_POST['f']['password'] = crypt(
$_POST['f']['password'],
'$2a$10$' . $salt
);
$mysqli = #new mysqli('localhost', '', '', '');
if ($mysqli->connect_error) {
$message['error'] = 'Datenbankverbindung fehlgeschlagen: ' . $mysqli->connect_error;
}
$query = sprintf(
"INSERT INTO user2 (username, password, email, firstname, lastname, phone, town, street, zip, country, code)
SELECT * FROM (SELECT '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s') as new_user
WHERE NOT EXISTS (
SELECT username FROM user2 WHERE username = '%s'
) LIMIT 1;",
$mysqli->real_escape_string($_POST['f']['username']),
$mysqli->real_escape_string($_POST['f']['password']),
$mysqli->real_escape_string($_POST['f']['email']),
$mysqli->real_escape_string($_POST['f']['firstname']),
$mysqli->real_escape_string($_POST['f']['lastname']),
$mysqli->real_escape_string($_POST['f']['phone']),
$mysqli->real_escape_string($_POST['f']['town']),
$mysqli->real_escape_string($_POST['f']['street']),
$mysqli->real_escape_string($_POST['f']['zip']),
$mysqli->real_escape_string($_POST['f']['country']),
$mysqli->real_escape_string($randomString),
$mysqli->real_escape_string($_POST['f']['username'])
);
$mysqli->query($query);
if ($mysqli->affected_rows == 1) {
$message['success'] = 'Neuer Benutzer (' . htmlspecialchars($_POST['f']['username']) . ') wurde angelegt, weiter zur Anmeldung.';
header('Location: http://' . $_SERVER['HTTP_HOST'] . '//login.php');
$_SESSION = array(
'login' => true,
'user' => array(
'username' => $row['username']
)
);
} else {
}
$mysqli->close();
}
}
?>
You are not using function generateRandomString anywhere. I don't understand its purpose quite well right now.
If $randomString has some value (input name in variable), you are looking for
$_POST[$randomString]
If you have input with name randomString, you are looking for
$_POST['randomString']
Anyway, currently you are trying to get value of input named $randomString. I bet you don't have input named like this.
If your variable is in single quotes, it is treated as plain string.
If you are trying just to save random string, use your function
$randomString = generateRandomString();
And save it
$mysqli->real_escape_string($randomString),
Few mistake in your code
1) $randomString = $_POST['$randomString']; change to $randomString = $_POST['randomString'];
2) $mysqli->real_escape_string($_POST['$randomString']), change to $mysqli->real_escape_string($_POST['randomString']),
And you not shows us how you call this function
generateRandomString()
in youe code??
I need to generate a random string when I insert data in my mysql.
I did read about uuid or cast(rand) but I cant find anything that looks like I can use it.
My data comes from a app.
I made a new row called code and made it unik.
I hope you can help me :)
how do I tell my insert to generate a random string to my row code?
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['name']) && isset($_POST['nummer']) && isset($_POST['description']) && isset($_POST['dato'])) {
$name = $_POST['name'];
$nummer = $_POST['nummer'];
$description = $_POST['description'];
$dato = $_POST['dato'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
mysql_set_charset("utf8");
// mysql inserting a new row
$result = mysql_query("INSERT INTO products(name, nummer, description, dato) VALUES('$name', '$nummer', '$description', '$dato')");
Ok this is what I got so far
if (isset($_POST['name']) && isset($_POST['nummer']) && isset($_POST['description']) && isset($_POST['dato'])) {
$name = $_POST['name'];
$nummer = $_POST['nummer'];
$description = $_POST['description'];
$dato = $_POST['dato'];
// $code = $_POST['code'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
function generate_random_string($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
// mysql inserting a new row
$result = mysql_query("INSERT INTO products(name, nummer, description, dato, code) VALUES('$name', '$nummer', '$description', '$dato', '$randomString')");
But I dont get anything in my code row?
return $randomString;
$random_str = generate_random_string(10);
}
// mysql inserting a new row
$result = mysql_query("INSERT INTO products(name, nummer, description, dato, code) VALUES('$name', '$nummer', '$description', '$dato', '$random_str')");
You can generate a random number using PHP's function rand :
// code = rand($min , $max); for example
code = rand(100000, 999999); // will generate a number between 100000 and 999999
// then add the column to your insert if it belongs to the same table or
// make another query to insert the code if it belongs to a different table
note that you can use the current time and md5 function to make stronger unique codes.
Also, if you like to take this logic to your database, try to create a trigger that will runs after each insert.
Good luck.
You can try the code below:
function generate_random_string($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
echo generate_random_string(15); // define amount of string length in parametre
Source: PHP random string generator
If you use random number as Random String code is below:
$number = range(100000,999999);
shuffle($number);
$ran_string = $number[0];
echo $ran_string;
How can I use another function to check if the email is in the right format ([number of symbols]#[number of symbols].[number of symbols]) and if it's unique while adding it using the insertUser? (All info is read from a .txt file).
Code:
class User{
function randomPassword($length = 8){
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
function insertUser($firstName, $lastName, $email){
global $DB;
$DB->query("INSERT INTO `users` (`fname`, `lname`, `password` , `email`) values ('$firstName', '$lastName', '" . randomPassword() . "', '$email') ");
}
In the index file:
$USER = new User();
$data = readData();
foreach($data as $nr => $user){
$USER->insertUser($user['first_name'], $user['last_name'], $user['email']);
}
Call as $this->randomPassword();
Email validation
function checkEmail($email) {
if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])
?*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/",$email)){
list($username,$domain)=split('#',$email);
if(!checkdnsrr($domain,'MX')) {
return false;
}
return true;
}
return false;
}
To insert the random string you should do this :
Change the insertUser function to :
function insertUser($firstName, $lastName, $email){
global $DB;
$DB->query("INSERT INTO `users` (`fname`, `lname`, `password` , `email`) values ('$firstName', '$lastName', '" . $this->randomPassword() . "', '$email') ");
}
I have a function that generates a random combination.
my function looks like this:
function random_gen($length) {
$random= "";
srand((double)microtime()*1000000);
$char_list = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$char_list .= "abcdefghijklmnopqrstuvwxyz";
$char_list .= "1234567890";
// Add the special characters to $char_list if needed
for($i = 0; $i < $length; $i++)
{
$random .= substr($char_list,(rand()%(strlen($char_list))), 1);
}
return $random;
}
$new_url = random_gen(6);
Now i would like to have a while-loop that checks if $new_url already exist in my database...
And then insert the result like this:
mysql_query("INSERT INTO lank (url, code) VALUES ('$url', '$new_url')");
I got everything to work except the while-loop. and i just cant figure out how to do it...
define your code field as UNIQUE in your database
generate a code and run an INSERT
check with mysql_affected_rows() if the INSERT actually happened or not (i.e. code already present)
saves you a SELECT query
while ( true ) {
$new_url = random_gen(6);
mysql_query("INSERT INTO lank (url, code) VALUES ('$url', '$new_url')");
if ( mysql_affected_rows() )
break;
}
Use this random_generator
function random_gen($length) {
$characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$string = '';
for ($i = 0; $i < $length; $i++) {
$string .= $characters[rand(0, strlen($characters) - 1];
}
return $string;
}
You don't need a while loop, just perform a query
mysql_query("SELECT COUNT(*) FROM lank WHERE code = {$new_url}");
It's pretty straight forward:
$sql = "SELECT COUNT(*) as num FROM lank WHERE code='{$new_url}'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
while($row['num'] > 0) {
$new_url = random_gen(6);
$sql = "SELECT COUNT(*) as num FROM lank WHERE code='{$new_url}'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
}
This should work, without repeating code:
while(true) {
$new_url = random_gen(6);
$sql = "SELECT COUNT(*) FROM lank WHERE code='{$new_url}'";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
if (!$row[0])
break;
}
Use the uniqid() function instead. It will always generate a random result.
If you need more security (i.e.: you don't want adjacent values), simply hash the output: sha1(uniqid()).