So, if i have a file that when its empty it requires a specific function, but if the file is NOT empty it will proceed to show (else) something else. This is currently the format I am using. I have tired several different manners and variations of doing so (from PHP Manual examples to StackOverFlow Q/A). What it is doing is showing me the else not the if, since the file is actually empty...
<?
$file = 'config/config2.php';
if(!empty($file))
{
some code here!
}
else
{
some other code here!
}
?>
<?
$file = 'config/config2.php';
if(filesize($file)!=0)// NB:an empty 'looking' file could have a file size above 0
{
some code here!
}
else
{
some other code here!
}
?>
The problem seems to be that you are not actually loading the file before you check if it is empty.
You are only setting the variable $file to the string 'config/config2.php' not actually loading the file.
Before running your if statement do this:
$file = file_get_contents('config/config2.php');
or look into this: http://php.net/manual/en/function.fopen.php
Related
I'm trying to create a script that will send across files from one server to another. My script successfully does that as well as checks if the file has something in it or not. My next step is to check whether the file already exists on the server; if the file already exists it does not send and if it does not exist, it does send.
I've tried a few different things and can't seem to get my head around it. How can I get it to check whether the file already exists or not? Any help would be appreciated!
(I had a look at some similar questions but couldn't find anything specific to my issue.)
require('constants.php');
$files = $sftp->nlist('out/');
foreach($files as $file) {
if(basename((string) $file)) {
if(strpos($file,".") > 1) { //Checks if file
$filesize = $sftp->size('out/'.$file); //gets filesize
if($filesize > 1){
if (file_exists('import/'.$file)){
echo $file.' already exists';
}
else {
$sftp->get('out/'.$file, 'import/'.$file); //Sends file over
//$sftp->delete('out/'.$file); //Deletes file from out folder
}
else {
echo $file. ' is empty.</br>';
}
}
}
}
}
EDIT: To try and get this to work, I wrote the following if statement to see if it was finding the file test.php;
if (file_exists('test.txt')){
echo 'True';
} else {
echo 'False';
}
This returned true (a good start) but as soon as I put this into my code, I just get a 500 Internal Server Error (extremely unhelpful). I cannot turn on errors as it is on a server that multiple people use.
I also tried changing the file_exists line to;
if (file_exists('test.txt'))
in the hopes that would work but still didn't work.
Just to clarify, I'm sending the files from the remote server to my local server.
There is a closing curly brace missing right before the second else keyword.
Please try to use a code editor with proper syntax highlighting and code formatting to spot such mistakes on the fly while you are still editing the PHP file.
The corrected and formatted code:
require('constants.php');
$files = $sftp->nlist('out/');
foreach ($files as $file) {
if (basename((string)$file)) {
if (strpos($file, ".") > 1) { //Checks if file
$filesize = $sftp->size('out/' . $file); //gets filesize
if ($filesize > 1) {
if (file_exists('import/' . $file)) {
echo $file . ' already exists';
} else {
$sftp->get('out/' . $file, 'import/' . $file); //Sends file over
}
} else {
echo $file . ' is empty.</br>';
}
}
}
}
Your code checks the file exist in your local server not in remote server.
if (file_exists('import/'.$file)){
echo $file.' already exists';
}
You need to check in remote server using sftp object like
if($sftp->file_exists('import/'.$file)){
echo $file.' already exists';
}
Edit:
Add clearstatcache() before checking file_exists() function as the results of the function get cached.
Refer: file_exists
JSFIDDLE
I'm using filedrop.js to create a file repository structure within my app. The above noted JSFIDDLE has all of the Javascript / jQuery / HTML and CSS code for this small module. While everything on the client end seems to be functioning properly (files can be DnD'd, progress bar acts correctly, console shows proper event triggers), the result on the server-side is always an empty $_FILES variable. My PHP (ajax.receiveFile.php) is as follows:
var_dump($_FILES);
ob_start();
$callback = &$_REQUEST['fd-callback'];
$job_id = &$_REQUEST['job_id'];
$subdir = &$_REQUEST['subdir'];
$j = loadJob($job_id);
$save_path = "D:\\JobFiles\\" . $j->gOrderNumber() . "\\" . $subdir . "\\";
if ( ($_FILES['fd-file']['size'] > 0) && is_uploaded_file($_FILES['fd-file']['tmp_name']) ) {
$name = $_FILES['fd-file']['name'];
if (move_uploaded_file($_FILES['fd-file']['tmp_name'], $save_path.$name)) {
$j->addAttachment($subdir,$name);
echo 'true';
} else {
echo 'false';
}
}
ob_end_flush();
FileDrop.js seems to be doing what it is supposed to do, as shown here:
I read here on SO that using the same element name over multiple input types of "file" can cause errors but I'm not sure that is the case here. I have double- and triple-checked the permissions on both the TEMP and TARGET upload folders, I have confirmed that all PHP variables are set as needed via visual inspection and PHPINFO(). The server config is PHP 5.4 on IIS7.
If anyone has any ideas on what else to look for, please contribute. Thanks!
This works for me:
file_put_contents('uploads/person/7.jpeg', fopen('php://input', 'r'));
I'm stumped, and I'm sure I'm missing something really basic here. Safe mode is disabled, the file exists.
This code:
$dir = "textfiles"
chdir('../'.$dir."/");
//using a Windows Slash here(Wamp Stack, on Windows 7 Dev environment
$filename = getcwd() ."\\". $row[0];
//echoing this outputs:
//C:\wamp\www\wordpress\textfiles\New Text Document.txt
$filename = str_replace("\\","\\\\",$filename);
//echoing this outputs C:\\wamp\\www\\wordpress\\textfiles\\New Text Document.txt
//escaping slashes in filename to prevent escaping. I SUSPECT my issue may be
// related to this
//if (file_exists("C:\\wamp\\www\\wordpress\\textfiles\\New Text Document.txt")) {
//Line above is commented out, but when it replaces the line below, this thing
//returns True
if (file_exists($filename)) {echo "Yes";}
else { echo $filename;}
Comment out line
/* $filename = str_replace("\\","\\\\",$filename); */
And your code should work.
So, I have a sidebar.php that is included in the index.php. Under a certain condition, I want sidebar.php to stop running, so I thought of putting exit in sidebar.php, but that actually exits all the code beneath it meaning everything beneath include('sidebar.php'); in index.php all the code would be skipped as well. Is there a way to have exit only skip the code in the sidebar.php?
Just use return;
Do also be aware that it is possible to actually return something to a calling script in this way.
if your parent script has $somevar = include("myscript.php"); and then in myscript.php you do say... return true; you will get that value in $somevar
Yes, you just use return;. Your sidebar.php file might look something like this:
<?php
if($certain_condition) {
return;
} else {
// Do your stuff here
}
?>
I know this is a really old question, but I've recently taken over the code base of another developer who used exit religiously, meaning that the parent file that included various files had to be designed in such a way that the include of the module files were done at the end so it didn't cut off the page. I wrote a small PHP script to replace all occurrences of "exit;" with "return;".
if($handle = opendir("path/to/directory/of/files")) {
while(false !== ($file = readdir($handle))) {
if("." === $file) continue;
if(".." === $file) continue;
$pageContents = file_get_contents($file);
$pageContents = str_replace("exit;", "return;", $pageContents);
file_put_contents($file, $pageContents);
echo $file . " updated<br />";
}
}
I hope this helps someone.
I'm not very familiar with regEx's and I'm trying to find a preg_match regex for searching for any of the following strings within a file and if found it will halt it. I already have the fopen and fgets and fclose setup I just need to use a regex inside of a preg_match for the following php tags:
<?php
<?
?>
so if preg_match returns 1 than this will skip this file and not upload it. I am using the $_FILES array to upload it via post, so I'm hoping I can use the $_FILES['file']['tmp_name'] variable for this to read through the file.
Thanks for your help with this :)
EDIT
if (in_array('application/x-httpd-php', $files[$filid]['mimetypes']) && ($_FILES[$value]['type'][$n] == 'application/octet-stream' || $_FILES[$value]['type'][$n] == 'application/octetstream'))
{
$file_extension = strtolower(substr(strrchr($_FILES[$value]['name'][$n], '.'), 1));
if ($file_extension == 'php')
{
// Reading the current php file to make sure it's a PHP File.
$fo = fopen($_FILES[$value]['tmp_name'][$n], 'rb');
while (!feof($fo))
{
$fo_output = fgets($fo, 16384);
// look for a match
if (preg_match([REG EX HERE], $fo_output) == 1)
{
$php = true;
break;
}
}
fclose($fo);
}
}
OK, I apologize, but actually, what I am doing is I need to find a PREG MATCH. Because if it is a PHP FILE, I need to set the MIME TYPE to: application/x-httpd-php within the database. BECAUSE I'm also allowing PHP Files to be uploaded as well in certain instances. So hopefully the code I posted above makes more sense to you all now.
Can someone please help me with a preg_match regex for this please?
/(?:<\?(?!xml)|\?>)/
(15 chars)
If you want to parse the file, try the following instead:
function containsPhp($file) {
if(!$content = file_get_contents($file)) {
trigger_error('Not a file');
return false;
}
foreach(token_get_all($content) as $token) {
if(is_array($token) && in_array(current($token), array(T_OPEN_TAG, T_OPEN_TAG_WITH_ECHO))) {
return true;
}
}
return false;
}
... besides checking for a php extension (php, php5, phtml, inc etc).
\?>|<\?((?=php)|(?!\w))