TutoBlog

6 noviembre 2018

Sort arrays in PHP

Filed under: General — joan16v @ 12:20
$array = array(3, 5, 2, 8);

Applicable sort functions:

sort
rsort
asort
arsort
natsort
natcasesort
ksort
krsort

Anuncios

Parse JSON with PHP

Filed under: General — joan16v @ 12:18
$string = file_get_contents("/home/test.json");
$json_a = json_decode($string, true);

foreach ($json_a as $person_name => $person_a) {
    echo $person_a['status'];
}

Parse XML in PHP

Filed under: General — joan16v @ 12:16
$xml = simplexml_load_string($xml_string);
$json = json_encode($xml);
$array = json_decode($json,TRUE);

Fix Headers already sent error in PHP

Filed under: General — joan16v @ 12:14

No output before sending headers!
Functions that send/modify HTTP headers must be invoked before any output is made. summary ⇊ Otherwise the call fails:

Warning: Cannot modify header information – headers already sent (output started at script:line)

Some functions modifying the HTTP header are:

header / header_remove
session_start / session_regenerate_id
setcookie / setrawcookie
Output can be:

Unintentional:

Whitespace before
The UTF-8 Byte Order Mark specifically
Previous error messages or notices
Intentional:

print, echo and other functions producing output
Raw sections prior <?php code.

Stackoverflow

Prevent SQL injection in PHP

Filed under: General — joan16v @ 12:11

Having this:

$unsafe_variable = $_POST['user_input']; 

mysql_query("INSERT INTO `table` (`column`) VALUES ('$unsafe_variable')");

You have to do this:

$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name); // 's' specifies the variable type => 'string'

$stmt->execute();

$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // do something with $row
}

Check if a string contains a specific word in PHP

Filed under: General — joan16v @ 12:09
$a = 'How are you?';

if (strpos($a, 'are') !== false) {
    echo 'true';
}

Crea un blog o un sitio web gratuitos con WordPress.com.