Failed to load resource 406 (Not Acceptable) - php

I saw this error today, yesterday everything was good.
Issue based on hosting or i don't know when i run the files on the localhost everythings fine and working correctly. Maybe there is problem with hosting secure ?
If anyone has any tips I would be very grateful.
Failed to load resource: the server responded with a status of 406 (Not Acceptable)
<?php
if( isset($_SESSION["DATAGLOBAL"][0]) && !empty($_SESSION["DATAGLOBAL"][0]) )
$C->LANGUAGE = $_SESSION["DATAGLOBAL"][0];
$this->load_langfile('inside/dashboard.php');
$this->load_langfile('global/global.php');
if( $this->user->is_logged )
{
$D->is_logged = 1;
$errored = 0;
$txterror = '';
$action = 0;
$wsee = -1;
$txtstatus = $txtvalueatach = $txttypeattach = $id_wall = '';
$typeattach = $posted_in = 0;
if( isset($_POST["wseep"]) && $_POST["wseep"] != -1 )
{
$wsee = $this->db1->e($_POST["wseep"]);
}
if( $wsee == -1 )
{
$errored = 1;
$txterror = $this->lang('global_post_txterror6');
}
if( $errored == 0 )
{
if( isset($_POST["pin"]) && $_POST["pin"] != '' )
{
$posted_in = $this->db1->e($_POST["pin"]);
}
if( isset($_POST["idw"]) && $_POST["idw"] != '' )
{
$id_wall = $this->db1->e($_POST["idw"]);
}
if( isset($_POST["newstatus"]) && $_POST["newstatus"] != '' )
{
$txtstatus = $this->db1->e(htmlspecialchars($_POST["newstatus"]));
}
if( isset($_POST["typeattach"]) && $_POST["typeattach"] != 0 )
{
$typeattach = $this->db1->e($_POST["typeattach"]);
}
if( isset($_POST["atach-value"]) && $_POST["atach-value"] != '' )
{
$txtvalueatach = $this->db1->e($_POST["atach-value"]);
}
$withattach = 0;
$endtxtatach = '';
$codep = uniqueCode(11, 1, 'posts', 'code');
if( $typeattach == 1 || $typeattach == 2 || $typeattach == 3 || $typeattach == 4 || $typeattach == 5 || $typeattach == 6 || $typeattach == 7 || $typeattach == 8 || $typeattach == 9 )
{
switch( $typeattach )
{
case 1:
$images_post = $_FILES['images_post'];
$numphotos = count($images_post['name']);
if( $images_post['name'][0] )
{
if( $numphotos > $C->NUM_PHOTOS_POST )
{
$errored = 1;
$txterror = $this->lang('global_post_txterror1') . ' ' . $C->NUM_PHOTOS_POST;
}
else
{
$photos = array();
$tmp_photos = array();
for( $i = 0; $i < $numphotos; $i++ )
{
if( $images_post['size'][$i] > $C->SIZE_PHOTO || $images_post['size'][$i] == 0 )
{
$errored = 1;
$txterror = $this->lang('global_post_txterror2') . ': ' . $images_post['name'][$i];
break;
}
$loadedtype = $images_post['type'][$i];
if( $loadedtype == "image/jpeg" || $loadedtype == "image/gif" || $loadedtype == "image/png" || $loadedtype == "video/m4v" )
{
switch( $loadedtype )
{
case "image/jpeg":
$uploadfile .= '.jpg';
$mfilename .= '.jpg';
break;
case "image/gif":
$uploadfile .= '.gif';
$mfilename .= '.gif';
break;
case "video/m4v":
$uploadfile .= '.gif';
$mfilename .= '.gif';
break;
case "image/png":
$uploadfile .= '.png';
$mfilename .= '.png';
break;
}
}
else
{
$errored = 1;
$txterror = $this->lang('global_post_txterror3') . ': ' . $images_post['name'][$i];
break;
}
$tmp_photos[] = $images_post['tmp_name'][$i];
$photos[] = $codep . '-' . $i . $extens;
}
if( $errored == 0 )
{
foreach( $photos as $key => $fname )
{
move_uploaded_file($tmp_photos[$key], '../' . $C->FOLDER_PHOTOS . $fname);
$thumbnail = new SmartImage('../' . $C->FOLDER_PHOTOS . $fname, true);
$thumbnail->mycrop($C->widthPhotoThumbail, $C->widthPhotoThumbail, 'center');
$thumbnail->saveImage('../' . $C->FOLDER_PHOTOS . 'min1/' . $fname);
$thumbnail->close();
}
unset($mythumb);
$txttypeattach = 'photo';
}
$endtxtatach = implode(',', $photos);
}
}
break;
case 2:
if( !empty($txtvalueatach) )
{
if( substr($txtvalueatach, 0, 20) == "https://youtube.com/" || substr($txtvalueatach, 0, 24) == "https://www.youtube.com/" || substr($txtvalueatach, 0, 16) == "www.youtube.com/" || substr($txtvalueatach, 0, 12) == "youtube.com/" || substr($txtvalueatach, 0, 19) == "http://youtube.com/" || substr($txtvalueatach, 0, 23) == "http://www.youtube.com/" || substr($txtvalueatach, 0, 16) == "http://youtu.be/" )
{
parse_str(parse_url($txtvalueatach, PHP_URL_QUERY), $my_array_of_vars);
if( substr($txtvalueatach, 0, 16) == 'http://youtu.be/' )
{
$endtxtatach = str_replace('http://youtu.be/', 'yt:', $txtvalueatach);
}
else
{
$endtxtatach = 'yt:' . $my_array_of_vars['v'];
}
}
elseif( substr($txtvalueatach, 0, 17) == "http://vimeo.com/" || substr($txtvalueatach, 0, 21) == "http://www.vimeo.com/" || substr($txtvalueatach, 0, 18) == "https://vimeo.com/" || substr($txtvalueatach, 0, 22) == "https://www.vimeo.com/" || substr($txtvalueatach, 0, 14) == "www.vimeo.com/" || substr($txtvalueatach, 0, 10) == "vimeo.com/" )
{
$endtxtatach = 'vm:' . (int) substr(parse_url($txtvalueatach, PHP_URL_PATH), 1);
}
else
{
$errored = 1;
$txterror = $this->lang('global_post_txterror4');
}
if( !empty($endtxtatach) )
{
$withattach = 1;
$typeattach = 2;
$txttypeattach = 'video';
}
}
break;
case 3:
if( !empty($txtvalueatach) )
{
if( substr($txtvalueatach, 0, 23) == "https://soundcloud.com/" || substr($txtvalueatach, 0, 27) == "https://www.soundcloud.com/" || substr($txtvalueatach, 0, 22) == "http://soundcloud.com/" || substr($txtvalueatach, 0, 22) == "https://m.soundcloud.com/" || substr($txtvalueatach, 0, 22) == "http://soundcloud.com/" || substr($txtvalueatach, 0, 22) == "http://www.soundcloud.com/" || substr($txtvalueatach, 0, 15) == "soundcloud.com/" || substr($txtvalueatach, 0, 19) == "www.soundcloud.com/" )
{
$endtxtatach = 'sc:' . parse_url($txtvalueatach, PHP_URL_PATH);
}
else
$endtxtatach = $this->db1->e(htmlspecialchars(trim(clearnl($txtvalueatach))));
if( !empty($endtxtatach) )
{
$withattach = 1;
$typeattach = 3;
$txttypeattach = 'music';
}
}
break;
case 4:
if( !empty($txtvalueatach) )
{
$endtxtatach = $this->db1->e(htmlspecialchars(trim(clearnl($txtvalueatach))));
if( !empty($endtxtatach) )
{
$withattach = 1;
$typeattach = 4;
$txttypeattach = 'map';
}
}
break;
case 5:
if( !empty($txtvalueatach) )
{
$endtxtatach = $this->db1->e(htmlspecialchars(trim(clearnl($txtvalueatach))));
if( !empty($endtxtatach) )
{
$withattach = 1;
$typeattach = 5;
$txttypeattach = 'visited';
}
}
break;
case 6:
if( !empty($txtvalueatach) )
{
$endtxtatach = $this->db1->e(htmlspecialchars(trim(clearnl($txtvalueatach))));
if( !empty($endtxtatach) )
{
$withattach = 1;
$typeattach = 6;
$txttypeattach = 'food';
}
}
break;
case 7:
if( !empty($txtvalueatach) )
{
$endtxtatach = $this->db1->e(htmlspecialchars(trim(clearnl($txtvalueatach))));
if( !empty($endtxtatach) )
{
$withattach = 1;
$typeattach = 7;
$txttypeattach = 'movie';
}
}
break;
case 8:
if( !empty($txtvalueatach) )
{
$endtxtatach = $this->db1->e(htmlspecialchars(trim(clearnl($txtvalueatach))));
if( !empty($endtxtatach) )
{
$withattach = 1;
$typeattach = 8;
$txttypeattach = 'book';
}
}
break;
case 9:
if( !empty($txtvalueatach) )
{
$endtxtatach = $this->db1->e(htmlspecialchars(trim(clearnl($txtvalueatach))));
if( !empty($endtxtatach) )
{
$withattach = 1;
$typeattach = 9;
$txttypeattach = 'game';
}
}
break;
}
}
}
if( $errored == 0 )
{
if( empty($txtstatus) && empty($endtxtatach) )
{
$errored = 1;
$txterror = $this->lang('global_post_txterror5');
}
else
{
$idwall = $this->network->idwall($id_wall, $posted_in);
$r = $this->db1->query("INSERT INTO posts SET code='" . $codep . "', iduser=" . $this->user->id . ", post='" . $txtstatus . "', typepost='" . $txttypeattach . "', posted_in=" . $posted_in . ", id_wall=" . $idwall . ",valueattach='" . $endtxtatach . "', who_see=" . $wsee . ", whendate='" . time() . "'");
$idpost = $this->db1->insert_id();
$this->db1->query('INSERT INTO activities SET iduser=' . $this->user->id . ', action=3, iditem=' . $idpost . ', typeitem=1, date="' . time() . '"');
if( $idwall != $this->user->id )
{
$this->db1->query("UPDATE users SET num_posts=num_posts+1 WHERE iduser=" . $this->user->id . " LIMIT 1");
$this->db1->query("UPDATE users SET num_posts_inwall=num_posts_inwall+1 WHERE iduser=" . $idwall . " LIMIT 1");
}
else
{
$this->db1->query("UPDATE users SET num_posts=num_posts+1, num_posts_inwall=num_posts_inwall+1 WHERE iduser=" . $this->user->id . " LIMIT 1");
}
preg_match_all('~([#])([^\s#]+)~', str_replace(array( '\r', '\n' ), ' ', $txtstatus), $matchedHashtags);
if( !empty($matchedHashtags[0]) )
{
foreach( $matchedHashtags[0] as $match )
{
$hashtag = str_replace('#', '', $match);
$hashtag = $this->db1->e(($hashtag));
$this->db1->query("INSERT INTO trends SET iduser=" . $this->user->id . ", trend='" . $hashtag . "', idpost=" . $idpost . ", whendate='" . time() . "'");
}
}
}
}
if( $errored == 1 )
{
$message = '0: ' . $txterror;
}
else
{
$onepost = $this->db2->fetch('
SELECT DISTINCT idpost, posts.code as pcode, whendate, posted_in, id_wall, typepost, valueattach, numlikes, numcomments, post, who_see, username, firstname, lastname, avatar, users.iduser as uiduser, users.code as ucode, verified
FROM posts, users
WHERE
(users.iduser=posts.iduser)
AND idpost=' . $idpost . '
LIMIT 1');
$D->isaPage = $D->isOnlyOne = $D->isaGroup = $D->isWithOther = 0;
if( $onepost->posted_in == 0 )
{
if( $onepost->uiduser == $onepost->id_wall )
{
$D->isOnlyOne = 1;
$D->codeUser = $onepost->ucode;
$D->userName = $onepost->username;
$D->nameUser = (empty($onepost->firstname) || empty($onepost->lastname)) ? $onepost->username : ($onepost->firstname . ' ' . $onepost->lastname);
$D->userAvatar = $onepost->avatar;
}
if( $onepost->uiduser != $onepost->id_wall )
{
$D->isWithOther = 1;
$D->codeUser = $onepost->ucode;
$D->userName = $onepost->username;
$D->nameUser = (empty($onepost->firstname) || empty($onepost->lastname)) ? $onepost->username : ($onepost->firstname . ' ' . $onepost->lastname);
$D->userAvatar = $onepost->avatar;
$wallsec = $this->network->infoBasicWall($onepost->posted_in, $onepost->id_wall);
$D->other_code = $wallsec->code;
$D->other_userName = $wallsec->username;
$D->other_nameUser = (empty($wallsec->firstname) || empty($wallsec->lastname)) ? $wallsec->username : ($wallsec->firstname . ' ' . $wallsec->lastname);
}
}
if( $onepost->posted_in == 1 )
{
$D->isaPage = 1;
$D->idPage = $onepost->id_wall;
$thePage = $this->db2->fetch('SELECT code, url, avatar_page, title FROM pages WHERE idpage=' . $D->idPage . ' LIMIT 1');
$D->pUserName = $thePage->url;
$D->pCode = $thePage->code;
$D->pAvatar = $thePage->avatar_page;
$D->pTitle = stripslashes($thePage->title);
}
if( $onepost->posted_in == 2 )
{
$D->isaGroup = 1;
}
$D->a_date = $onepost->whendate;
$D->codeUser = $onepost->ucode;
$D->valueattach = $onepost->valueattach;
$D->typepost = $onepost->typepost;
$D->idpost = $onepost->idpost;
$D->codepost = $onepost->pcode;
$D->idUser = $onepost->uiduser;
$D->numlikes = $onepost->numlikes;
$D->numcommentstotal = $onepost->numcomments;
$D->post = stripslashes($onepost->post);
$D->whosee = $onepost->who_see;
$D->post = str_replace('<script>', '< script >', $D->post);
$D->post = str_replace('</script>', '< \/script >', $D->post);
$txtpostreturn = '';
$txtpostreturn = $this->load_template('__one-post.php', FALSE);
unset($onePost);
$txtpostreturn = str_replace('<script>', '<script>', $txtpostreturn);
$txtpostreturn = str_replace('</script>', '</script>', $txtpostreturn);
$message = '1: ' . $txtpostreturn;
}
}
?>
<script language="javascript" type="text/javascript">
window.top.window.endPostear( '<?php echo $this->db1->e($message); ?>' );
</script>

From the documentation:
The HTTP 406 Not Acceptable client error response code indicates that a response matching the list of acceptable values defined in Accept-Charset and Accept-Language cannot be served.
Looks like you are using some language files, so maybe that's your issue. What do the server logs say?

Related

What is the best approach to scn directories inside condition

Inside a condition, I have some element in static.
$group == 'modules_account_customers'
for example
I would like to make that in dynamic (read).
How to proceed?
Below you an example of this condition.
All the directories start with modules_
I suppose I must use a function like a glob and select all the _modules. I don't know exactly how to start.
Any idea.
Tk.
foreach ( $modules_array as $module ) {
$class = basename($module, '.php');
// module language
if ( !class_exists($class) ) {
if ( MODE_VENTE_PRIVEE == 'true' && $customer->isLoggedOn() ) {
$modules_boxes = 'modules_boxes';
} elseif (MODE_VENTE_PRIVEE == 'true' && !$customer->isLoggedOn ) {
$modules_boxes = '';
} else {
$modules_boxes = 'modules_boxes';
}
if ($group == $modules_boxes ||
$group == 'modules_account_customers' ||
$group == 'modules_account_history_info' ||
$group == 'modules_advanced_search' ||
$group == 'modules_blog' ||
$group == 'modules_blog_content' ||
$group == 'modules_create_account' ||
) { .....}
}
}
I started by this and allow to display the directories inside an array :
public function getReadModulesDefaultDirectories($source_folder = 'modules_') {
$dir = $this->_directoryTemplateSources . '/' . $this->_template . '/' . $this->_codeSail . '/' . $this->_directoryModules;
$module_directories = array_diff(glob($dir . $source_folder . '*', GLOB_ONLYDIR), $exclude);
$result = [];
foreach ($module_directories as $value) {
$result[] = str_replace($dir, '', $value);
}
return $result;
}

how to execute multi requete pdo mysql

i don't know how execute multi requete sql
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_SESSION['pseudo']) && !empty($_SESSION['pseudo']) && isset($_SESSION['user_id']) && !empty($_SESSION['user_id'])) {
$id = trim(htmlspecialchars($_SESSION['user_id']));
$pseudo = trim(htmlspecialchars($_SESSION['pseudo']));
$stmt->$connect->prepare('SELECT id,pseudo,jeton FROM users WHERE id=:id AND pseudo=:pseudo');
$stmt->execute(array(
':id' => $id,
':pseudo' => $pseudo
));
$row = $stmt->fetch();
if ($_SESSION['pseudo'] == $row['pseudo'] && $_SESSION['user_id'] == $row['id']) {
// Files Image profil
$avatarName = $_FILES['avatarCouverture']['name'];
$avatarTmp = $_FILES['avatarCouverture']['tmp_name'];
$avatarSize = $_FILES['avatarCouverture']['size'];
$avatarType = $_FILES['avatarCouverture']['type'];
$extension = array(
'jpg',
'jpeg',
'png'
);
$avatarExplode = explode('.', $avatarName);
$avatarEnd = end($avatarExplode);
$avatarLower = strtolower($avatarEnd);
$saveIdUser = trim(htmlspecialchars($_SESSION['user_id']));
$saveIdUserNew = filter_var($saveIdUser, FILTER_SANITIZE_NUMBER_INT);
$avatar = rand(0, 100000) . '_' . date('Y-m-d H-i-s') . '_' . $saveIdUserNew;
if (isset($avatarName) && !empty($avatarName)) {
if ($avatarSize < 8000000) {
if (in_array($avatarLower, $extension)) {
if (isset($avatarTmp) && !empty($avatarTmp)) {
$image = getimagesize($avatarTmp);
if ($image['mime'] === 'image/jpeg') {
$imageSrc = imagecreatefromjpeg($avatarTmp);
} elseif ($image['mime'] === 'image/png') {
$imageSrc = imagecreatefrompng($avatarTmp);
} else {
$imageSrc = false;
}
// modifier size image
if ($imageSrc !== false) {
$imageWidth = 60;
$imageHeight = 60;
if ($image[0] >= $imageWidth && $image[1] >= $imageHeight) {
$imageFinale = $imageSrc;
} else {
$newWidth[0] = $imageWidth;
$newHeight[1] = $imageHeight;
$imageFinale = imagecreatetruecolor($newWidth[0], $newHeight[1]);
imagecopyresampled($imageFinale, $imageSrc, 0, 0, 0, 0, $newWidth[0], $newHeight[1], $image[0], $image[1]);
}
$target = imagejpeg($imageFinale, 'upload/avatarPost/' . $avatar . '.jpg');
move_uploaded_file($avatarTmp, $target);
} // ! == false
}
}
}
}
$stmt = $connect->prepare('INSERT INTO users(avatarcouverture) VALUES(:avatarne) ');
$stmt->execute(array(
":avatarne" => $avatar
));
//header('Location: profil.php');
}
}
}
?>
I think the issue was the initial prepared statement assignment
$stmt->$connect->prepare('SELECT id,pseudo,jeton FROM users WHERE id=:id AND pseudo=:pseudo');
it should be perhaps more like this.
$stmt = $connect->prepare('SELECT id, pseudo, jeton FROM users WHERE id=:id AND pseudo=:pseudo');
The final sql query surely should only be run if there is a successfully added avatar? Reorganised a little whilst looking for issues - hope it helps.
if( $_SERVER['REQUEST_METHOD'] === 'POST' ) {
if( !empty( $_SESSION['pseudo'] ) && !empty( $_SESSION['user_id'] ) ) {
$id = trim( htmlspecialchars( $_SESSION['user_id'] ) );
$pseudo = trim( htmlspecialchars($_SESSION['pseudo'] ) );
/*
Assign the prepared statement as a variable
*/
$stmt = $connect->prepare('SELECT id, pseudo, jeton FROM users WHERE id=:id AND pseudo=:pseudo');
if( !$stmt )exit('Failed to prepare sql');
$stmt->execute( array(
':id' => $id,
':pseudo' => $pseudo
)
);
$row=$stmt->fetch();
if( $_SESSION['pseudo'] == $row['pseudo'] && $_SESSION['user_id'] == $row['id'] ) {
$avatarName = $_FILES['avatarCouverture']['name'];
$avatarTmp = $_FILES['avatarCouverture']['tmp_name'];
$avatarSize = $_FILES['avatarCouverture']['size'];
$avatarType = $_FILES['avatarCouverture']['type'];
$extension = array('jpg','jpeg','png');
$avatarLower = strtolower( pathinfo($avatarName,PATHINFO_EXTENSION ) );
$saveIdUser = trim( htmlspecialchars( $_SESSION['user_id'] ) );
$saveIdUserNew = filter_var( $saveIdUser, FILTER_SANITIZE_NUMBER_INT );
$avatar = rand(0,100000).'_'.date('Y-m-d H-i-s').'_'.$saveIdUserNew;
if( !empty( $avatarName ) ) {
if( $avatarSize < 8000000 ) {
if( in_array( $avatarLower, $extension ) ){
if( !empty( $avatarTmp ) ) {
$image = getimagesize( $avatarTmp );
if( $image['mime'] === 'image/jpeg' ) {
$imageSrc = imagecreatefromjpeg( $avatarTmp );
} elseif( $image['mime']==='image/png' ) {
$imageSrc = imagecreatefrompng( $avatarTmp );
} else {
$imageSrc = false;
}
// modifier size image
if( $imageSrc !== false ) {
$imageWidth = 60;
$imageHeight = 60;
if( $image[0]>= $imageWidth && $image[1]>= $imageHeight ) {
$imageFinale = $imageSrc ;
} else {
$newWidth[0] = $imageWidth;
$newHeight[1] = $imageHeight;
$imageFinale = imagecreatetruecolor( $newWidth[0], $newHeight[1] );
imagecopyresampled( $imageFinale, $imageSrc, 0,0,0,0, $newWidth[0], $newHeight[1], $image[0], $image[1] );
}
$target = imagejpeg( $imageFinale,'upload/avatarPost/'.$avatar.'.jpg' );
move_uploaded_file( $avatarTmp ,$target );
$stmt=$connect->prepare('INSERT INTO users( avatarcouverture ) VALUES( :avatarne )');
if( !$stmt )exit('Failed to prepare sql');
$stmt->execute( array( ":avatarne"=> $avatar ) );
}
}
}
}
}
//header('Location: profil.php');
}
}
}

