Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts
Thursday, November 17, 2016
Export & Import all mysql databases at one time.
2:33 PM
Most of the times you want to keep a backup of all of your MySQL databases. Suppose you have more than 100 MySQL databases & you want to export all of them at the same time and again import all of them into MySQL server at one time. How would you do that?
The answer ....
Go to the command line :
How to export all mysql databases at once:
mysqldump -u root -p --all-databases > alldb.sql
Edit the root and enter the password for root to export all the databases to alldb.sql file, notice that this file will be generated at the same place where you are working in shell from.
How to Import all mysql databases at once:
mysql -u root -p < alldb.sql
Edit the user root if necessary and enter the password for root to import all the databases from alldb.sql file to mysql.
Good luck!!
Monday, November 14, 2016
Too many redirects occurred trying to open localhost - Joomla! [SOLVED]
5:18 PM
How to fix Too many redirects occurred Error in Joomla!
Too many redirects occurred trying to open http://mywebsite.com/Joomla_3/index.php " how do I fix this?
Fix:
You need to change the home menu item so it points to a published article. Assuming the home menu item is of type single article and is not pointing to a published article.
Issue with migrating? Include logs/joomla_update.php in your report!
Blank screen? Verify pagesource for HTML code (javascript error)
Installation failing on populating database? Install with set_time_limit(0)
Document your customizations!
Blank screen? Verify pagesource for HTML code (javascript error)
Installation failing on populating database? Install with set_time_limit(0)
Document your customizations!
PHP Send data to browser, but keep executing script in background
5:12 PM
How to echo or print PHP script while its still executing?
ob_flush writes the buffer. In other words, ob_flush tells PHP to give Apache (or nginx/lighttpd/whatever) the output and then for PHP to forget about it. Once Apache has the output, it does whatever it wants with it. (In other words, after ob_flush it's out of your control whether or not it gets immediately written to the browser).
So, short answer: There's no guaranteed way to do that.
Just a guess, you're likely looking for AJAX. Whenever people are trying to manipulate when page content loads as you're doing, AJAX is almost always the correct path.
If you want to continue a task in the background, you can use ignore_user_abort, however, that is often not the optimal approach. You essentially lose control over that thread, and in my opinion, a web server thread is not where heavy processing belongs.
I would try to extract it out of the web facing stuff. This could mean a cron entry or just spawning a background process from inside of PHP (a process that though started from inside of script execution will not die with the script, and the script will not wait for it to finish before dying).
If you do go that route, it will mean that you can even make some kind of status system if necessary. Then you could monitor the execution and give the user periodic updates on the progress. (Technically you could make a status system with a ignore_user_abort-ed script too, but it doesn't seem as clean to me.)
I have done this in the past and this is how I solved it:
ob_start();
/*
* Generate your output here
*/
// Ignore connection-closing by the client/user
ignore_user_abort(true);
// Set your timelimit to a length long enough for your script to run,
// but not so long it will bog down your server in case multiple versions run
// or this script get's in an endless loop.
if (
!ini_get('safe_mode')
&& strpos(ini_get('disable_functions'), 'set_time_limit') === FALSE
){
set_time_limit(60);
}
// Get your output and send it to the client
$content = ob_get_contents(); // Get the content of the output buffer
ob_end_clean(); // Close current output buffer
$len = strlen($content); // Get the length
header('Connection: close'); // Tell the client to close connection
header("Content-Length: $len"); // Close connection after $len characters
echo $content; // Output content
flush(); // Force php-output-cache to flush to browser.
// See caveats below.
// Optional: kill all other output buffering
while (ob_get_level() > 0) {
ob_end_clean();
}
Saturday, October 6, 2012
Best way to Avoid MySQL injection in PHP
11:38 PM
SQL Injection, a commonly method used by majority of hackers and which is the cause for about 70% of the hack's all over the cyber warfare. Mostly hacker uses this (mysql injection) vulnerability to exploit the website and gain access to the server thus through Admin panel or obtain the sensitive information including Credit Cards etc as well.
So here i am going to explain you the best practices you should do while writing code!
First of all keep it in mind, never ever trust a user's input, you are on to your own! So it is the very first thing to keep in mind that whatever a user sends, intentionally or unintentionally, if it is not properly sanitized and exploits a vulnerability which could be possibly a MySQL injection or even a XSS attack, could let hackers give a way to intrude.
Bullet Points:
Best way to Avoid MySQL Injections.
Any comments are welcome :) Share your practices with me as well.
SQL Injections are Common nowadays! |
So here i am going to explain you the best practices you should do while writing code!
First of all keep it in mind, never ever trust a user's input, you are on to your own! So it is the very first thing to keep in mind that whatever a user sends, intentionally or unintentionally, if it is not properly sanitized and exploits a vulnerability which could be possibly a MySQL injection or even a XSS attack, could let hackers give a way to intrude.
Bullet Points:
- When you are going to embed strings in HTML for example when you "print" or when you "echo" you should default to escape the string using htmlspecialchars(); .
- Never trust user's input, always sanitize the user input by first sanitizing it properly and before performing any SQL query, this can be achieved by mysql_real_escape_string($parameter).Where $parameter is the input you are about to filter.
- Disable Magic Quotes.
- Use prepared statements and parameterized queries, always filter the user inputs properly,thoroughly and strictly.
- Don't through mysql_error() to the user,don't even let them know something happened out there,most of the people use it like, die(mysql_error()); . Instead of just throwing this error straight away to the user you can write your custom messages, prepare some log files or even create a mail() function so you get notified whenever someone tries to pull something off the routine.
- Log,Log,Log, always log the errors and warning messages, turn off error reporting on live websites and enable only when debugging or during development process or testing phases.
- Be Self-Aware, never give up, always try up-to-date security precautions, create difficult random passwords for database, encrypt all the user's information in the database and set a value of 666 to the files which contains configuration for mySQL access.
- Keep your server patched and updated, use only latest software's, if you are on a shared hosting server, and find something which is not fine, notify the Administrator.
- If you are using some software's like WordPress,Joomla,Drupal or any other free and open-source or even other software's,keep them updates, most of these products have built-in update notifiers in the Admin panel's and most of the time they update themselves with a single click.
Best way to Avoid MySQL Injections.
You basically have two options to achieve this:
- Using PDO:
$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name'); $stmt->execute(array(':name' => $name)); foreach ($stmt as $row) { // do something with $row }
- Using mysqli:
$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?'); $stmt->bind_param('s', $name); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { // do something with $row }
PDO
Note that when using
PDO
to access a MySQL database real prepared statements are not used by default. To fix this you have to disable the emulation of prepared statements. An example of creating a connection using PDO is:$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'pass');
$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
In the above example the error mode isn't strictly necessary, but it is advised to add it. This way the script will not stop with a
Fatal Error
when something goes wrong. And gives the developer the chance to catch
any error(s) (which are throw
ed as PDOException
s.
What is mandatory however is the
setAttribute()
line, which tells PDO to disable emulated prepared statements and use real prepared statements. This makes sure the statement and the values aren't parsed by PHP before sending it the the MySQL server (giving a possible attacker no chance to inject malicious SQL).
Although you can set the
charset
in the options of the constructor it's important to note that 'older' versions of PHP (< 5.3.6) silently ignored the charset parameter in the DSN.Explanation
What happens is that the SQL statement you pass to
prepare
is parsed and compiled by the database server. By specifying parameters (either a ?
or a named parameter like :name
in the example above) you tell the database engine where you want to filter on. Then when you call execute
the prepared statement is combined with the parameter values you specify.
The important thing here is that the parameter values are combined with the compiled statement, not a SQL string. SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database. So by sending the actual SQL separately from the parameters you limit the risk of ending up with something you didn't intend. Any parameters you send when using a prepared statement will just be treated as strings (although the database engine may do some optimization so parameters may end up as numbers too, of course). In the example above, if the
$name
variable contains 'Sarah'; DELETE * FROM employees
the result would simply be a search for the string "'Sarah'; DELETE * FROM employees", and you will not end up with an empty table.
Another benefit with using prepared statements is that if you execute the same statement many times in the same session it will only be parsed and compiled once, giving you some speed gains.
Oh, and since you asked about how to do it for an insert, here's an example (using PDO):
$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)');
$preparedStatement->execute(array(':column' => $unsafeValue));
Any comments are welcome :) Share your practices with me as well.
♥ Happy Coding ♥
How to Validate a URL in PHP? [Easy]
7:41 PM
Starting from PHP 5.2 we have bunch of built-in functions which makes it easier for programmers to perform small functions without writing up code for them,one of such function is filter_var(); , using filter_var().
We can validate emails and URL's easily with just a few steps or you can say only 4-5 lines of code, so lets say you want to validate a URL using filter_var() you can do it as follow:
To use this function simply use the following code :
if(checkurl("http://www.google.com")) {
echo 'URL is correct';
//continue....
}else{
echo 'URL is incorrect';
//through an error!
}
Simple isn't? And if you don't want to use the complete function,you can simply use the filter_var("Your URL here!", FILTER_VALIDATE_URL); .
Comments are welcome, and once more you must have PHP >= 5.2.
We can validate emails and URL's easily with just a few steps or you can say only 4-5 lines of code, so lets say you want to validate a URL using filter_var() you can do it as follow:
function checkurl($url)
return filter_var($url, FILTER_VALIDATE_URL);
}
To use this function simply use the following code :
if(checkurl("http://www.google.com")) {
echo 'URL is correct';
//continue....
}else{
echo 'URL is incorrect';
//through an error!
}
Simple isn't? And if you don't want to use the complete function,you can simply use the filter_var("Your URL here!", FILTER_VALIDATE_URL); .
Comments are welcome, and once more you must have PHP >= 5.2.
♥ Happy Coding.! ♥
PHP Get time difference in Hour,Minutes or Seconds.
7:08 PM
Starting from PHP 5.3,it has became so much easy for the programmers to code less and get more because of the in-built classes that came with it.One of from those classes is the DateTime() class which made it lot more easier for using it in many different ways,one of the most required technique from this class is getting the difference of time in Years,months,days,hours or even seconds :).
So lets start, we have a scenario that we want to actually get the difference between a past date,suppose a past date you want to compare it with the current date, initiate the class:
First we need to get the today's time, Year-Month-Date Hour:Minute:Seconds , so in this way we can totally compare the past time and get the actual difference in every possible way :). Next,
Now you can get the years,months,days,hours or minutes and vice versa, by the following method:
So, now you can actually get the total difference in anyway you want,even in seconds.
Comments are welcome, hope you have learnt these small tricks,and in a way they are allot more helpful!
So lets start, we have a scenario that we want to actually get the difference between a past date,suppose a past date you want to compare it with the current date, initiate the class:
$today = new DateTime(date('y-m-d h:m:s'));
First we need to get the today's time, Year-Month-Date Hour:Minute:Seconds , so in this way we can totally compare the past time and get the actual difference in every possible way :). Next,
$pastDate = $today->diff(new DateTime('2012-09-11 10:25:00'));
Next we are going to compare the past time with the current, so using the DateTime()'s method diff() , since $pastDate is a DateInterval object.
echo $pastDate->y; //return the difference in Year(s).
echo $pastDate->m; //return the difference in Month(s).
echo $pastDate->d; //return the difference in Day(s).
echo $pastDate->h; //return the difference in Hour(s).
echo $pastDate->i; //return the difference in Minute(s)
echo $pastDate->s; //return the difference in Second(s).
So, now you can actually get the total difference in anyway you want,even in seconds.
Comments are welcome, hope you have learnt these small tricks,and in a way they are allot more helpful!
♥ Happy Coding! ♥
Thursday, October 4, 2012
PHP Get Process Creation Time.
11:55 PM
So, this is a very quick and dirty method that i am going to tell you today, actually whenever on windows platform if you need to get the time of when is a certain process is created, actually nobody needs it that much only but if you are creating system layered applications with PHP and are going deep inside digging through the WinCOM Objects.
Anyway, i won't recommend this method but may be any of you finds it useful in any scenarios,so here we go:
First of all you need to know, what actually are you trying to achieve,the process in Windows can be accessed using two ways, either by using the PID (Process Identifier) or the name (Image Name). So i will tell you the both ways you can actually get to that by how, here is the code :
So, what is actually happening above, its quite simple, i am using COM objects with PHP, even though you should use them with great precautions because they can be huge security risk if exploited so you should have to be really careful playing around with these.
Just change the $pid = "9252"; to any PID you like,and if you want to know the process creation time using its name,than it is quite simple as well, just change the ProcessId with ProcessName in $wmi->ExecQuery("SELECT * FROM Win32_Process WHERE ProcessId ='".$pid."'"); and you are good to go.
There could be many more methods out but i used this one for my own usage and it quite helped me. But as before i would recommend you to thoroughly tighten the security if you are using COM objects on Enterprise level.
Happy Coding!
Anyway, i won't recommend this method but may be any of you finds it useful in any scenarios,so here we go:
First of all you need to know, what actually are you trying to achieve,the process in Windows can be accessed using two ways, either by using the PID (Process Identifier) or the name (Image Name). So i will tell you the both ways you can actually get to that by how, here is the code :
$pid = "9252";$wmi = new COM('winmgmts://'); $process = $wmi->ExecQuery("SELECT * FROM Win32_Process WHERE ProcessId ='".$pid."'"); $pDate = floor($process->CreationDate); $formatDate = date_parse($pDate);$time = $formatDate['hour'].':'.$formatDate['minute'].':'.$formatDate['second'];print $time;
So, what is actually happening above, its quite simple, i am using COM objects with PHP, even though you should use them with great precautions because they can be huge security risk if exploited so you should have to be really careful playing around with these.
Just change the $pid = "9252"; to any PID you like,and if you want to know the process creation time using its name,than it is quite simple as well, just change the ProcessId with ProcessName in $wmi->ExecQuery("SELECT * FROM Win32_Process WHERE ProcessId ='".$pid."'"); and you are good to go.
There could be many more methods out but i used this one for my own usage and it quite helped me. But as before i would recommend you to thoroughly tighten the security if you are using COM objects on Enterprise level.
Happy Coding!
Subscribe to:
Posts (Atom)