gallery with next and prev function - php

I'm working on an image gallery as my first real project as of learning php.. The problem I'm not able to get around somehow is using the "previous" button. My "next" function grabs the next 6 images from the folder and posts them to the page, my prev function does this in reverse.. but that's incorrect, can you help? oh, and this code is sloppy beginner code so i'm happy for tips :)
<?php
session_start();
if(session_id() == '') {
$_SESSION["count"] = 0;
}
function PostHTML($id, $file) {
if($id==0) {
echo "<div class=\"item\"><div class=\"well\"><img
class=\"img-responsive\" src=\"$file\" alt=\"\"><p>blahblahblah xxxxxx</p></div></div>";
}else{
echo "<div class=\"item\"><div class=\"well\"><video autoplay
loop class=\"img-responsive\"><source src=\"$file\" type=\"video/mp4\"></video></div></div>";
}
}
function next_img() {
$dir = "images/src/*.*";
$files = array();
$start = $_SESSION["count"];
$end = $_SESSION["count"]+6;
$y=0;
foreach(glob($dir) as $file) {
$files[$y] = $file;
$y++;
}
for($i=$start; $i < $end; $i++){
if(pathinfo($files[$i], PATHINFO_EXTENSION)=="jpg") {
PostHTML(0,$files[$i]);
} else {
PostHTML(1,$files[$i]); }
}
$_SESSION["count"]+=6;
}
function prev_img() {
$dir = "images/src/*.*";
$files = array();
$start = $_SESSION["count"]-1;
$end = $_SESSION["count"]-6;
$y=0;
foreach(glob($dir) as $file) {
$files[$y] = $file; //100 files
$y++;
}
for ($i = $start; $i > $end; $i--) {
if(pathinfo($files[$i], PATHINFO_EXTENSION)=="jpg") {
PostHTML(0,$files[$i]);
} else {
PostHTML(1,$files[$i]);
}
}
$_SESSION["count"]-=6;
}
?>

If i were to do something like this I might create a File Controller class to manage all the file operations i might need.
<?php
class FileController
{
private $_dir = "DIR";
private $files;
private $current;
function__construct()
{
$current = 0;
$files = scandir($_dir); // scans the dir to get a list of file names
if(!$files) echo "Failed To Load Files"; // failed to load files
else
{
$this->file = $files; // objects propery contains all file names in array;
}
}
function PostHTML($fileName) {
$src = $this->_dir + "/" + $fileName;
if(!$fileName)
{
return "<div class=\"item\"><div class=\"well\"><img
class=\"img-responsive\" src=\"$src\" alt=\"\"><p>blahblahblah xxxxxx</p></div></div>";
}
else
{
return "<div class=\"item\"><div class=\"well\"><video autoplay
loop class=\"img-responsive\"><source src=\"$src\" type=\"video/mp4\"></video></div></div>";
}
}
function nextImg()
{
$current = $this->getCurrent();
$end = $current + 6;
$this->setCurrent($end);
$files = $this->files;
$html = "";
for($i = $current; $i<= $end; $i++)
{
$html += postHtml($files[$i]);
}
echo $html;
}
function prevImg()
{
$current = $this->getCurrent();
$end = $current - 6;
$this->setCurrent($end);
$files = $this->files;
$html = "";
for($i = $current; $i>= $end; $i--)
{
$html += postHtml($files[$i]);
}
echo $html;
}
function getCurrent()
{
return $_SESSION['current'];
}
function setCurrent($current)
{
$_SESSION['current'] = $current;
}
}
?>

Related

Linked list from user input php

public $head = null;
public $size = 0;
function push($value, $pos)
{
if($pos>0 && $pos>$this->size)
{
return false;
}
else{
$node = new Node($value);
if ( $pos == 0) {
$node->next=$this->head;
$this->head= $node;
$this->size++;
} else {
$current = $this->head;
for ($i = 0; $i < $pos; $i++) {
$previous = $current;
$current = $current->next;
}
$node->next = $current;
$previous->next = $node;
$this->size++;
}
}
}
function pop($pos)
{
$current=$this->head;
if($pos==0)
{
$this->head=$current->next;
}
else{
for($i=0;$i<$pos;$i++)
{
$previous=$current;
$current=$current->next;
}
$previous->next=$current->next;
}
$this->size--;
}
pushing value is working fine, but poping is not working,excuting pop() method and deleting value from database at the same time.stuck please help.
deleting value from database is easy but the order of linked list get unsorted and push method does not work.
deleting value of pos=0 will delete pos=0 from database and pos will start from pos=1 and push method is not excuting.

