schedule task not working - php

i have one php file and i am using ftp_get() function in it. when i run it from server localhost it's running fine but when i run it from schedule task it's giving error. here's my code.
<?php
$ftp_server = "IP";
$conn_id = ftp_connect ($ftp_server)
or die("Couldn't connect to $ftp_server");
$login_result = ftp_login($conn_id, "syslog", "Gms$67");
if ((!$conn_id) || (!$login_result))
die("FTP Connection Failed");
ftp_pasv($conn_id, true);
echo "Start time:".date("d-m-Y h:i:sa")."<br/>";
ftp_sync ("."); // Use "." if you are in the current directory
echo "<br/>End time:".date("d-m-Y h:i:sa")."<br/>";
ftp_close($conn_id);
// ftp_sync - Copy directory and file structure
function ftp_sync ($dir) {
global $conn_id;
if ($dir != ".") {
if (ftp_chdir($conn_id, $dir) == false) {
echo ("Change Dir Failed: $dir<BR>\r\n");
return;
}
if (!(is_dir($dir)))
mkdir($dir);
chdir ($dir);
}
$contents = ftp_nlist($conn_id, ".");
foreach ($contents as $file) {
if ($file == '.' || $file == '..')
continue;
if (#ftp_chdir($conn_id, $file)) {
ftp_chdir ($conn_id, "..");
ftp_sync ($file);
}
else
{
if(ftp_get($conn_id, "files/syslog.txt", $file, FTP_BINARY))
{
$mbody= nl2br(file_get_contents("files/syslog.txt"));
//$f = fopen('files/syslog.txt', 'r+');
//$mbody = fread($f, filesize("files/syslog.txt"));
//fclose($f);
$resArray = explode("\n",$mbody);
foreach($resArray as $r) {
$ArrayResults[] = explode(" ",$r,6);
}
/*echo "<pre>";
print_r($ArrayResults);
echo "</pre>";*/
$fields="srdate,srtime,facility,severity,host,message";
foreach ($ArrayResults as $rowValues) {
//echo "vip==".$rowValues[0]."--<br/>";
if($rowValues[0]!="")
{
$serarray = explode(".",$rowValues[2]);
//echo "servi=".$serarray[1]."<br/>";
$facility=$serarray[0];
$severity=$serarray[1];
/*foreach ($rowValues as $key => $rowValue) {
$rowValues[$key] = mysql_real_escape_string($rowValues[$key]);
}*/
$rowValues1[0] = mysql_real_escape_string($rowValues[0]);
$rowValues1[1] = mysql_real_escape_string($rowValues[1]);
$rowValues1[2] = mysql_real_escape_string($facility);
$rowValues1[3] = mysql_real_escape_string($severity);
$rowValues1[4] = mysql_real_escape_string($rowValues[3]);
$rowValues1[5] = mysql_real_escape_string($rowValues[5]);
$values[] = "('" . implode('\', \'', $rowValues1) . "')";
unset($serarray);
}
}
include("config.php");
$query = "INSERT INTO syslogtbl ($fields) VALUES " . implode (', ', $values) . "";
if(mysql_query($query))
{
echo "Successfully Insert to Database.";
}
else
{
echo "<br/>Error in insert syslog".mysql_error();;
}
}
else
{
echo "Error downloading $server_file.";
}
}
}
ftp_chdir ($conn_id, "..");
chdir ("..");
}
?>
when i run from schedule task it shows not any error but also not anything change in output(it must change). then i run file from batch file and it shows error in command prompt is.
C:\script>C:\wamp\bin\php\php5.5.12\php.exe C:\wamp\www\syslog\schedule_readtxt.php
Start time:24-11-2016 12:33:41pm<br/>
Warning: ftp_get(files/syslog.txt): failed to open stream: No such file or directory in C:\wamp\www\syslog\schedule_readtxt.php on line 69
Call Stack:
0.0000 250200 1. {main}() C:\wamp\www\syslog\schedule_readtxt.php:0
0.0156 259928 2. ftp_sync() C:\wamp\www\syslog\schedule_readtxt.php:35
0.0156 261832 3. ftp_get() C:\wamp\www\syslog\schedule_readtxt.php:69
Warning: ftp_get(): Error opening files/syslog.txt in C:\wamp\www\syslog\schedul
e_readtxt.php on line 69
Call Stack:
0.0000 250200 1. {main}() C:\wamp\www\syslog\schedule_readtxt.php:0
0.0156 259928 2. ftp_sync() C:\wamp\www\syslog\schedule_readtxt.php:35
0.0156 261832 3. ftp_get() C:\wamp\www\syslog\schedule_readtxt.php:69
Notice: Undefined variable: server_file in C:\wamp\www\syslog\schedule_readtxt.p
hp on line 118
Call Stack:
0.0000 250200 1. {main}() C:\wamp\www\syslog\schedule_readtxt.php:0
0.0156 259928 2. ftp_sync() C:\wamp\www\syslog\schedule_readtxt.php:35
Error downloading .<br/>End time:24-11-2016 12:33:41pm<br/>
C:\script>pause
Press any key to continue . . .
i don't know how to run this script from schedule task. please help me.

