PHP ftp_chdir not visibly changing the directory - php

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>";
}
}

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()).

Shell_exec not executing php files

I'm trying to run a shell_exec query by pressing a button.
But it does not seem to execute anything. I checked php.ini and it isn't disabled. I'm trying to execute a php file in a different directory
/var/www/html/root/download_handler.php. It doesn't seem to work.
Here's my code. I hope anyone knows what i can do to fix this?
if ($_SERVER['REQUEST_METHOD'] === "POST") {
if (isset($_POST['download'])) {
$site = $_POST['site'];
$wait = $_POST['wait'];
$folder = $_POST['folder'];
$strpos = strpos($site, "http://");
if (empty($site) || empty($wait) || empty($folder)) {
$error = Error::display("Input fields left empty", "alert");
} else {
if ($strpos === false) {
$error = Error::display("Incorrect URL Format. Example: http://example.com/", "alert");
} else {
$username = $_SESSION['username'];
$error = Error::display($site . $wait . $folder . $username, "success");
shell_exec("screen php /var/www/html/download_handler.php download $site $folder $wait $username");
}
}
}
}
?>

Login works on local server not on live server

My login of admin panel and member panel both works fine on local server, But on Live server member panel doesn't work. As admin and member panel both use same connection file so it means connection file works fine. More over when we fill wrong user or password it says
Invalid User or Password
But when we login with correct user or password it returns back with no indication of error.
My login file upper php part is:
<?php
include_once("../init.php");
$msg='';
?>
<?php
if(isset($_POST['click']))
{
$user = trim($_POST['user']);
$pass = trim($_POST['pass']);
if(($user =='' )|| ($pass=='')){
$msg ='Please enter username & password';
}else{
$npass = ($pass);
$qry = mysql_query("select * from user where user ='$user'");
if(mysql_num_rows($qry)==0) {
$msg ='Invalid UserName';
} else {
$res = mysql_fetch_array($qry);
if($res['pass']==$npass) {
$_SESSION['USE_USER'] = $res['user'];
$_SESSION['SID'] = $res['id'];
$_SESSION['USE_NAME'] = $res['fname'];
$_SESSION['USE_SPONSOR'] = $res['sponsor'];
$_SESSION['PACKAGE_AMT'] = $res['package_amt'];
$_SESSION['ADDRESS'] = $res['address'];
$_SESSION['PHONE'] = $res['phone'];
$_SESSION['JOIN_DATE'] = $res['join_date'];
header('location: main.php');
} else {
$msg ='Invalid Password';
}
}
}
}
?>
My header file main.php is
<?php
include_once("../init.php");
validation_check($_SESSION['SID'],MEM_HOME_ADMIN);
$msg='';
$dir ='../'.USER_PIC;
$sId = $_SESSION['SID'];
?>
Session is started from another file called function.php
<?php
function logout($destinationPath)
{
if(count($_SESSION))
{
foreach($_SESSION AS $key=>$value)
{
session_unset($_SESSION[$key]);
}
session_destroy();
}
echo "<script language='javaScript' type='text/javascript'>
window.location.href='".$destinationPath."';
</script>";
}
function validation_check($checkingVariable, $destinationPath)
{
if($checkingVariable == '')
{
echo "<script language='javaScript' type='text/javascript'>
window.location.href='".$destinationPath."';
</script>";
}
}
function realStrip($input)
{
return mysql_real_escape_string(stripslashes(trim($input)));
}
function no_of_record($table, $cond)
{
$sql = "SELECT COUNT(*) AS CNT FROM ".$table." WHERE ".$cond;
$qry = mysql_query($sql);
$rec = mysql_fetch_assoc($qry);
$count = $rec['CNT'];
return $count;
}
//drop down
function drop_down($required=null, $text_field, $table_name, $id, $name, $cond, $selected_id=null)
{
$qry = mysql_query("SELECT $id, $name FROM $table_name WHERE $cond ORDER BY $name ASC");
$var = '';
if(mysql_num_rows($qry)>0)
{
$var = '<select id="'.$text_field.'" name="'.$text_field.'" '.$required.'>';
$var .='<option value="">--Choose--</option>';
while($r = mysql_fetch_assoc($qry))
{
$selected = '';
if($selected_id==$r[$id]){
$selected = 'selected="selected"';
}
$var .='<option value="'.$r[$id].'" '.$selected.'>'.$r[$name].'</option>';
}
$var .='</select>';
}
echo $var;
}
function uploadResume($title,$uploaddoc,$txtpropimg)
{
$upload= $uploaddoc;
$filename=$_FILES[$txtpropimg]['name'];
$fileextension=strchr($filename,".");
$photoid=rand();
$newfilename=$title.$photoid.$fileextension;
move_uploaded_file($_FILES[$txtpropimg]['tmp_name'],$upload.$newfilename);
return $newfilename;
}
function fRecord($field, $table, $cond)
{
$fr = mysql_fetch_assoc(mysql_query("SELECT $field FROM $table WHERE $cond"));
return $fr[$field];
}
function get_values_for_keys($mapping, $keys) {
$output_arr = '';
$karr = explode(',',$keys);
foreach($karr as $key) {
$output_arr .= $mapping[$key].', ';
}
$output_arr = rtrim($output_arr, ', ');
return $output_arr;
}
function getBaseURL() {
$isHttps = ((array_key_exists('HTTPS', $_SERVER)
&& $_SERVER['HTTPS']) ||
(array_key_exists('HTTP_X_FORWARDED_PROTO', $_SERVER)
&& $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')
);
return 'http' . ($isHttps ? 's' : '') .'://' . $_SERVER['SERVER_NAME'];
}
function request_uri()
{
if ($_SERVER['REQUEST_URI'])
return $_SERVER['REQUEST_URI'];
// IIS with ISAPI_REWRITE
if ($_SERVER['HTTP_X_REWRITE_URL'])
return $_SERVER['HTTP_X_REWRITE_URL'];
$p = $_SERVER['SCRIPT_NAME'];
if ($_SERVER['QUERY_STRING'])
$p .= '?'.$_SERVER['QUERY_STRING'];
return $p;
}
preg_match ('`/'.FOLDER_NAME.'(.*)(.*)$`', request_uri(), $matches);
$tableType = (!empty ($matches[1]) ? ($matches[1]) : '');
$url_array=explode('/',$tableType);
?>
Moreover I have created user id by words and time like LH1450429882 and column is verture type. I think this has no effect on login.
I think main errors come from function.php Sorry for a long code, but I tried to cover all parts of coding.
I am struggling with this code from a week. Thanks in advance for help.
This is probably a bug that error_reporting will show off. Always use it in development mode, to catch some carelessness errors and ensure the code's clarity.
ini_set('display_errors',1);
error_reporting(E_ERROR | E_WARNING | E_PARSE);
By implementing code ini_set('display_errors',1); error_reporting(E_ERROR | E_WARNING | E_PARSE); I got the error of header ploblem on line 6 in login php I have removed ?> and
Now my working code in login.php is
<?php
include_once("../init.php");
$msg='';
if(isset($_POST['click']))
{
$user = trim($_POST['user']);
$pass = trim($_POST['pass']);
if(($user =='' )|| ($pass=='')){
$msg ='Please enter username & password';
}else{
$npass = ($pass);
$qry = mysql_query("select * from user where user ='$user'");
if(mysql_num_rows($qry)==0) {
$msg ='Invalid UserName';
} else {
$res = mysql_fetch_array($qry);
if($res['pass']==$npass) {
$_SESSION['USE_USER'] = $res['user'];
$_SESSION['SID'] = $res['id'];
$_SESSION['USE_NAME'] = $res['fname'];
$_SESSION['USE_SPONSOR'] = $res['sponsor'];
$_SESSION['PACKAGE_AMT'] = $res['package_amt'];
$_SESSION['ADDRESS'] = $res['address'];
$_SESSION['PHONE'] = $res['phone'];
$_SESSION['JOIN_DATE'] = $res['join_date'];
header('location: main.php');
} else {
$msg ='Invalid Password';
}
}
}
}
?>

Retrieve Files from remote server based on yesterday's date

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);

Categories