Menu
  • HOME
  • TAGS

Am I safe?? [trying to prevent sql injection] [duplicate]

Tag: php,mysql,security,laravel,pdo

This question already has an answer here:

  • How can I prevent SQL-injection in PHP? 28 answers

I was wondering if I'm safe from SQL injection if I have this in a script:

< script>

    //some stuff

    var item = <?php echo json_oncode($PHPVAR) ?>

    item.replace(/"/,'&quot').replace(/'/,'&#39');

    //do more script stuff with item

< /script>

currently using Laravel (PHP), with PDO Are there anything else that I should be aware of/look out for? (I didn't whitelist/blacklist before submitting to database b/c PDO does that for me from what I understand)

Also I'm asking b/c item is taken from a user input and it dynamically creates HTML using the value of item

Best How To :

The question is somewhat unanswerable (atleast not in a way that will not give you a false sense of security) with the amount of resource provided.

Since you are using PDO I'll go right ahead and say that you ought to be using prepared statements. Injection on a whole primarily lies on how the Web Application handles user input.

Your question should be, "How does this piece of user input interact with my application?" -- ofcourse there isn't a set list of things to do in order to keep yourself protected from (B)SQLi (or other variants of Injection [XSS/LDAP]).

The following are some good resources that will help you out further with regards to SQL Injection on a whole (you need to know how the vulnerability works in general if you want to be able to cover something specific).

OWASP SQL Injection

Acunetix SQL Injection

SQL Injection Cheat Sheet

There isn't much more to specifically answer your question except maybe go deeper into how to handle user input with regards to the code you have provided (which we may but I don't think is required).

mysql_real_escape_string creates \ in server only not in local

php,sql

Your server has magic quotes enabled and your local server not. Remove it with the following sentence set_magic_quotes_runtime(0) As this function is deprecated and it will be deleted in PHP 7.0, I recommend you to change your php.ini with the following sentencies: magic_quotes_gpc = Off magic_quotes_runtime = Off If you...

PHP / MySQLi: How to prevent SQL injection on INSERT (code partially working)

php,mysql,mysqli,sql-injection,sql-insert

In the New PHP code snippet, you are still vulnerable to injections. You are using a prepared statement in the insert part, but you are not actually using the preparations strengths correctly. When creating a prepared statement, you create a query in which you add placeholders instead of the raw...

When I click to the next page on pagination,it goes to 404 error in codeigniter

php,codeigniter,pagination

in config.php $config['base_url'] = ''; $config['index_page'] = ''; in your router $route['news/(:any)'] = 'news/$1'; $route['news'] = 'news'; $route['default_controller'] = 'news/create'; $route['(:any)'] ='pages/view/$1'; and place .htaccess <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L] </IfModule> EDIT 01 <?php $data['title'] = 'Database Details'; $count = $this->news_model->record_count()...

how to multiply two column names using codeigniter validation rule

php,codeigniter,validation

You done need to do anything with your controller. Add this change your view to <script> function calculate() { var myBox1 = document.getElementById('crop_quantity').value; var myBox2 = document.getElementById('per_rate').value; var result = document.getElementById('income_amount'); var myResult = myBox1 * myBox2; result.value = myResult; } window.onload = calculate(); </script> <div class="control-group"> <label class="control-label">Crop Quantity</label>...

Symfony 2 unable to pass entity repository to form

php,forms,symfony2,runtime-error

You have not included the Symfony EnityRepository class at the top of your form file so PHP is looking for it in the same directory as your form class. Hence the error message. Add this to your form class (or qualify EntityRepository inline): use Doctrine\ORM\EntityRepository; ...

RecursiveIteratorIterator to fetch subdirectories

php

I would change if ( $dir->isDir() ) to if ( $dir->isDir() && $dir != $root) to remove the root directory...

Wordpress log out using URL and redirect to specify page

javascript,php,wordpress