Short display images by date newer to older in PHP

I'm using the following function to read a directory and show images as a gallery, it works really well, but I need to display images ordering by date from newer to older.
Knows anyone how to do it using this method?
function getPictures() {
global $page, $per_page, $has_previous, $has_next;
if ( $handle = opendir("saved/2013") ) {
$lightbox = rand();
$count = 0;
$skip = $page * $per_page;
if ( $skip != 0 )
$has_previous = true;
while ( $count < $skip && ($file = readdir($handle)) !== false ) {
if ( !is_dir($file) && ($type = getPictureType($file)) != '' )
$count++;
}
$count = 0;
while ( $count < $per_page && ($file = readdir($handle)) !== false ) {
if ( !is_dir($file) && ($type = getPictureType($file)) != '' ) {
if ( ! is_dir('saved/2013') ) {
mkdir('saved/2013');
}
$strFileName = "saved/2013/".$file;
echo '<div id="imagen-t">';
echo '<p>' .date( "D d M Y g:i A", filemtime($strFileName)) . "</p>";
echo '<p><img src=saved/2013/'.$file.' alt="" width="220" /></p>';
echo '</div>';
$count++;
}
}
while ( ($file = readdir($handle)) !== false ) {
if ( !is_dir($file) && ($type = getPictureType($file)) != '' ) {
$has_next = true;
break;
}
}
}
}
Here is the result:
http://www.espigoplatja.com/whale/galeria/
Salutations,
Gonzalo
Have you looked at USort: http://php.net/manual/en/function.usort.php
It allows you to sort an array by values with user defined comparison function.
An example
<?php
function my_sort($a,$b)
{
if ($a==$b) return 0;
return ($a<$b)?-1:1;
}
$a=array(4,2,8,6);
usort($a,"my_sort");
$arrlength=count($a);
for($x=0;$x<$arrlength;$x++)
{
echo $a[$x];
echo "<br>";
}
?>
By the way I try implementing the sample you provide and it displays the same date for all imagenes:
# SETTINGS
$per_page = 6;
$page = $_GET['page'];
$has_previous = false;
$has_next = false;
function getPictures() {
global $page, $per_page, $has_previous, $has_next;
if ( $handle = opendir("saved/2013") ) {
$lightbox = rand();
$count = 0;
$skip = $page * $per_page;
if ( $skip != 0 )
$has_previous = true;
while ( $count < $skip && ($file = readdir($handle)) !== false ) {
if ( !is_dir($file) && ($type = getPictureType($file)) != '' )
$count++;
}
function my_sort($a,$b)
{
if ($a==$b) return 0;
return ($a<$b)?-1:1;
}
$count = 0;
while ( $count < $per_page && ($file = readdir($handle)) !== false ) {
if ( !is_dir($file) && ($type = getPictureType($file)) != '' ) {
if ( ! is_dir('saved/2013') ) {
mkdir('saved/2013');
}
$a=array($file);
usort($a,"my_sort");
//$strFileName = "saved/2013/".$file;
$strFileName = "saved/2013/".$a[$x];
echo '<div id="imagen-t">';
//echo '<p>' .date( "D d M Y g:i A", filemtime($strFileName)) . "</p>";
echo '<p>' .date( "D d M Y g:i A", filemtime($strFileName)) . "</p>";
echo '<p><img src=saved/2013/'.$file.' alt="" width="220" /></p>';
echo '</div>';
$count++;
}
}
while ( ($file = readdir($handle)) !== false ) {
if ( !is_dir($file) && ($type = getPictureType($file)) != '' ) {
$has_next = true;
break;
}
}
}
}

