This question already has answers here:
PHP - Failed to open stream : No such file or directory
(10 answers)
Closed 5 years ago.
I am just trying to make a simple PHP program that allows me to generate my page quickly.
I am completely new at PHP.. And I have no clue what I am doing.
/index.php
<?php
include "/base/startup.php";
echo "Test";
startPage("Home");
?>
I'm getting a 500 server error with this.. Please tell me what I'm doing wrong. Thank you.
/base/startup.php
$HOME = "/";
$SCRIPT = <<<EOD
EOD;
$IMPORTS = array(
"/scripts/script.js"
);
$STYLES = array(
"/styles/style.css"
);
function prnt($string) {
echo $string;
}
function map($func, $arr) {
foreach($arr as $i) {
call_user_func($func, $i);
}
}
function linkScript($script) {
prnt("<script src='$script'></script>");
}
function linkStyle($style) {
prnt("<link rel='stylesheet' href='$style'/>");
}
function startPage($title, $script="", $imports=array(), $styles=array()) {
$pre_tags = array(
"<html>",
"<head>"
);
$post_tags = array(
"</head>",
"<body>"
);
map(prnt, $pre_tags);
prnt("<title>$title</title>");
map(linkScript, $IMPORTS);
map(linkScript, $imports);
map(linkStyle, $STYLES);
map(linkStyle, $styles);
map(prnt, $post_tags);
}
function genNav() {
$nav_links = array(
"Home"=>$HOME,
"Walkthroughs"=>$HOME . "/walkthroughs/",
"Dex"=>$HOME . "dex.php"
);
prnt("<div class='nav'>");
foreach ($nav_links as $key => $value) {
prnt("<a class='link' href='" . $value . "'/>" . $key . "</a>");
}
}
function endPage() {
$endTags = array(
"</body>",
"</html>"
);
}
?>
This is the error:
Warning: include(/base/startup.php): failed to open stream: No such file or directory in /var/www/html/index.php on line 2
Warning: include(): Failed opening '/base/startup.php' for inclusion (include_path='.:/usr/share/php') in /var/www/html/index.php on line 2
Test
Fatal error: Uncaught Error: Call to undefined function startPage() in /var/www/html/index.php:4 Stack trace: #0 {main} thrown in /var/www/html/index.php on line 4
Since you mentioned you are on a Linux machine, it looks like the issue is caused because of the / here. The / is considered the root directory of linux machine. So removing the / must most probably work:
<?php
include "base/startup.php"; // Try removing the slash.
echo "Test";
startPage("Home");
?>
Since you haven't enabled the display of errors, the issue would be, there's no /base in your system and it would have thrown an error, like Fatal: Include file not found., which is not displayed because of your configuration, instead it would have shown Error 500 silently.
Update
Along with the above error, after seeing your code, the next one is you need to quote the function names. So replace the stuff with:
map("prnt", $pre_tags);
prnt("<title>$title</title>");
map("linkScript", $IMPORTS);
map("linkScript", $imports);
map("linkStyle", $STYLES);
map("linkStyle", $styles);
map("prnt", $post_tags);
The next error is, you haven't included the global variables correctly inside the function. You need to use:
global $IMPORTS, $STYLES;
Now your code works as expected.
And finally finishing the endPage() function:
function endPage() {
$endTags = array(
"</body>",
"</html>"
);
foreach($endTags as $tag)
echo $tag;
}
Related
This question already has answers here:
Only variables should be passed by reference
(12 answers)
Closed 2 years ago.
I created a php project a few days ago, when this error was not coming, but since 2 days this error is coming, I do not know what the problem is, please help someone.
Strict Standards: Only variables should be passed by reference in /home/indiamaz/public_html/musicwala.cf/get-zip.php on line 31
Warning: filesize(): stat failed for /home/indiamaz/public_html/musicwala.cf/siteuploads/Gulabo Sitabo (2020) Mp3 Songs-musicwala.zip in /home/indiamaz/public_html/musicwala.cf/get-zip.php on line 51
##get-zip.php##
<?php
require_once('config/functions.php');
if(isset($_GET["code"]))
{
if(!empty($_GET["code"]) == true)
{
$zipname = __dir__.'/siteuploads/'.$_GET["name"].'-musicwala.zip';
if(file_exists($zipname))
{
$rp = str_replace(array("_","%20","+")," ",$_GET["name"]);
$size = filesize($zipname);
echo '
<div id="dlzip"> <a class="dwnLink2" rel="nofollow" href="/siteuploads/'.$_GET["name"].'-musicwala.zip">download Zip Of '.$rp.' - '.vars::bytes($size).'</a>
<center> <b style="color:red">Note*Only 10 Files Compressed Due To Server Bandwidth Limition!</b></center></div>
';
exit;
}
$url = vars::$siteUrl.$_GET["code"];
$data = vars::cURL($url);
$match = preg_match_all("|<!-- WapkaHost.Com Web Solution :: File List -->(.*?)<!-- WapkaHost.Com Web Solution :: File List Complete -->|mis",$data,$cats);
$rp = str_replace("/download/",vars::$siteUrl."download/",$cats[1][0]);
preg_match_all('#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#', $rp,$urls);
$count = count($urls[1]);
if($count < 12){
// $zipname = __dir__.'/siteuploads/'.$_GET["name"].'-musicwala.zip';
$files="";
foreach($urls[0] as $url)
{
$name = end(explode("/",$url));
// echo $name;
$rm = preg_replace("|https://(.*?)/(.*?)/(.*?)/{$name}|mis","http://musicwala.cf/files/download/id/$3",$url);
$headers = get_headers($rm);
$location = str_replace("Location: /","",$headers[3]);
$files[] = $location;
}
$zip = new ZipArchive; $zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file)
{
// echo $file;
$zip->addFile($file);
}
$zip->close();
$rp = str_replace(array("_","%20","+")," ",$_GET["name"]);
$size = filesize($zipname);
echo '
<div class="download">
<div id="dlzip"> <a class="dwnLink2" rel="nofollow" href="/siteuploads/'.$_GET["name"].'-musicwala.zip">download Zip Of '.$rp.' - '.vars::bytes($size).'</a> </div>
<center> <b style="color:red">Note*Only 10 Files Compressed Due To Server Bandwidth Limition!</b></center>
</div>
';
}
else
{
echo "Sorry Max File Size Allow 10";
}
}
else
{
echo "Faild To Compress!";
}
}
?>
Regarding the Strict Standards error on the end function, from the documentation:
Parameters (1)
array. The array. This array is passed by reference because it is modified by the function. This means you must pass it a real variable and not a function returning an array because only actual variables may be passed by reference.
explode is a function that returns an array - not a real variable, Since end modifies real variables, you must set the return value of explode to a separate real variable and send that variable to end.
// $url = __dir__.'/siteuploads/'.$_GET["name"].'-musicwala.zip';
foreach($urls[0] as $url)
{
$exploded_array = explode("/", $url);
$name = end( $exploded_array );
// ...
As a guess, the OP's code should actually be foreach ( $urls as $url ){ (not $urls[0]) but that isn't specifically related to the error code.
The second message: Warning: filesize(): stat failed for.. is a bit harder to diagnose here. Possibly the file wasn't created, maybe it's too large (filesize can get weird over 2GB files), or some other issue. Try using the following to determine more of an error message (docs here).
var_dump( $zip->getStatusString() ); // Returns a string with the status message on success or false on failure.
var_dump( $zip->close() ); // Returns true on success or false on failure.
After installing CakePHP successfully, on first time running, I'm getting these warnings at the bottom. How can I fix this.
Warning (2): Missing argument 1 for View::element(), called in /Users/michaelanywar/Sites/cakephp/app/View/Layouts/default.ctp on line 61 and defined [CORE/Cake/View/View.php, line 398]
Notice (8): Undefined variable: name [CORE/Cake/View/View.php, line 416]
Notice (8): Undefined variable: name [CORE/Cake/View/View.php, line 422]
Notice (1024): Element Not Found: Elements/.ctp [CORE/Cake/View/View.php, line 425]
My View/view.php lines from 398 to 427 look like this:
public function element($name, $data = array(), $options = array()) {
$file = $plugin = null;
if (isset($options['plugin'])) {
$name = Inflector::camelize($options['plugin']) . '.' . $name;
}
if (!isset($options['callbacks'])) {
$options['callbacks'] = false;
}
if (isset($options['cache'])) {
$contents = $this->_elementCache($name, $data, $options);
if ($contents !== false) {
return $contents;
}
}
$file = $this->_getElementFilename($name);
if ($file) {
return $this->_renderElement($file, $data, $options);
}
if (empty($options['ignoreMissing'])) {
list ($plugin, $name) = pluginSplit($name, true);
$name = str_replace('/', DS, $name);
$file = $plugin . 'Elements' . DS . $name . $this->ext;
trigger_error(__d('cake_dev', 'Element Not Found: %s', $file), E_USER_NOTICE);
}
}
If you look at your first warning/error message it should be clear what the issue is: "Warning (2): Missing argument 1 for View::element()".
Look on line 61 of your default layout View template (/app/View/Layouts/default.ctp). You obviously have a call to $this->element() that isn't passing a template name (hence Cake is looking for "Elements/.ctp").
Make sure you pass a template name to the element() method or remove it from your template. For example, if you want to include the template "View/Elements/site_header.ctp":-
echo $this->element('site_header');
The template just needs to exist in the 'View/Elements' folder. You don't need to pass the '.ctp' extension to the element() method, Cake assumes this.
Make sure you've read the docs on Elements.
Moving the default.ctp to View/Elements folder was the best thing and then calling it element('default');?>
I removed the default.ctp in the layout folder..
i try to do
<?php
$i = new \GlobIterator('/test/file*.gz');
echo $i->count();
With file*.gz may not exist. And when no file found i got this error
Fatal error: Uncaught exception 'LogicException' with message 'The parent constructor was not called: the object is in an invalid state ' in /in/qHHhR:3
Stack trace:
0 /in/qHHhR(3): SplFileInfo->_bad_state_ex()
As you can see here http://3v4l.org/qHHhR, it's not working only 5.3.7+
PHP bug or what am i doing wrong?
Ok so, as CBroe say it's a php bug.
A solution (found on https://bugs.php.net/bug.php?id=55701) is to do like this:
// Next works as expected: no xml files found = no output
foreach (new GlobIterator($path_to_files . '/*.xml') as $fileinfo) {
echo $fileinfo->getFilename() . "\n";
}
$it = new GlobIterator($path_to_files . '/*.xml');
// Expected result: count = 0
// Instead next line will crash php if no xml files are found
if ($it->count()) {
// do something...
}
Another method that looks cleaner to me:
try {
$count = $i->count();
} catch ( \LogicException $e) {
$count = 0;
}
Another method using iterator_to_array
count(iterator_to_array($i))
// return 0
I get an error in my php code when trying to get all the files from their directory, then creating html links for them and I don't understand why.
Here is the error:
Warning: printf(): Too few arguments in C:\Users\Ryan\Documents\Web Development\xampp\htdocs\muzik\player.php on line 59
Line 59 is:
printf("<li><a href='mp3/%s'>%s</a></li>", htmlentities($file->getBasename()));
Here is the code:
`echo '<ul id="playlist">';
foreach( new DirectoryIterator('mp3/') as $file) {
if( $file->isFile() === TRUE) {
printf("<li><a href='mp3/%s'>%s</a></li>", htmlentities($file->getBasename()));
}
}
echo '</ul>';`
You have two %s, so the printf expects 2 arguments and you only put one.
You may want to use this one :
$filename = htmlentities($file->getBasename();
printf("<li><a href='mp3/%s'>%s</a></li>", $filename, $filename);
I am trying to loop through this directory:
$path = "D:\\import\\statsummary\\";
Here is my code:
$path = "D:\\import\\statsummary\\";
//$path = "C:\\test";
//function load_csv($path, $filename){
if(is_null($filename)){
header('Content-type: text/plain');
$output = array();
foreach (new DirectoryIterator($path) as $file){
if($file->isFile()){
$output[] = $i++ . " " . $file->getFileName() . "\n";
$output[] = file($file->getPathName());
$output[] = "\n------------\n";
}
}
}
echo implode('', $output);
When I run this script, I get this error:
Fatal error: Uncaught exception 'UnexpectedValueException' with message 'DirectoryIterator::__construct(D:\import\statsummary\,D:\import\statsummary\): Access is denied. (code: 5)' in C:\inetpub\wwwroot\include\file_importer.php:10
Stack trace:
#0 C:\inetpub\wwwroot\include\file_importer.php(10): DirectoryIterator->__construct('D:\import\...')
#1 {main}
thrown in C:\inetpub\wwwroot\include\file_importer.php on line 10
But when I change it to a test directory on my C:\ drive, it runs just fine. I've even created a username to run PHP as directed in this post:
php - Unable to connect to network share - Stack Overflow
Based on the DirectoryIterator class, something like this should work:
<?php
$path = "D:/import/statsummary";
$output=array();
$iterator = new DirectoryIterator(path);
foreach ($iterator as $fileinfo) {
if ($fileinfo->isFile()) {
$filename= $fileinfo->getFilename();
$path=$fileinfo->getPathname();
$output[][$filename]=$path;
}
}
print_r($output);
?>
Update
Since you're getting access denied, you'll need to run the command prompt (CMD) window as Administrator more than likely. If this is on a link (lnk) you can change the permissions in the link settings.
For instance if you right-click on the shortcut for cmd as select properties, you would go to shortcut>advanced>Run as Administrator.