Try wp_logout() function use the funtion . if($_GET['logout'] == 1) { ob_start(); error_reporting(0); wp_logout(); $redirect = wp_logout_url(); wp_safe_redirect( $redirect ); } ...

compare today's date with unix timestamp value in database

php,mysql

If I understand correctly you have a unix timestamp in a varchar field and you can't change this. If you compare the unix timestamp directly you will only get results that match the exact second of the timestamp. You can use FROM_UNIXTIME() to convert the timestamp in a date value...

how to escape php code in echo with javascript

javascript,php

You are mixing inline PHP with a PHP command (echo). When you are echoing a string, you do it just like normal, this means you can mix literal strings (the js you are manually typing) and the output of functions (like a json in this case): echo "<script type='text/JavaScript'> var...

Click on link next link should be display on same page

javascript,php,jquery,html,css3

Ok, so i tried to decypher what you meant with your Question. To Clarify: He has this one page setup. inside the div Our Project, there are two Buttons or links Visit more. When clicked, he wants the About Section to be shown. All in all it is impossible for...

PHP Regular Expressions Counting starting consonants in a string

php,regex

This is one way to do it, using preg_match: $string ="SomeStringExample"; preg_match('/^[b-df-hj-np-tv-z]*/i', $string, $matches); $count = strlen($matches[0]); The regular expression matches zero or more (*) case-insensitive (/i) consonants [b-df-hj-np-tv-z] at the beginning (^) of the string and stores the matched content in the $matches array. Then it's just a matter...

Error connecting to MSSQL using PHP

php,sql-server,pdo,odbc,sqlsrv

Change it to: $this->link = new PDO( "sqlsrv:Server={$this->serverName},{$this->port};Database={$this->db};", $this->uid, $this->pwd ); The default SQL Server port is 1433. Note the curly brackets, they allow for class variables....

Trying to rewrite mysql_* to pdo

php,mysql,pdo

I don't know the source of the array $arr = array();, but it is assigned to null before the insert query. So it means, literally you are inserting nothing into the database. So check your array well, maybe it was to be like $arr = array('name'=>'My Name', 'url'=>'url', 'email'=>'my email',...

How can I replace the white rectangle within an image using ImageMagick?

php,image-processing,imagemagick

I think you can locate the shape pretty accurately with a simple threshold, like this: convert image.jpg -threshold 90% result.jpg and you can then do a Canny edge detection like this: convert image.jpg -threshold 90% -canny 0x1+10%+30% result.jpg The next things I would be looking at are, using the -trim...

Retrieve Values As Column

mysql,sql

If types are fixed (just IMPRESSION and CLICK), you could use a query like this: SELECT headline, SUM(tracking_type='IMPRESSION') AS impressions, SUM(tracking_type='CLICK') AS clicks FROM tracking GROUP BY headline ...

How to pass a value from a page to another page in PHP

php

Only values that are sent by a form will be in the GET or POST array. From what you are showing I conclude that you don't want to show the field in your form, so make it hidden. Add this inside your form tag: <input name="price" type="hidden" value="'.$price.'" class="inputClass"> Also,...

Unable to configure Symfony (3rd party) bundle

php,symfony2,rss

I havent tried this bundle yet, but i think you need to tell doctrine that you want to save your newly created feed into the database: $feeds = new Feed; $reader->readFeed($url, $feeds, $date); $em = $this->getDoctrine()->getManager(); $em->persist($feeds); $em->flush(); return $this->render('default/index.html.twig'); UPDATE According to the docs if you want to use...

array and function php

php,arrays

