Retrieve Files from remote server based on yesterday's date - php

I need to modify this script to retrieve only the files with yesterday's date. Here is what I have:
<?php
$username = 'XXXXXX';
$password = 'XXXXXX';
$ftp_server = 'data.mywebsite.com';
$conn = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");
if(ftp_login($conn, $username, $password))
{
echo 'Logged in';
}
else
{
echo 'FTP Error:Could not log in to '.$ftp_server;
exit();
}
ftp_pasv ($conn, true);
if (ftp_chdir($conn, "../Photos/Hi-res")) {
echo "Current FTP directory is now: " . ftp_pwd($conn) . "\n";
} else {
echo "Couldn't change to Photos directory\n";
}
$list = ftp_nlist($conn, '.');
function is_img($file) {
if(preg_match('/.*\.png/', $file))
{
return preg_match('/.*\.png/', $file) > 0;
}
if(preg_match('/.*\.jpg/', $file))
{
return preg_match('/.*\.jpg/', $file) > 0;
}
if(preg_match('/.*\.gif/', $file))
{
return preg_match('/.*\.gif/', $file) > 0;
}
}
$filtered = array_filter($list, is_img);
foreach($filtered as $img) {
if (ftp_get($conn, $img, $img, FTP_BINARY)) {
echo "Successfully written to $img\n";
} else {
echo "There was a problem\n";
}
}
ftp_close($conn);
When I run the script, it is grabbing all files not already on my server which is not what I want. I just want it to grab all the files with yesterdays date.
Thanks

Here's a quick and dirty solution for you, please note that this will not take the server timezone differences or other pitfalls into account when comparing the mtimes.
The main change is that the is_img function have been renamed and extended with ftp_mdtm() for each file.
$username = 'XXXXXX';
$password = 'XXXXXX';
$ftp_server = 'data.mywebsite.com';
$now = time();
$conn = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");
if(ftp_login($conn, $username, $password))
{
echo 'Logged in';
}
else
{
echo 'FTP Error:Could not log in to '.$ftp_server;
exit();
}
ftp_pasv ($conn, true);
if (ftp_chdir($conn, "../Photos/Hi-res")) {
echo "Current FTP directory is now: " . ftp_pwd($conn) . "\n";
} else {
echo "Couldn't change to Photos directory\n";
}
$list = ftp_nlist($conn, '.');
function is_for_download($file) {
$is_img = false;
if(preg_match('/.*\.png/', $file))
{
$is_img = preg_match('/.*\.png/', $file) > 0;
}
if(preg_match('/.*\.jpg/', $file))
{
$is_img = preg_match('/.*\.jpg/', $file) > 0;
}
if(preg_match('/.*\.gif/', $file))
{
$is_img = preg_match('/.*\.gif/', $file) > 0;
}
if (!$is_img) {
return false;
}
global $conn;
global $now;
$yesterday_start = strtotime('yesterday midnight', $now);
$yesterday_end = strtotime('yesterday midnight + 24 hours', $now);
$mtime = ftp_mdtm($conn, $file);
if ($yesterday_start <= $mtime && $mtime <= $yesterday_end) {
return true;
}
return false;
}
$filtered = array_filter($list, 'is_for_download');
foreach($filtered as $img) {
if (ftp_get($conn, $img, $img, FTP_BINARY)) {
echo "Successfully written to $img\n";
} else {
echo "There was a problem\n";
}
}
ftp_close($conn);

Related

I cannot upload variables to database