Printing prime numbers from an user's input php

I'm trying ta make a program that will ask the user for a number and then show all the prime numbers between 0 to this number in an array.
<?php
class SmallerPrimes{
public function __construct($file){
$this->input_filename = $file;
}
public function Main(){
$smaller_than = (int)$this->readString()[0];
$result = array();
/* YOUR CODE HERE */
function isPrime($n)
{
if ($n <= 1)
return false;
for ($i = 2; $i < $n; $i++)
if ($n % $i == 0)
return false;
return true;
}
function printPrime($n)
{
for ($i = 2; $i <= $n; $i++)
{
if (isPrime($i))
echo $i . " ";
}
}
$n = 7;
printPrime($n);
/*end of your code here */
return $result;
}
public function readString(){
$file = fopen($this->input_filename, "r");
$line = array();
while (!feof($file)){
array_push($line, str_replace(PHP_EOL, "", fgets($file)));
}
return $line;
}
}
$o = new SmallerPrimes($argv[1]);
echo implode(" ", $o->Main()) . PHP_EOL;
This code work, but with a $n fixed.
I don't know how to use an input who ask the user a number
It's a code who verify itself and show us when it's ok
The code that i have to complete is this one (we only have this at first):
class SmallerPrimes{
public function __construct($file){
$this->input_filename = $file;
}
public function Main(){
$smaller_than = (int)$this->readString()[0];
$result = array();
/* YOUR CODE HERE */
return $result;
}
public function readString(){
$file = fopen($this->input_filename, "r");
$line = array();
while (!feof($file)){
array_push($line, str_replace(PHP_EOL, "", fgets($file)));
}
return $line;
}
}
$o = new SmallerPrimes($argv[1]);
echo implode(" ", $o->Main()) . PHP_EOL;
This is your script:
<?php
class SmallerPrimes{
public function __construct($file){
$this->input_filename = $file;
}
public function Main(){
$smaller_than = (int)$this->readString()[0];
$result = array();
function isPrime($n) {
if ($n <= 1) return false;
for ($i = 2; $i < $n; $i++) if ($n % $i == 0) return false;
return true;
}
function printPrime($n) {
for ($i = 2; $i < $n; $i++) if (isPrime($i)) $result[] = $i;
return $result;
}
$result = printPrime($smaller_than);
return $result;
}
public function readString(){
$file = fopen($this->input_filename, "r");
$line = array();
while (!feof($file)){
array_push($line, str_replace(PHP_EOL, "", fgets($file)));
}
return $line;
}}
$o = new SmallerPrimes($argv[1]);
echo implode(" ", $o->Main()) . PHP_EOL;
function getSmallerPrimes($smaller_than) {
if ($smaller_than <= 2) {
return [];
}
$result = [2];
$sqrt = sqrt($smaller_than);
for ($n = 3; $n < $smaller_than; $n += 2) {
$isPrime = true;
foreach($result as $prime) {
if ($n % $prime == 0) {
$isPrime = false;
break;
}
if ($prime > $sqrt) {
break;
}
}
if ($isPrime) {
$result[] = $n;
}
}
return $result;
}
$input = 23;
echo implode(' ', getSmallerPrimes($input));
Result: 2 3 5 7 11 13 17 19

base64 in PHP Otp Library