$x and $y are only defined within the scope of the function. The code outside of the function does not know what $x or $y are and therefore will not print them. Simply declare them outside of the function as well, like so: <?php function sum($x, $y) { $z =...

How to register global variable for my Laravel application?

php,laravel,laravel-5

Actually, you should reserve in config/app.php file. Then, you can add In the Service Providers array : 'Menu\MenuServiceProvider', In the aliases array : 'Menu' => 'Menu\Menu', Finally, you need to run the following command; php artisan dump-autoload I assume that you already added this package in composer.json Sorry, I didn't...

php include capitalization on files

php

Your local host must be Windows, that doesn't differentiate between upper and lower case in file names and your web server Unix Based which does, simple as that.

Dynamically select from a dynamically generated dropdown

php,html,select,drop-down-menu

It is because you aren't ending the value attribute, so your selected option becomes <option value="optionvalueselected" -- 'optionvalue' being the value of your selected option, and 'selected' being the attribute you want to set, but won't be set because you never ended value The following should work: <select name="course_id" id="course_id">...

Why am getting this error?: Unknown column 'firstname' in 'field list'

php,database,mysqli

$query = "INSERT INTO `myDatabaseForAll`.`users` (`id`, `firstname`, `lastname`, `username`, `password`) VALUES (NULL, $firstname, $lastname,$username,$password)"; you need single quote around text feilds in sql queries change above query to $query = "INSERT INTO `myDatabaseForAll`.`users` (`id`, `firstname`, `lastname`, `username`, `password`) VALUES (NULL, '$firstname', '$lastname','$username','$password')"; ...

Cant submit form

javascript,php

Your PHP is checking if $_POST['submit'] contains a value. Your form does not contain a form element with the attribute name="submit", so therefore it fails and moves straight to the else statement. If you want to check if the form was posted then you should instead check for: if (!empty($_POST))...

MySQL - How can I know my query is tuned?

mysql,performance,explain

Except for trivial queries, there is no way to know if you have the optimal query & indexes. Nor can you get a metric for how well designed the schema and application are. 3 seconds on a cold system for a 3-way JOIN with "Rows" of 409, 45, 1 is...

Laravel Interfaces

php,laravel,interface,namespaces

In my recent laravel 5 project, I'm used to prepare my logics as Repository method. So here's my current directory structure. For example we have 'Car'. So first I just create directory call it libs under app directory and loaded it to composer.json "autoload": { "classmap": [ "database", "app/libs" //this...

Php Mysql Query not working properly

php,mysql

No need to use union as it will give a lots of duplicate data What you want to achieve can be done with simple left join or inner join SELECT m.issue_name ,m.issue_type , m.priority ,m.status,m.description , m.start_date,m.end_date,m.duration, s.name as server_name,p.name as product_name from mod_networkstatus as m LEFT JOIN tblservers as...

$http.get returns actual php script instead of running it (yeoman, grunt)

php,angularjs,pdo,gruntjs

Change $http.get('/scripts/php/articles.php') to $http.get('http://YOURDOMAIN.COM/scripts/php/articles.php') Off course you need to replace YOURDOMAIN.COM with localhost or any other domain you are using....

If I export my database with phpmyadmin will it lock my tables or take my database down?

mysql,database,phpmyadmin

The answer is no, tables won't be locked, database won't be down. But, if your database is large and it takes long time to backup it, you can sometimes expect performance degradation(slow SQL queries from your application).

I Want to fetch SQL Records in MySQL of current Year

mysql

Try this: SELECT count(enq.`enquiryId`), Month(enq.`date`), Year(enq.`date`) FROM enquiry enq WHERE Year(enq.date)=somevalue --2015 for example GROUP BY MONTH(enq.`date`) ...

Include both local and server at the same time

php

file_exists: http://php.net/manual/en/function.file-exists.php is_dir: http://php.net/manual/en/function.is-dir.php Best way to do that is use dirname(__FILE__) which gets the directory's full path of the current file in ether unix of windows format. Then we use realpath() which conveniently returns false if file does not exist. All you have to do is specify a relative...

How to search images by name inside a folder?

php,mysql,image

This looks like a job for glob, which returns an array of file names matching a specified pattern. I'm aware of the other answer just posted, but let's provide an alternative to regex. According to the top comment on the docs page, what you could do is something like this:...

Mixing

php

Set short_open_tag=On in php.ini And restart your Apache server...

How to call MySQL view in Struts2 or Hibernate

java,mysql,hibernate,java-ee,struts2

You can simply create an Entity, that's mapping the database view: @Entity public class CustInfo { private String custMobile; private String profession; private String companyName; private Double annualIncome; } Make sure you include an @Id in your view as well, if that's an updatable view. Then you can simply use...

Codeigniter PHP Mailer, Sender Info

php,email,codeigniter-2,phpmailer,contact-form

Don't do that. It's effectively forging the from address and will fail SPF checks. Instead, use your own address as the From address, and add the submitted address as a reply-to address. In PHPMailer: $mail->From = '[email protected]'; $mail->addReplyTo($POST['emailfrom']); ...

Time format conversion with PHP

php,time

<?php $duration="1H10M5S"; $display=str_replace(array('H','M','S'), array(' Hour(s) ',' Minute(s) ',' Seconds'), $duration); echo $display; Output 1 Hour(s) 10 Minute(s) 5 Seconds Fiddle...

php redirection working in chorme but not on firefox

php,google-chrome,mozilla

have you tried using header('location') function? example : <?php if (isset($_POST['putonline'])) { $query = "UPDATE user SET status= '1' WHERE id= '$new_id'"; $result = $cid-> query($query); if ($result== TRUE) { header("location:EidEmp.php"); die(); } else { echo "Failed"; } } ?> Edited : Maybe Change Your header function with javascript function...

Pull information from SQL database and getting login errors

php,sql,database

change $username = "'rylshiel_order"; to $username = "rylshiel_order"; and you should be through. You are passing on an extra single quote here. ...

How do I display my mysql table column headers in my php/html output?

php,html,mysql,table,data

Note: You can just make a single file out of it to achieve your wanted output Use mysql_real_escape_string() to sanitize the passed-on value to prevent SQL injections You should use mysqli_* instead of the deprecated mysql_* API Form them in a single file like this (display.php): <html> <form method="post" name="display"...

MySQL Query returning strange values

php,mysql

You need to join by account_id and also question_id SELECT * FROM `quiz_questions` INNER JOIN `quiz_answers` ON `quiz_questions`.`account_id` = `quiz_answers`.`account_id` AND `quiz_questions`.`question_id` = `quiz_answers`.`question_id` WHERE `quiz_questions`.`account_id` = '1840979156127491' ORDER BY `quiz_questions`.`question_id` ASC LIMIT 5 ...

How to modify CodeIgniter calendar to handle multiple events per day?

php,codeigniter,calendar

If you want to show all four boxes for the dates which has data, try to change the get_calendar_data() foreach as below, $content = ""; $lastDay = -1; $index = 0; foreach ($query->result() as $row) { if($lastDay != intval(substr($row->date_cal, 8, 2))){ if($index > 0 ){ if($content != ''){ $cal_data[$lastDay] =...

Composer dump-autoload gives preg_match error

php,composer-php,autoload

autoload should be moved out of require-dev: { "require-dev":{ "phpunit/phpunit":"4.5.*" }, "autoload":{ "psr-0":{ "Yii\\":"yii-1.1.14.f0fee9/" } } } You can test your composer.json file using composer validate. Your original file returned: ./composer.json is invalid, the following errors/warnings were found: require-dev.autoload : invalid value, must be a string containing a version constraint...

access the json encoded object returned by php in jquery

php,jquery,ajax,json

Try: $.ajax({ url: "functions.php", dataType: "JSON", data: {id: id}, type: 'POST', success: function(json){ for(var i=0;i<json.length;i++){ alert(json[i].fname); } } }); ...

Laravel 4.2 Sending email error

php,email,laravel,laravel-4

Closures work just like a regular function. You need to inject your outer scope variables into function's scope. Mail::send('invoices.mail', array($pinvoices,$unpinvoices), function($message) use ($email) { $message->to($email , 'Name')->subject('your invoices '); }); ...