I tried to upload video filenames and other variables to the database, but the insert statement won't work. Anyway the videofile-name and the thumbnail-filename are both uploaded to the right folders.
I've checked and there's nothing wrong with the sql statement. But why won't it work can anyone tell me?
PHP code
<?php
session_start();
if (isset($_POST['submit'])) {
$videoName = $_POST['videoName'];
$videoDesc = $_POST['description'];
$category = $_POST['category'];
$level = $_POST['level'];
$userId = $_SESSION['userId'];
$videoFile = $_FILES["videoFile"];
$videoFileName = $videoFile['name'];
$videoFileType = $videoFile['type'];
$videoFileTempName = $videoFile['tmp_name'];
$videoFileError = $videoFile['error'];
$videoFileExt = explode(".", $videoFileName);
$videoFileActualExt = strtolower(end($videoFileExt));
$videoAllowed = array("mp4", "mov", "avi");
$thumbFile = $_FILES["thumbnail"];
$thumbFileName = $thumbFile["name"];
$thumbFileType = $thumbFile["type"];
$thumbFileTempName = $thumbFile["tmp_name"];
$thumbFileError = $thumbFile["error"];
$thumbFileExt = explode(".", $thumbFileName);
$thumbFileActualExt = strtolower(end($thumbFileExt));
$thumbAllowed = array("jpg", "jpeg", "png");
if (in_array($videoFileActualExt, $videoAllowed)) {
if(in_array($thumbFileActualExt, $thumbAllowed)) {
if ($videoFileError === 0) {
if ($thumbFileError === 0) {
$videoFullName = $videoFile . "." . uniqid("", true) . "." . $videoFileActualExt;
$videoFileDestination = "../video/" . $videoFullName;
$thumbFullName = $thumbFile . "." . uniqid("", true) . "." . $thumbFileActualExt;
$thumbFileDestination = "../thumbnail/" . $thumbFullName;
include 'dbh.inc.php';
if(empty($videoName) or empty($videoDesc)) {
header("Location: ../uploadVideo.php?upload=empty");
exit();
} else {
move_uploaded_file($videoFileTempName, $videoFileDestination);
move_uploaded_file($thumbFileTempName, $thumbFileDestination);
$sql = "INSERT INTO video (filnavn, thumbnail, videoName, descript, idMusician, categoryName, idLevel) VALUES ('$videoFullName', '$thumbFullName', '$videoName', '$videoDesc', $userId, '$category', $level);";
mysqli_query($conn, $sql);
header("Location: ../uploadVideo.php?upload=success");
exit();
}
} else {
echo "You had a thumbnail error!";
exit();
}
} else {
echo "You had a video error!";
exit();
}
} else {
echo "You need to upload a proper thumbnail file type";
exit();
}
} else {
echo "You need to upload a proper video file type!";
exit();
}
} else {
}
You cannot insert or in this way in the if() condition, you must always use the logical operator as
if(empty($videoName) || empty($videoDesc))
Because of that your execution of code must have stopped at that point.

Code executing both if and else statements together how do i fix?

the code is running to match username with password and if both correct redirecting to another page but that and the else statements both run
Code:
if (isset($_POST['Login'])) {
$IncorrectDetails = 0;
$Username=$_REQUEST['Username'];
$Password=$_REQUEST['Password'];
echo "<p> $Username $Password</p>";
$myfile = fopen("bin\Account Details.txt", "r") or die("Unable to open file!");
//reads raw file
$string = fread($myfile,filesize("bin\Account Details.txt"));
//turns the string to array
$a = explode(',', $string);
foreach ($a as $result) {
$b = explode('. ', $result);
$AccountDetails[trim($b[0])] = trim($b[1]);
}
//closes file
fclose($myfile);
print_r($AccountDetails);
foreach ($AccountDetails as $StoredUsername => $StoredPassword) {
if ($StoredUsername == $Username){
if ($StoredPassword == $Password) {
header('Location: Main.php');
}
else {
$IncorrectDetails = 1;
}
}
else {
$IncorrectDetails = 1;
}
}
if ($IncorrectDetails == 1){
echo "<script type='text/javascript'>alert('Incorrect login details');</script>";
}
}
its expected to come up with a popup when incorrect and redirect when correct
if (isset($_POST['Login'])) {
$IncorrectDetails = 0;
$Username=$_REQUEST['Username'];
$Password=$_REQUEST['Password'];
echo "<p> $Username $Password</p>";
$myfile = fopen("bin\Account Details.txt", "r") or die("Unable to open file!");
//reads raw file
$string = fread($myfile,filesize("bin\Account Details.txt"));
//turns the string to array
$a = explode(',', $string);
foreach ($a as $result) {
$b = explode('. ', $result);
$AccountDetails[trim($b[0])] = trim($b[1]);
}
//closes file
fclose($myfile);
foreach ($AccountDetails as $StoredUsername => $StoredPassword) {
if ($StoredUsername == $Username && $StoredPassword == $Password){
$CorrectDetails = 1;
} else {
$IncorrectDetails = 1;
}
}
if(isset($CorrectDetails) && $CorrectDetails == 1){
header('Location: Main.php');
}else ($IncorrectDetails == 1){
echo "<script type='text/javascript'>alert('Incorrect login details');</script>";
}
}
You are redirect to another page it's not a proper way instead of that you can use a variable just like you have used in else and outside the loop you can redirect to another page.
That's beacuse the redirection is not instantaneus, php code still being processed.
So, just after header('Location: Main.php'); do exit; to stop at all your script in that point, and let the redirection works.
header('Location: Main.php');
exit;
Also, you musn't print anything before the header() instruction (remove print_r()).