I trying to make some simple library for encrypting files in PHP with OTP method. My problem is that some chars in decrypted code are different than original. I worked on it almost one week but without result. Is there problem with base64 chars or with encoding/decoding mechanism ?
Many thanks for the answers.
final class Otp
{
private static $charSet = array('+','/','0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L',
'M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r',
's','t','u','v','w','x','y','z');
public static function encryptFile($originalFilePath, $encryptedFilePath, $keyFilePath)
{
if(!self::existsFile($keyFilePath) || !self::existsFile($encryptedFilePath)) {
if($originalFileData = self::existsFile($originalFilePath)) {
$originalFileBase64Data = base64_encode($originalFileData);
$originalFileBase64DataLength = strlen($originalFileBase64Data) - 1;
$originalFileBase64DataArray = str_split($originalFileBase64Data);
$encryptedData = NULL;
$encryptedDataKey = NULL;
for ($i = 0; $i <= $originalFileBase64DataLength; $i++) {
$randKey = rand(0, sizeOf(self::$charSet) - 1);
$arrayKey = array_search($originalFileBase64DataArray[$i], self::$charSet);
if($randKey > $arrayKey) {
$str = '-' . ($randKey - $arrayKey);
} elseif($randKey < $arrayKey) {
$str = ($randKey + $arrayKey);
} else {
$str = $randKey;
}
$encryptedData .= self::$charSet[$randKey];
$encryptedDataKey .= $str. ';';
}
$encryptedDataString = $encryptedData;
$encryptedDataKeyString = $encryptedDataKey;
if(!self::existsFile($keyFilePath)) {
file_put_contents($keyFilePath, $encryptedDataKeyString);
}
if(!self::existsFile($encryptedFilePath)) {
file_put_contents($encryptedFilePath, $encryptedDataString);
}
return 'OK';
} else {
return 'Source file not exists';
}
} else {
return 'Encrypted data already exists';
}
}
public static function decryptFile($encryptedFilePath, $keyFilePath, $decryptedFilePath)
{
$keyFileData = self::existsFile($keyFilePath);
$encryptedFileData = self::existsFile($encryptedFilePath);
$encryptedFileDataLength = strlen($encryptedFileData) - 1;
if($encryptedFileData && $keyFileData) {
$encryptedFileDataArray = str_split($encryptedFileData);
$keyFileDataArray = explode(';', $keyFileData);
$decryptedData = NULL;
for ($i = 0; $i <= $encryptedFileDataLength; $i++) {
$poziciaaktualneho = array_search($encryptedFileDataArray[$i], self::$charSet);
$poziciasifrovana = $keyFileDataArray[$i];
if($poziciasifrovana < 0) {
$move = $poziciasifrovana + $poziciaaktualneho;
} elseif($poziciasifrovana > 0) {
$move = $poziciasifrovana - $poziciaaktualneho;
} else {
$move = '0';
}
$decryptedData .= self::$charSet[$move];
}
if(!self::existsFile($decryptedFilePath)) {
file_put_contents($decryptedFilePath, base64_decode($decryptedData));
return 'OK';
} else {
return 'Decrypted data already exists';
}
}
}
private static function existsFile($filePath)
{
$fileData = #file_get_contents($filePath);
if($fileData) {
return $fileData;
}
return FALSE;
}
}
$originalFilePath = 'original.jpg';
$keyFilePath = 'Otp_Key_' . $originalFilePath;
$encryptedFilePath = 'Otp_Data_' . $originalFilePath;
$decryptedFilePath = 'Otp_Decrypted_' . $originalFilePath;
echo Otp::encryptFile($originalFilePath, $encryptedFilePath, $keyFilePath);
echo Otp::decryptFile($encryptedFilePath, $keyFilePath, $decryptedFilePath);
The problem seems to be only happening when $poziciaaktualneho is equal to $poziciasifrovana and so by adding another if statement on line 78 to check for this and instead set $move equal to $poziciasifrovana I was able to fix the problem. The below script should work:
final class Otp
{
private static $charSet = array('+','/','0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L',
'M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r',
's','t','u','v','w','x','y','z');
public static function encryptFile($originalFilePath, $encryptedFilePath, $keyFilePath)
{
if(!self::existsFile($keyFilePath) || !self::existsFile($encryptedFilePath)) {
if($originalFileData = self::existsFile($originalFilePath)) {
$originalFileBase64Data = base64_encode($originalFileData);
$originalFileBase64DataLength = strlen($originalFileBase64Data) - 1;
$originalFileBase64DataArray = str_split($originalFileBase64Data);
$encryptedData = NULL;
$encryptedDataKey = NULL;
for ($i = 0; $i <= $originalFileBase64DataLength; $i++) {
$randKey = rand(0, sizeOf(self::$charSet) - 1);
$arrayKey = array_search($originalFileBase64DataArray[$i], self::$charSet);
if($randKey > $arrayKey) {
$str = '-' . ($randKey - $arrayKey);
} elseif($randKey < $arrayKey) {
$str = ($randKey + $arrayKey);
} else {
$str = $randKey;
}
$encryptedData .= self::$charSet[$randKey];
$encryptedDataKey .= $str. ';';
}
$encryptedDataString = $encryptedData;
$encryptedDataKeyString = $encryptedDataKey;
if(!self::existsFile($keyFilePath)) {
file_put_contents($keyFilePath, $encryptedDataKeyString);
}
if(!self::existsFile($encryptedFilePath)) {
file_put_contents($encryptedFilePath, $encryptedDataString);
}
return 'OK';
} else {
return 'Source file not exists';
}
} else {
return 'Encrypted data already exists';
}
}
public static function decryptFile($encryptedFilePath, $keyFilePath, $decryptedFilePath)
{
$keyFileData = self::existsFile($keyFilePath);
$encryptedFileData = self::existsFile($encryptedFilePath);
$encryptedFileDataLength = strlen($encryptedFileData) - 1;
if($encryptedFileData && $keyFileData) {
$encryptedFileDataArray = str_split($encryptedFileData);
$keyFileDataArray = explode(';', $keyFileData);
$decryptedData = NULL;
for ($i = 0; $i <= $encryptedFileDataLength; $i++) {
$poziciaaktualneho = array_search($encryptedFileDataArray[$i], self::$charSet);
$poziciasifrovana = $keyFileDataArray[$i];
if ($poziciasifrovana == $poziciaaktualneho) {
$move = $poziciasifrovana;
} elseif($poziciasifrovana < 0) {
$move = $poziciasifrovana + $poziciaaktualneho;
} elseif($poziciasifrovana > 0) {
$move = $poziciasifrovana - $poziciaaktualneho;
} else {
$move = '0';
}
$decryptedData .= self::$charSet[$move];
}
if(!self::existsFile($decryptedFilePath)) {
file_put_contents($decryptedFilePath, base64_decode($decryptedData));
return 'OK';
} else {
return 'Decrypted data already exists';
}
}
}
private static function existsFile($filePath)
{
$fileData = #file_get_contents($filePath);
if($fileData) {
return $fileData;
}
return FALSE;
}
}
$originalFilePath = 'original.jpg';
$keyFilePath = 'Otp_Key_' . $originalFilePath;
$encryptedFilePath = 'Otp_Data_' . $originalFilePath;
$decryptedFilePath = 'Otp_Decrypted_' . $originalFilePath;
echo Otp::encryptFile($originalFilePath, $encryptedFilePath, $keyFilePath);
echo Otp::decryptFile($encryptedFilePath, $keyFilePath, $decryptedFilePath);
Warning: I would not recommend using my solution in an enterprise setting if at all since I do not know why this fixes your script or what was
originally wrong with it and it is most likely not air tight.

