How to insert url into MySQL database using PHP?

I have a form that submits information to a database. The form includes 3 inputs - name, description and URL. All three work fine and present data to the database, but the input url only works if the text entered does NOT include http://

, which is not what I want. I need to enablehttp://

Currently, if I submit the form without http://

, it goes through fine, but if it includes http://

, I get a 406 invalid error.

I have read several articles about mysqli_real_escape_string

but I have been unable to get it to work. I currently have the following:

$dbh = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$code_name = filter_var($_POST['code_name'], FILTER_SANITIZE_STRING);
$code_desc = filter_var($_POST['code_desc'], FILTER_SANITIZE_STRING);
$code_dest = filter_var($_POST['code_dest'], FILTER_SANITIZE_STRING);

$stmt = $dbh->prepare("INSERT INTO qr_codes (code_name, code_desc, code_dest ) VALUES (:code_name, :code_desc, :code_dest )");

$stmt->bindParam(':code_name', $code_name, PDO::PARAM_STR);
$stmt->bindParam(':code_desc', $code_desc, PDO::PARAM_STR, 40);
$stmt->bindParam(':code_dest', $code_dest, PDO::PARAM_STR, 40);

$stmt->execute();

      

Here is the form:

<form id="newQR" method="post" action="create-qr-code.php" onSubmit="return validateForm();">
    <ul class="new-qr-form">
        <li><label>Name</label><br><input id="code_name" name="code_name" type="text" class="form-control" ></li>
        <li><label>Description</label><br><input id="code_desc" name="code_desc" type="text" class="form-control" ></li>
        <li><label>Destination</label><br><input id="code_dest" name="code_dest" type="text" class="form-control" ></li>
        <li class="img-src-preview"><label>Preview Source</label><br><input value="test" id="code_img_src" name="code_img_src" type="text" class="form-control" ></li>
    </ul>
</form>

      

Any ideas on why it won't allow the url?

+3


source to share


2 answers


A simple workaround would be to simply remove the http: // onSubmit in validateForm (). Or you can code it somehow, for example with encodeURIComponent ().



0


source


$url= filter_var($_POST['url'], FILTER_SANITIZE_URL);

      



USE FILTER_SANITIZE_URL-Constant for your url

0


source







All Articles