Related

PHP fopen, fwrite and fclose proceed without errors but no file created

I am running PHP 7.0.22, under LAMP, on two ubuntu 16.04.
The following code proceeds without throwing an exception and $tempFile has the value Resource id #4.
try {
// Open temp file for writing
$tempFile = fopen("/var/www/dropbox/temp.lst", "w");
echo "tempfile=" . $tempFile . "<br>";
// Write list of file names to file
for ($x = 0; $x <= $inputFileCount; $x++) {
fwrite($tempFile, $fileNames);
}
// Close temp file
fclose($tempFile);
} catch ( Exception $e ) {
// send error message if you can
echo 'Caught exception: ', $e->getMessage(), "\n";
}
However, no file, by the name of temp.lst, appears in the directory /var/www/dropbox/ which has full write permission.
ls -ld /var/www/dropbox/
drwxrwsrwx 2 ubuntu www 4096 Mar 25 18:13 /var/www/dropbox/
No errors, related to the code, are shown by
cat /var/log/apache2/error.log
fopen, fwrite, fclose don't throw Exceptions, they return errors
Try
try {
// Open temp file for writing
$tempFile = fopen("/var/www/dropbox/temp.lst", "w");
if (false === $tempFile) throw new \RuntimeException("Failed to open file");
echo "tempfile=" . $tempFile . "<br>";
// Write list of file names to file
for ($x = 0; $x <= $inputFileCount; $x++) {
if(false === fwrite($tempFile, $fileNames)) throw new \RuntimeException("Failed to write to file");
}
// Close temp file
if(false === fclose($tempFile)) throw new \RuntimeException("Failed to close file");
} catch ( Exception $e ) {
// send error message if you can
echo 'Caught exception: ', $e->getMessage(), "\n";
}
and you should get some exceptions

upload csv to server from local system using php

<?php
// FTP access parameters
$source_ftp_server = 'ftp://uk9.siteground.eu';
$source_ftp_user_name = 'xyz';
$source_ftp_user_pass = 'abc';
// file to move:
$local_file = '/Users/Swayam/Desktop/Test.csv';
$remote_file = '/home/c10mill2/public_html/edtopiadb/Test.csv';
$fp = fopen($local_file, 'r');
$conn_id = ftp_connect($source_ftp_server);
$login_result = ftp_login($conn_id, $source_ftp_user_name, $source_ftp_user_pass);
$ret = ftp_nb_fput($conn_id, $remote_file, $fp, FTP_BINARY);
while ($ret == FTP_MOREDATA) {
// Establish a new connection to FTP server
if(!isset($conn_id2)) {
$conn_id2 = ftp_connect($source_ftp_server);
$login_result2 = ftp_login($conn_id2, $source_ftp_user_name, $source_ftp_user_pass);
}
// Retreive size of uploaded file.
if(isset($conn_id2)) {
clearstatcache(); // <- this must be included!!
$remote_file_size = ftp_size($conn_id2, $remote_file);
}
// Calculate upload progress
$local_file_size = filesize($local_file);
if (isset($remote_file_size) && $remote_file_size > 0 ){
$i = ($remote_file_size/$local_file_size)*100;
printf("%d%% uploaded<br>", $i);
flush();
}
$ret = ftp_nb_continue($conn_id);
}
if ($ret != FTP_FINISHED) {
echo "<span style='color:red;'><b>There was an error uploading the file...</b></span><br>";
exit(1);
}
else {
echo "<br>Files successfully uploaded!<br><br>";
}
fclose($fp);
Pls help me with the code to get it working.
When i execute this code i get a error -
Warning: ftp_connect(): php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known in /Users/Swayam/Desktop/sample.php on line 14
Warning: ftp_login() expects parameter 1 to be resource, boolean given in /Users/Swayam/Desktop/sample.php on line 15
Warning: ftp_nb_fput() expects parameter 1 to be resource, boolean given in /Users/Swayam/Desktop/sample.php on line 16
<span style='color:red;'><b>There was an error uploading the file...</b></span><br>