Amazon Scraper Script works on XAMPP Windows but not PHP5 Cli on Linux

I'm trying to scrape Amazon ASIN codes using the below code:
<?php
class Scraper {
const BASE_URL = "http://www.amazon.com";
private $categoryFile = "";
private $outputFile = "";
private $catArray;
private $currentPage = NULL;
private $asin = array();
private $categoriesMatched = 0;
private $categoryProducts = array();
private $pagesMatched = 0;
private $totalPagesMatched = 0;
private $productsMatched = 0;
public function __construct($categoryFile, $outputFile) {
$this->categoryFile = $categoryFile;
$this->outputFile = $outputFile;
}
public function run() {
$this->readCategories($this->categoryFile);
$this->setupASINArray($this->asin);
$x = 1;
foreach ($this->catArray as $cat) {
$this->categoryProducts["$x"] = 0;
if ($this->currentPage == NULL) {
$this->currentPage = $cat;
$this->scrapeASIN($this->currentPage, $x);
$this->pagesMatched++;
}
if ($this->getNextPageLink($this->currentPage)) {
do {
// next page found
$this->pagesMatched++;
$this->scrapeASIN($this->currentPage, $x);
} while ($this->getNextPageLink($this->currentPage));
}
echo "Category complete: $this->pagesMatched Pages" . "\n";
$this->totalPagesMatched += $this->pagesMatched;
$this->pagesMatched = 0;
$this->writeASIN($this->outputFile, $x);
$x++;
$this->currentPage = NULL;
$this->categoriesMatched++;
}
$this->returnStats();
}
private function readCategories($categoryFile) {
$catArray = file($categoryFile, FILE_IGNORE_NEW_LINES);
$this->catArray = $catArray;
}
private function setupASINArray($asinArray) {
$x = 0;
foreach ($this->catArray as $cat) {
$asinArray["$x"][0] = "$cat";
$x++;
}
$this->asin = $asinArray;
}
private function getNextPageLink($currentPage) {
$document = new DOMDocument();
$html = file_get_contents($currentPage);
#$document->loadHTML($html);
$xpath = new DOMXPath($document);
$element = $xpath->query("//a[#id='pagnNextLink']/#href");
if ($element->length != 0) {
$this->currentPage = self::BASE_URL . $element->item(0)->value;
return true;
} else {
return false;
}
}
private function scrapeASIN($currentPage, $catNo) {
$html = file_get_contents($currentPage);
$regex = '~(?:www\.)?ama?zo?n\.(?:com|ca|co\.uk|co\.jp|de|fr)/(?:exec/obidos/ASIN/|o/|gp/product/|(?:(?:[^"\'/]*)/)?dp/|)(B[A-Z0-9]{9})(?:(?:/|\?|\#)(?:[^"\'\s]*))?~isx';
preg_match_all($regex, $html, $asin);
foreach ($asin[1] as $match) {
$this->asin[$catNo-1][] = $match;
}
}
private function writeASIN($outputFile, $catNo) {
$fh = fopen($outputFile, "a+");
$this->fixDupes($catNo);
$this->productsMatched += (count($this->asin[$catNo-1]) - 1);
$this->categoryProducts["$catNo"] = (count($this->asin[$catNo-1]) - 1);
flock($fh, LOCK_EX);
$x = 0;
foreach ($this->asin[$catNo-1] as $asin) {
fwrite($fh, "$asin" . "\n");
$x++;
}
flock($fh, LOCK_UN);
fclose($fh);
$x -= 1;
echo "$x ASIN codes written to file" . "\n";
}
private function fixDupes($catNo) {
$this->asin[$catNo-1] = array_unique($this->asin[$catNo-1], SORT_STRING);
}
public function returnStats() {
echo "Categories matched: " . $this->categoriesMatched . "\n";
echo "Pages parsed: " . $this->totalPagesMatched . "\n";
echo "Products parsed: " . $this->productsMatched . "\n";
echo "Category breakdown:" . "\n";
$x = 1;
foreach ($this->categoryProducts as $catProds) {
echo "Category $x had $catProds products" . "\n";
$x++;
}
}
}
$scraper = new Scraper($argv[1], $argv[2]);
$scraper->run();
?>
But it works fine on XAMPP on Windows but not on Linux. Any ideas as to why this may be? Sometimes it scrapes 0 ASIN's to file, sometimes it only scrapes 1 page in a category of 400+ pages. But the output/functionality is totally fine in Windows/XAMPP.
Any thoughts would be greatly appreciated!
Cheers
- Bryce
So try to change this way, just to avoid the error messages:
private function readCategories($categoryFile) {
if (file_exists($categoryFile)) {
$catArray = file($categoryFile, FILE_IGNORE_NEW_LINES);
$this->catArray = $catArray;
} else {
echo "File ".$categoryFile.' not exists!';
$this->catArray = array();
}
}