Retrieve remote file via SSH2 works in PHP 7 but not PHP5.6

So.. this function works great in PHP7.. but I have to downscale the server to 5.6 because of some other code that doesn't work with PHP7.
Once the server is scaled back to 5.6, this SSH2 function throws the Failed to open directory error.
I have checked all the functions that are called and they are all PHP 4.0 and up. Anyone have any ideas?
function get_the_k12_file($filename)
{
$host = "thehost.com";
$port = 22;
$username = "username!";
$password = "password!";
$remoteDir = "/the/path/tothefile/";
$localDir = "";
if (!function_exists("ssh2_connect"))
die("Function ssh2_connect does not exist.");
if (!$connection = ssh2_connect($host, $port))
die("Failed to connect.");
if (!ssh2_auth_password($connection, $username, $password))
die("Failed to authenticate.");
if (!$sftp_conn = ssh2_sftp($connection))
die("Failed to create a sftp connection.");
if (!$dir = opendir("ssh2.sftp://$sftp_conn$remoteDir"))
die("Failed to open the directory.");
$files = array();
while ( ($file = readdir($dir)) !== false)
{
if(substr($file, -4)==".zip")
{
$files[]=$file;
}
}
closedir($dir);
foreach ($files as $file)
{
if($file==$filename)
{
echo "Copying file: $file\n";
if (!$remote = fopen("ssh2.sftp://$sftp_conn$remoteDir$file", "r"))
{
echo "Failed to open remote file: $file\n";
continue;
}
if (!$local = fopen($localDir . $file, "w"))
{
echo "Failed to create local file: $file\n";
continue;
}
$read = 0;
$filesize = filesize("ssh2.sftp://$sftp_conn/$remoteDir$file");
while ( ($read < $filesize) && ($buffer = fread($remote, $filesize - $read)) )
{
$read += strlen($buffer);
if (fwrite($local, $buffer) === FALSE)
{
echo "Failed to write to local file: $file\n";
break;
}
}
}
fclose($local);
fclose($remote);
}
}

PHP How to limit users to a specific number of files that can be uploaded