how to upload a base64_decode($data) using ftp?

Im trying to upload a mp3 file to my ftp server:
$data = substr($_POST['data'], strpos($_POST['data'], ",") + 1);
$decodedData = base64_decode($data);
$filename = urldecode($_POST['fname']);
$cid = ftp_connect("foo.com");
$result = ftp_login($cid, "rodrigo#foo.com","password");
if ((!$cid) || (!$result)) {
echo "connection failed"; die;
} else {
echo "connected";
}
ftp_pasv ($cid, true);
ftp_chdir($cid, "my_folder");
if (ftp_put($cid, $filename, $decodedData, FTP_BINARY)) {
//...
} else {
//...
}
I have this warning:
Warning: ftp_put(���) [function.ftp-put]: failed to open stream: Invalid argument in...
I cant find out how to send a valid argument
You will need to create a file that you can pass, the below example writes the file to memory instead of a file on your disk ... but you may want to write it to disk depending on the size.
$tmp = fopen('php://memory', 'r+');
fputs($tmp, $decodedData);
rewind($tmp);
if (ftp_fput($cid, $filename, $tmp, FTP_BINARY)) {
}

PHP fopen() not working. file exists, path is correct, permission checked

I'm trying to open a file with fopen() but it doesn't work.
"Warning: fopen(): Filename cannot be empty"
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
$file = 'output/example.csv';
$handle = fopen("$file", "r");
if ($handle != FALSE) {
echo "error";
}
?>
I checked if the file exists and if the path is correct.
echo $file;
gives me "output/example.csv"
I can't figure it out. In an other php script the code above works fine...
Need help please. Any help is appreciated. Thanks!
*******EDIT*******
Maybe I should precise my problem and post a bigger part of my code:
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
clearstatcache();
require('mainConfig.php');
################ Save & delete markers #################
if($_POST) //run only if there's a post data
{
//make sure request is comming from Ajax
$xhr = $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest';
if (!$xhr){
header('HTTP/1.1 500 Error: Request must come from Ajax!');
exit();
}
/***** Datei öffnen *****/
$code = filter_var($_POST["mfileName"], FILTER_SANITIZE_STRING);
$file = 'output/'.$code.".csv";
echo "file to open: ".$file."<br>";
if (!file_exists($file)) {
echo "file doesn't exist: ".$file."<br>";
} else {
echo "file exists: ".$file."<br>";
}
$directory = 'output/backup/versions/'.$code;
if (!file_exists($directory)) {
mkdir($directory, 777, true);
}
$handle = fopen($file, "rb"); // 'r' = Lese und Schreib Rechte
if (!$handle) {
echo "Es ist ein Fehler aufgetreten. Datei konnte nicht geöffnet werden.<br>";
}
fclose($handle);
$i = 0;
if ($handle = opendir($directory)) {
while (($file = readdir($handle)) !== false){
if (!in_array($file, array('.', '..')) && !is_dir($dir.$file))
$i++;
}
}
closedir($handle);
$versionFileNameAndPath = 'output/backup/versions/'.$code.'/'.$code.'_versionNr_'.$i.".csv";
echo "copy Ziel-Datei: ".$versionFileNameAndPath."<br>";
if (!file_exists($versionFileNameAndPath)) {
if ( copy($file , $versionFileNameAndPath) ) {
// file copied.
} else {
print_r(error_get_last());
// error occurred..call error_get_last() function for err details.
}
}
$handle = fopen($file, "r"); // 'r' = Lese und Schreib Rechte
$managedPinArray = "";
$managedPinArrayIndexInFile = 0;
if ($handle != FALSE) {
echo "Es ist ein Fehler aufgetreten. Datei konnte geöffnet werden.";
} else {
$connection = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die(mysql_error());
mysql_select_db($DB_Name,$connection) or die(mysql_error());
...
etc.
And this gives me the following Output:
file to open: output/69-1407031331-de.csv
file exists: output/69-1407031331-de.csv
copy Ziel-Datei: output/backup/versions/69-1407031331-de/69-1407031331-de_versionNr_0.csv
Warning: copy(): Filename cannot be empty in C:\xampp\htdocs\guide\map_process.php on line 49
Array ( [type] => 2 [message] => copy(): Filename cannot be empty [file] => C:\xampp\htdocs\guide\map_process.php [line] => 49 )
Warning: fopen(): Filename cannot be empty in C:\xampp\htdocs\guide\map_process.php on line 56
The problem lies here:
$file = 'output/'.$code.".csv";
// ... other code ...
while (($file = readdir($handle)) !== false){
// ... other code ...
copy($file , $versionFileNameAndPath)
You're reusing the $file variable and at the end of your while loop it will be false (hence, the notice about an empty file name).
You got error in if
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
$file = 'output/example.csv';
$handle = fopen("$file", "r");
if (!$handle) {
echo "error";
}
?>
try this code, your condition was "if $handle is not false report error"
Try to use the entire address where is the file
Ex
In windows
c:\\some\\output\\example.csv
In linux
/home/some/example.csv

FTP file copying from source to destination in PHP

I have a script which connect my source FTP and destination FTP and copy all files from source to destination now i have change my server and it returns me these errors ftp connection suspenseful but didn't copy files just create files. My code is written below.
$ftp1 = new ClsFTP("$user1","$pass1", "$site1");
if(!$ftp1)
{
echo "could not connect";
exit;
}
$ftp2 = new ClsFTP("$user2","$pass2", "$site2");
$mod = "0755";
$dir_list[] = "httpdocs";
for($i=0;$i<count($dir_list); $i++)
{
echo "<br>Copying Directory: " . $dir_list[$i];
if(!$ftp1->cd($dir_list[$i]))
{
echo "1::$site1 could not open directory: $dir_list[$i]. skipping<br>\n";
continue;
}
if(!$ftp2->cd($dir_list[$i]))
{
echo "2::$site2 could not open directory: $dir_list[$i]. Trying to create it<br>\n";
if(!$ftp2->mkdir($dir_list[$i]))
{
echo "2::$site2 could not create directory: $dir_list[$i]. skipping<br>\n";
continue;
}
if(!$ftp2->cd($dir_list[$i]))
{
echo "2::$site2 could not open directory: $dir_list[$i]. skipping<br>\n";
continue;
}
}
if($dir_list[$i]=="httpdocs/tmpupload"){
}else{
$dir_rawlist = $ftp1->rawlist();
$dir_nlist = $ftp1->nlist();
$ftp1->p($dir_rawlist);
#$ftp1->p($dir_nlist);
for($k = 0; $k<count($dir_nlist); $k++)
{
if($dir_list[$i]=="httpdocs/includes" && $dir_nlist[$k]=="cert_key_pem.txt"){
continue;
}
if($dir_list[$i]=="httpdocs" && $dir_nlist[$k]=="PayPal.class.php"){
continue;
}
$size = $ftp1->check_file($dir_nlist[$k]);
if($size >0)//substr($dir_rawlist[$k], 0, 1)=='-')//its a file
{
$ftp1->get("tmp/".$dir_nlist[$k], $dir_nlist[$k]);
$handle = fopen("tmp/".$dir_nlist[$k], 'r');
$contents = fread($handle, filesize("tmp/".$dir_nlist[$k]));
fclose($handle);
$contents = str_replace($search_for, $replace_with, $contents);
$handle = fopen("tmp/".$dir_nlist[$k], 'w');
fwrite($handle, $contents);
fclose($handle);
$ftp2->put($dir_nlist[$k], "tmp/".$dir_nlist[$k]);
$ftp2->chmod($dir_nlist[$k], $mod);
}
}
}
$ftp1->cd("/");
$ftp2->cd("/");
}
These warnings thrown by script.
Warning: ftp_get(): Error opening tmp/InviteFriend2.php in /var/www/vhosts/virtualphoneline.com/httpdocs/includes/ftp.class.php on line 120
Warning: fopen(tmp/InviteFriend2.php): failed to open stream: Permission denied in /var/www/vhosts/virtualphoneline.com/httpdocs/includes/clone.php on line 228
Warning: fwrite() expects parameter 1 to be resource, boolean given in /var/www/vhosts/virtualphoneline.com/httpdocs/includes/clone.php on line 229
Warning: fclose() expects parameter 1 to be resource, boolean given in /var/www/vhosts/virtualphoneline.com/httpdocs/includes/clone.php on line 230

Categories