cannot upload the file through admin panel

Column count doesn't match value count at row 1
public function file_upload($file,$dir)
{
$uploads_dir = $dir;
$original_file = addslashes($file['name']); // storing file name
$buffer_path = $file['tmp_name']; // storing temp buffer path
$unique_name = time().$original_file; // creating unique file name by appending time stamp
$path = $uploads_dir.$unique_name;
// uploading file using default function
if(move_uploaded_file($buffer_path,$path))
{
return $path;
}
else
{
return "No";
}
}
function multiple_image_upload($file,$path)
{
//echo "<pre>";print_r($file);
if(empty($file['name'][0]))
{
return "No file selected";
}
else
{
$cnt = 0 ;
foreach($file['name'] as $filename)
{
$buffer_path = $file['tmp_name'][$cnt];
$unique_file_name = $path.date('Y-m-d H-i-s').time().$filename;
move_uploaded_file($buffer_path,$unique_file_name);
$final_file_path[] = $unique_file_name;
$cnt++;
}
return $final_file_path;
}
}
function multiple_thumb($msg,$filedata,$thumb_folder)
{
if(!is_dir($thumb_folder))
{
mkdir($thumb_folder,0755);
}
$cnt=0;
foreach($msg as $val)
{
/* echo $val;
echo "<br />"; */
//echo "<pre>";
//print_r($filedata['name']);
$o_image = imagecreatefromjpeg($val);
$o_width = imageSX($o_image);
$o_height = imageSY($o_image);
$n_width = 230;
$n_height = 250;
$new_image = imagecreatetruecolor($n_width,$n_height);
//print_r($new_image);
imagecopyresampled($new_image,$o_image,0,0,0,0,$n_width,$n_height,$o_width,$o_height);
$thumb_unique_path = $thumb_folder.date('Y-m-d H-i-s').time().$filedata['name'][$cnt];
imagejpeg($new_image,$thumb_unique_path);
$thumb_final_data[] = $thumb_unique_path;
$cnt++;
}
//print_r($thumb_final_data);
return $thumb_final_data;
}

Categories