I've been searching for ways to limit users to "5" file uploads and if they upload more, echo a message. I want to limit 5 because just in case of spammers and users that want to cheat the system and upload more than 5 into he database.
I found this answer
if(isset($_FILES['file']['name'][5])){
// Code
}else{
//exit
}
But, it's not working for me. It still sends to the database and skips the, if file is greater than 5, checker. Here is my code
PHP
if($_SERVER['REQUEST_METHOD'] =="POST"){
if(!empty($_POST['price']) && !empty($_POST['description'])){
if(!ctype_digit($_POST['price'])){
echo "PRICE ENTERED IS NOT AN INTEGER... PLEASE TRY AGAIN!";
exit;
}
$price = addslashes(trim((int)$_POST['price']));
$description = addslashes(trim($_POST['description']));
if(strlen($description) < 15){
echo "Description field needs to be GREATER than 15 characters!";
exit;
}
if(isset($_FILES['file']['name'][5])){
try{
// new php data object
$handler = new PDO('mysql:host=127.0.0.1;dbname=magicsever', 'root', '');
//ATTR_ERRMODE set to exception
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
die("There was an error connecting to the database");
}
$query = "INSERT INTO test(name, file)VALUES(:file_name, :file_tmp)";
$stmt = $handler->prepare($query);
$errors = array();
foreach($_FILES['file']['tmp_name'] as $key => $error){
if ($error != UPLOAD_ERR_OK) {
$errors[] = $_FILES['file']['name'][$key] . ' was not uploaded.';
continue;
}
$file_name = $key.$_FILES['file']['name'][$key];
$file_tmp = $_FILES['file']['tmp_name'][$key];
try{
$stmt->bindParam(':file_name', $file_name, PDO::PARAM_STR);
$stmt->bindParam(':file_tmp', $file_tmp, PDO::PARAM_STR);
$stmt->execute();
$dir = "devFiles";
if(is_dir($dir)==false){
mkdir($dir, 0700);
}
if(is_file($dir.'/'.$file_name)==false){
move_uploaded_file($file_tmp,$dir.'/'.$file_name);
}else{
echo '<br><h1 style="color:red;">VALUES MISSING!</h1>';
exit;
}
}catch(PDOException $e){
$errors[] = $file_name . 'not saved in db.';
echo $e->getMessage();
}
}
echo "pk";
}else{
echo "tooo big";
exit;
}
}else{
echo '<br><h1 style="color:red;">VALUES MISSING!</h1>';
exit;
}
}
Your condition is currently checking for the existence of a 6th file and continuing. Instead:
if (count($_FILES['file']['name']) <= 5) {
...
You are executing the code if there ARE more than 5, you want to check that there are NOT more than 5 so use !:
if(!isset($_FILES['file']['name'][5])){
But you could probably just count:
if(count($_FILES['file']['name']) < 6){

PHP ftp_chdir not visibly changing the directory

I started on an ftp project and I'm having trouble getting the directory to reload. My code says that it successfully changed, but I am assume that it only changes server-side. I need the browser to change the directory as well.
PS: How can I download via FTP through the browser? When I test locally it writes the files to the root directory but when connected remotely I don't know where they go. There is no indication of files being downloaded.
Any help would be greatly appreciated! And please, if you have any tips for me that would be great. I'm still pretty new at this but I'm trying my best.
<?php
session_id('logon');
session_start();
if (isset($_POST['connect']))
{
$_SESSION['port'] = $_POST['port'];
$_SESSION['server'] = $_POST['server'];
$_SESSION['user'] = $_POST['user'];
$_SESSION['password'] = $_POST['password'];
}
$port = $_SESSION['port'];
$server = $_SESSION['server'];
$user = $_SESSION['user'];
$pass = $_SESSION['password'];
$connection = ftp_connect($server)
or die("Couldn't connect!");
$logon = ftp_login($connection,$user,$pass)
or die("Couldn't login!" . $server ."<br>". $port);
$workingDir = ftp_pwd($connection);
echo "You are in $workingDir<br><br>";
$dirList = ftp_nlist($connection, ".");
foreach($dirList as $item)
{
$res = ftp_size($connection, $item);
if ($res != "-1")
{
echo "<a href='?download=$item'>$item</a><br>";
if (isset($_GET['download']))
{
if ($_GET['download'] == $item)
{
include('include/download.php');
}
}
}
else
{
$directory = $item;
echo "<a href='?change=$directory'>$directory</a><br>";
if ($_GET['change'] == $directory)
{
if (ftp_chdir($connection, $directory))
{
echo "Changed to " . ftp_pwd($connection) . "!<br>";
$dirList = ftp_nlist($connection, ".");
header("Refresh:0");
}
else
{
echo "Failed to change to $directory";
}
}
}
}
ini_set('error_reporting', E_ALL);
ftp_quit($connection);
?>
Solved! Added a directory.php file with
$getChange = $_GET['change'];
if (ftp_chdir($connection, $getChange))
{
echo "Changed to " . ftp_pwd($connection) . "!<br>";
$dirList = ftp_nlist($connection, ".");
}
else
{
echo "Failed to change to $getChange";
}
$workingDir = ftp_pwd($connection);
echo "You are in $workingDir<br><br>";
$dirList = ftp_nlist($connection, ".");
foreach($dirList as $item)
{
$res = ftp_size($connection, $item);
if ($res != "-1")
{
echo "<a href='?download=$item'>$item</a><br>";
if (isset($_GET['download']))
{
if ($_GET['download'] == $item)
{
include('include/download.php');
}
}
}
else
{
echo "<a href='directory.php?change=$item'>$item</a><br>";
}
}

Categories