Sort images by exif data in php

I'm new to php and I'm trying to figure out how to sort images by exif creation date. The code below is the one from this tutorial I followed: Simple Php Gallery Pagination
I just modified a little bit to retrieve exif data
I'm looking for a method without database, the goal is to have a paginated gallery (and now it is paginated) sorted with newest first
function getPictures() {
global $page, $per_page, $has_previous, $has_next, $DirFoto, $DirThumb;
if ( $handle = opendir($DirFoto) ) {
echo '<ul id="pictures">';
$count = 0;
$skip = $page * $per_page;
if ( $skip != 0 )
$has_previous = true;
while ( $count < $skip && ($file = readdir($handle)) !== false ) {
if ( !is_dir($file) && ($type = getPictureType($file)) != '' )
$count++;
}
while ( $count < $per_page && ($file = readdir($handle)) !== false ) {
if ( !is_dir($file) && ($type = getPictureType($file)) != '' ) {
$exif = exif_read_data("$DirFoto/$file", 0, true);
if ( ! is_dir($DirThumb) ) {
mkdir($DirThumb);
}
if ( ! file_exists($DirThumb.'/'.$file) ) {
makeThumb( $file, $type );
}
echo '<li><a href="'.$DirFoto.'/'.$file.'" title="Photo taken on '.date("F d Y, H:i:s", strtotime($exif['IFD0']['DateTime'])).'">';
echo '<img src="'.$DirThumb.'/'.$file.'" alt="'.date("F d Y, H:i:s", strtotime($exif['IFD0']['DateTime'])).'"/>';
echo '</a></li>';
$count++;
}
}
echo '</ul>';
while ( ($file = readdir($handle)) !== false ) {
if ( !is_dir($file) && ($type = getPictureType($file)) != '' ) {
$has_next = true;
break;
}
}
}
}
I rationalized a bit the whole code, and this is my result:
$ScriptsHead = '
<link type="text/css" media="screen" rel="stylesheet" href="./stile.css"/>
<link type="text/css" rel="stylesheet" href="./js/photoswipe.css"/>
<script type="text/javascript" src="./js/jquery-1.8.3.js"></script>
<script type="text/javascript" src="./js/klass.min.js"></script>
<script type="text/javascript" src="./js/code.photoswipe-3.0.5.min.js"></script>
<script type="text/javascript" src="./js/miophotoswipe.js"></script>
';
function getPictures() {
global $page, $per_page, $has_previous, $has_next, $DirFoto, $DirThumb;
if ( $handle = opendir($DirFoto) ) {
$skip = $page * $per_page;
$images = array(); # empty data structure
while(($file = readdir($handle)) !== false ) {
if($file == '..' || $file == '.' || is_dir($file) || getPictureType($file) == '')
continue;
# only for images
$exif = exif_read_data("$DirFoto/$file", 0, true);
$date = $exif['IFD0']['DateTime']; # everything you like to be ordered
$images[$file] = $date; # associate each file to its date
}
asort($images); # sort the structure by date
echo '<ul id="pictures">';
if ( $skip != 0 )
$has_previous = true;
$count = -1;
foreach ($images as $file => $fileDate) {
$count ++;
if($count < $skip)
continue;
if($count >= $skip + $per_page) {
$has_next = true;
break;
}
if ( ! is_dir($DirThumb) ) {
mkdir($DirThumb);
}
if ( ! file_exists($DirThumb.'/'.$file) ) {
makeThumb( $file, $type );
}
echo '<li><a href="'.$DirFoto.'/'.$file.'" title="Photo taken on '.date("F d Y, H:i:s", strtotime($fileDate)).'">';
echo '<img src="'.$DirThumb.'/'.$file.'" alt="'.date("F d Y, H:i:s", strtotime($fileDate)).'"/>';
echo '</a></li>';
}
echo '</ul>';
}
}
function getPictureType($file) {
$split = explode('.', $file);
$ext = $split[count($split) - 1];
if ( preg_match('/jpg|jpeg/i', $ext) ) {
return 'jpg';
} else if ( preg_match('/png/i', $ext) ) {
return 'png';
} else if ( preg_match('/gif/i', $ext) ) {
return 'gif';
} else {
return '';
}
}
function makeThumb( $file, $type ) {
global $max_width, $max_height, $DirFoto, $DirThumb;
if ( $type == 'jpg' ) {
$src = imagecreatefromjpeg($DirFoto.'/'.$file);
} else if ( $type == 'png' ) {
$src = imagecreatefrompng($DirFoto.'/'.$file);
} else if ( $type == 'gif' ) {
$src = imagecreatefromgif($DirFoto.'/'.$file);
}
if ( ($oldW = imagesx($src)) < ($oldH = imagesy($src)) ) {
$newW = $oldW * ($max_width / $oldH);
$newH = $max_height;
} else {
$newW = $max_width;
$newH = $oldH * ($max_height / $oldW);
}
$new = imagecreatetruecolor($newW, $newH);
imagecopyresampled($new, $src, 0, 0, 0, 0, $newW, $newH, $oldW, $oldH);
if ( $type == 'jpg' ) {
imagejpeg($new, $DirThumb.'/'.$file);
} else if ( $type == 'png' ) {
imagepng($new, $DirThumb.'/'.$file);
} else if ( $type == 'gif' ) {
imagegif($new, $DirThumb.'/'.$file);
}
imagedestroy($new);
imagedestroy($src);
}
/* echo phpinfo(); */
?>
Since the code reads through the directory and outputs HTML as it goes, you will have to change it up a bit to do what you want. I suggest first reading the filenames into an array and call exif_read_data for each file read.
If you key the array by the filename and the value of the array is the exif creation date, you can then call asort() to sort the array by creation date. If a file doesn't have a valid exif creation date, perhaps you could just use the modification time of the file on the server.
Once the array is sorted in the proper order, you could change the following while loop
while ( $count < $per_page && ($file = readdir($handle)) !== false ) {
to be
while ( $count < $per_page && ($file = array_shift($sorted_files)) !== false ) {
where $sorted_files is the array of sorted files. Hope that helps, if not I can try to write up an example.
Sorry I can't try this solution right now, but it should be something like:
<?php
function getPictures() {
global $page, $per_page, $has_previous, $has_next, $DirFoto, $DirThumb;
if ( $handle = opendir($DirFoto) ) {
$images = array(); # empty data structure
while(($file = readdir($handle)) !== false ) {
if ( !is_dir($file) && ($type = getPictureType($file)) != '' )
# only for images
$exif = exif_read_data("$DirFoto/$file", 0, true);
$date = $exif['IFD0']['DateTime']; # everything you like to be ordered
$images[$file] = $date; # associate each file to its date
}
}
asort($images); # sort the structure by date
echo '<ul id="pictures">';
$skip = $page * $per_page;
if ( $skip != 0 )
$has_previous = true;
$count = 0;
while ( $count < $skip && ($file = array_shift($images)) !== false ) {
if ( !is_dir($file) && ($type = getPictureType($file)) != '' )
$count++;
}
# $count = 0;# (???)
while ( $count < $per_page && ($file = array_shift($images)) !== false ) {
$exif = exif_read_data("$DirFoto/$file", 0, true); # it could be avoided
if ( ! is_dir($DirThumb) ) {
mkdir($DirThumb);
}
if ( ! file_exists($DirThumb.'/'.$file) ) {
makeThumb( $file, $type );
}
echo '<li><a href="'.$DirFoto.'/'.$file.'" title="Photo taken on '.date("F d Y, H:i:s", strtotime($exif['IFD0']['DateTime'])).'">';
echo '<img src="'.$DirThumb.'/'.$file.'" alt="'.date("F d Y, H:i:s", strtotime($exif['IFD0']['DateTime'])).'"/>';
echo '</a></li>';
$count++;
}
echo '</ul>';
while ( ($file = readdir($handle)) !== false ) {
if ( !is_dir($file) && ($type = getPictureType($file)) != '' ) {
$has_next = true;
break;
}
}
}
}
?>
Please give me a feedback on that.
Cheers,
Riccardo
The code works now, if I mouseover the tooltip shows me the right date but no thumbnails or images are loaded.
In my first question I omitted the last two functions, this is my current update code:
<?php
$page = $_GET['page'];
$has_previous = false;
$has_next = false;
function getPictures() {
global $page, $per_page, $has_previous, $has_next, $DirFoto, $DirThumb;
if ( $handle = opendir($DirFoto) ) {
$images = array();
while(($file = readdir($handle)) !== false ) {
if ( !is_dir($file) && ($type = getPictureType($file)) != '' )
$exif = exif_read_data("$DirFoto/$file", 0, true);
$date = $exif['IFD0']['DateTime'];
$images[$file] = $date;
}
}
asort($images);
echo '<ul id="pictures">';
$skip = $page * $per_page;
if ( $skip != 0 )
$has_previous = true;
$count = 0;
while ( $count < $skip && ($file = array_shift($images)) !== false ) {
if ( !is_dir($file) && ($type = getPictureType($file)) != '' )
$count++;
}
while ( $count < $per_page && ($file = array_shift($images)) !== false ) {
$exif = exif_read_data("$DirFoto/$file", 0, true);
if ( ! is_dir($DirThumb) ) {
mkdir($DirThumb);
}
if ( ! file_exists($DirThumb.'/'.$file) ) {
makeThumb( $file, $type );
}
echo '<li><a href="'.$DirFoto.'/'.$file.'" title="Photo taken on '.date("F d Y, H:i:s", strtotime($exif['IFD0']['DateTime'])).'">';
echo '<img src="'.$DirThumb.'/'.$file.'" alt="'.date("F d Y, H:i:s", strtotime($exif['IFD0']['DateTime'])).'"/>';
echo '</a></li>';
$count++;
}
echo '</ul>';
while ( ($file = readdir($handle)) !== false ) {
if ( !is_dir($file) && ($type = getPictureType($file)) != '' ) {
$has_next = true;
break;
}
}
}
function getPictureType($file) {
$split = explode('.', $file);
$ext = $split[count($split) - 1];
if ( preg_match('/jpg|jpeg/i', $ext) ) {
return 'jpg';
} else if ( preg_match('/png/i', $ext) ) {
return 'png';
} else if ( preg_match('/gif/i', $ext) ) {
return 'gif';
} else {
return '';
}
}
function makeThumb( $file, $type ) {
global $max_width, $max_height;
if ( $type == 'jpg' ) {
$src = imagecreatefromjpeg($DirFoto.'/'.$file);
} else if ( $type == 'png' ) {
$src = imagecreatefrompng($DirFoto.'/'.$file);
} else if ( $type == 'gif' ) {
$src = imagecreatefromgif($DirFoto.'/'.$file);
}
if ( ($oldW = imagesx($src)) < ($oldH = imagesy($src)) ) {
$newW = $oldW * ($max_width / $oldH);
$newH = $max_height;
} else {
$newW = $max_width;
$newH = $oldH * ($max_height / $oldW);
}
$new = imagecreatetruecolor($newW, $newH);
imagecopyresampled($new, $src, 0, 0, 0, 0, $newW, $newH, $oldW, $oldH);
if ( $type == 'jpg' ) {
imagejpeg($new, $DirThumb.'/'.$file);
} else if ( $type == 'png' ) {
imagepng($new, $DirThumb.'/'.$file);
} else if ( $type == 'gif' ) {
imagegif($new, $DirThumb.'/'.$file);
}
imagedestroy($new);
imagedestroy($src);
}
?>

Optimizing PHP code (trying to determine min/max/between case)

I know this code-bit does not conform very much to best coding practices, and was looking to improve it, any ideas?
if ($query['date_min'] != _get_date_today())
$mode_min = true;
if ($query['date_max'] != _get_date_today())
$mode_max = true;
if ($mode_max && $mode_min)
$mode = "between";
elseif ($mode_max && !$mode_min)
$mode = "max";
elseif (!$mode_max && $mode_min)
$mode = "min";
else
return;
if ($mode == "min" || $mode == "between") {
$command_min = "A";
}
if ($mode == "max" || $mode == "between") {
$command_max = "B";
}
if ($mode == "between") {
$command = $command_min . " AND " . $command_max;
} else {
if ($mode == "min")
$command = $command_min;
if ($mode == "max")
$command = $command_max;
}
echo $command;
Solution:
$mode_min = ($query['date_min'] != _get_date_today());
$mode_max = ($query['date_max'] != _get_date_today());
if ($mode_min){
$command_min = "A";
}
if ($mode_max) {
$command_max = "B";
}
if ($mode_min && $mode_max) {
$command = $command_min . " AND " . $command_max;
} else {
if ($mode_min)
$command = $command_min;
if ($mode_max)
$command = $command_max;
}
Technically your variables are undefined if the condition is not met, so I would just use:
$mod_min = ($query['date_min'] != _get_date_today());
$mod_max = ($query['date_max'] != _get_date_today());
Apart from that, why are you defining the $mode variable, do you need it somewhere else? If not, you can just use $mod_min and $mod_max in your last set of if statements.
For example:
if ($mode == "min" || $mode == "between")
seems to translate to:
if ($mod_min)
Edit: An edit of your last update:
$command_min = "A";
$command_max = "B";
if ($mode_min && $mode_max) {
$command = $command_min . " AND " . $command_max;
}
elseif ($mode_min){
$command = $command_min;
}
elseif ($mode_max) {
$command = $command_max;
} else {
return;
}

Categories