I would like to check if a page exists. My file is article.php . The article's URLs are article.php?id=1 article.php?id=2 etc. But when I check it this way it doesn't work:
$filecheck = "article.php?id=$id";
if (file_exists($filecheck)) {
echo "This article exists.";
} else {
echo "Sorry this article does not exist.";
}
But it always returns "Sorry this article does not exist."
How could I fix this?
Don't pass the query string to it.
$filecheck = 'article.php';
The file "article.php?id=$id" will not exist as it is not a physical file.
I am assuming that you are using the $id to find an article that exists in a database. If this is the case then the file_exists function is not what you need.
What you will need to do is write a quick MySQL statement to check if the article exists and then go from there.
Something like this perhaps:
$query = "SELECT * FROM articles WHERE id='$id'";
$result = mysql_query($query);
// Check if result is there (ie article exists)
if ($result) {
echo "This article exists.";
} else {
echo "Sorry this article does not exist.";
}
I hope that helps. Let me know if you need anything else.
It's because there is no file called: article.php?id=$id
There probably is a file called: article.php though :)
If they are physical page instead of dynamically created content use this way:
$filecheck = "article_1.php"
if (file_exists($filecheck)) {
echo "This article exists.";
} else {
echo "Sorry this article does not exist.";
}
Otherwise check the ID whether it is in the DB.
Well the reason it is not finding the file is because you have a querystring in it. If you are by chance getting this data from some other source and can't control if a querystring is sent with it then you can do this:
$yourFile = 'article.php?id=$id'; // Or wherever you get this value from
$yourFile = strstr( $yourFile , '?' , TRUE );
echo $yourFile; // now has a value of article.php
Related
Hi I'm trying do put some PHP in my website as a part of it I want my user to be able to add photos on it I already make it work but there is one problem I want the file uploaded to be put in two different repositories here's my code(or the part that as already received the file from the input form this is the part where I move my file into the folders and insert it into my database) I would like to know how to duplicate the file like that I could put it in two different folders
$name=$_FILES['mon_fichier']['name'];
echo $name."<br/>";
$destination= './Images/'.$dossierA.'/';
echo $destination."<br/>";
// $destinationEN= '../en/Images/';
$dir = './Images/mainSlider';
$fichierEtDossiers=scandir($destination);
for ($i=0; $i<count($fichierEtDossiers); $i++)
{
$w = 0;
while($fichierEtDossiers[$i]==$name){
$name=explode(".",$_FILES['mon_fichier']['name'])[0]."(".$w.")".".".$extension_upload;
$w++;
}
}
$resultat = move_uploaded_file($_FILES['mon_fichier']['tmp_name'],$destination.$name);
// $resultat2 = move_uploaded_file($_FILES['mon_fichier']['tmp_name'],$destinationEN.$name);
if ($resultat){
$req= "INSERT INTO PHOTOS_MONUMENTS(Name, FileName, Valid) VALUES ('".$name."','".$dossierA."',0);";
try {
$dbh->query($req);
echo "<h2 class=\"h2 text-center\">transfer reussi</h2><br />";
header("Refresh:3; url=upload.php");
} catch (\Exception $e) {
echo "<h2 class=\"h2 text-center\">erreur d'enregistrement</h2><br />";
echo $e;
header("Refresh:10; url=upload.php");
}
I put in comment what I tried but it don't work, please can you help me ?
$resultat = move_uploaded_file($_FILES['mon_fichier']['tmp_name'],$destination.$name);
//$resultat2 = move_uploaded_file($_FILES['mon_fichier']['tmp_name'],$destinationEN.$name);
$_FILES['mon_fichier']['tmp_name'] will be moved to $destination after 1st line.
Try copy it to $destinationEN
$resultat2 = copy($_FILES['mon_fichier']['tmp_name'],$destinationEN.$name);
I am trying to create a profile editing setup. It seems as though the information is edited only when an image is being uploaded. I found out that allowing the error message to be a condition allows for some more manipulation so I attempted it now my condition statement is not working as it should.
if($_FILES['files']['error']==0) {
print_r($_FILES['files']['error']);
echo "if";
foreach($_FILES['files']['name'] as $file => $name) {
$filename = $name;
try{
if(move_uploaded_file($_FILES['files']['tmp_name'][$file],'uploads/'.$filename)) {
$updateInfo = $db->prepare("UPDATE users SET image = :image, aboutme = :aboutme WHERE id = :id");
$updateInfo->bindParam(":image", $filename);
$updateInfo->bindParam(":id", $_SESSION['user']['id']);
$updateInfo->bindParam(':aboutme', $aboutme);
$updateInfo->execute();
}
} catch(Exception $e) {
echo $e;
}
}
} elseif($_FILES['files']['error'] == 4) {
print_r($_FILES['files']['error']);
echo "Elseif";
try{
$updateInfo = $db->prepare("
UPDATE users
SET
aboutme = :aboutme
WHERE id = :id
");
$updateInfo->bindParam(':id', $_SESSION['user']['id']);
$updateInfo->bindParam(':aboutme', $aboutme);
$updateInfo->execute();
} catch(Exception $e) {
echo $e;
}
} else{
print_r($_FILES['files']['error']);
echo "else";
}
}
When I check what array is being sent, its the correct one but the wrong condition, ie: it would run the else statement no matter the file check.
My question:
Is there something wrong with my code, with the exception of any security or efficiency flaws?
$_FILES['files']['error'] returns error code along with the file array. There are different type of error codes, all codes are mentioned in following link with details:
Please check by
print_r($_FILES['files'])
and see what are you getting in response.
As you posted your array response, you can get error code by $_FILES['files']['error'][0] or use switch case as mentioned in following link.
See here for more details:
http://php.net/manual/en/features.file-upload.errors.php
Also regarding debugging, always debug code step by step from top to bottom. Check $_POST, $_FILES, $_SERVER etc details if you get some problem particular related to data process.
I have a download button and when i click on it, instead of saving to disk it opens it in the browser. I tried a bunch of attempts to make it open in the browser but it doesnt seem to do anything
<?php
// make a connection to the database
require_once("connection/connection.php");
//retrieve the ID from the url to fetch the specific details
if ($_GET['id'] != ""){
$item_id = $_GET['id'];
$bad_id = FALSE;
}
else{
$item_id = "";
$bad_id = TRUE;
}
//select the specific item from the database
// run if statement to ensure valid id was passed
if (is_numeric ($_GET['id'])){
$query = "SELECT name FROM repository WHERE item_id = '$item_id'";
$result = mysql_query($query) or die(mysql_error());
// assign the values to an array
$row = mysql_fetch_assoc($result);
//assign the values from the array to variables
$name = $row['name'];
}
// define path to the xml file
$file = "xml/".$hud_name . "_cfg.xml";
// check to make sure the file exists
if(!file_exists($file)){
die('Error: File not found.');
} else{
// Set headers
header("Content-Type: application/xml");
header("Content-Disposition:attachment; filename=".basename($file)."");
readfile($file);
}
?>
That is download.php and it obviously finds the file because it doesnt give the error about it not existing. It also echos back the correct file path
Then on another page i have:
<img src="images/download.png" alt=""/>
Any ideas whats wrong?
Well the solution turned out to be simple in the end but i didnt see any documentation saying the header must be the very first line. If i placed:
header("Content-Type: application/xml");
as the first line and then the coding below it and the other header info at the end it works. Im not sure if that's the solution or a workaround but it fixed it for me
I'm a noob in php and I need some help please.
I have a uploading script that uploads something to my server.
So after I upload the file i get a message your file was upload and I want this message to be posted in my html upload page(main page) and the code is like this:
if(empty($errors)===true){
move_uploaded_file($file_tmp,"upload/".$file_name);
echo "Your file was upload!"; <- I want this line to be printed in other page //
}else{
print_r($errors);
}
}
Edit :
And I found an error to my script if you could help me with this two please:
$file_name=$_FILES['file']['name'];
$file_tmp =$_FILES['file']['tmp_name'];
$file_type=$_FILES['file']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['file']['name'])));
$extensions = array("rar","zip","jpeg","jpg","png","gif");
if(in_array($file_ext,$extensions)=== false){
$error[]= "Extension not allowed, please choose a RAR or ZIP file or if you upload an image use JPEG, JPG, PNG or GIF format.</br> Thank you!";
}
This is my code to restrict file upload,but it won't take the restrictions,can any1 tell me why please?
Hope I'm explicit enough.
Thank you !
You can modify your script in the below way.
... if(empty($errors)===true){
move_uploaded_file($file_tmp,"upload/".$file_name);
header("Location: otherpage.php?msg=success");
}else{
header("Location: otherpage.php?msg=failure");
print_r($errors);
}
} ...
In otherpage.php,
if(isset($_GET['msg']) && $_GET['msg'] == 'success') {
echo "File uploaded sucessfully";
}
EDIT:
You have written print_r($errors). I am assuming that $errors is an array. In that case you can pass this variable to the url by using json_encode($errors), see below.
$err = json_encode($errors);
$urlEncode = urlencode($err);
//now pass this to the url like this
header("Location: otherpage.php?msg=failure&err=".$urlEncode);
//in otherpage.php, you have to decode it.
if(isset($_GET['err'])) {
$errDecode = urldecode($_GET['err']);
$err = json_decode($errDecode);
print_r($err); //prints the error
}
Extensions:
Your script seems to be correct, can you try it in the below way.
$extensions = array("rar","zip","jpeg","jpg","png","gif");
if(!in_array($file_ext,$extensions)){
$error[]= "your error statement";
}
Place your echo on the page you want it to appear on, not on a separate page. Alternately send your echo string as part of the form submission, but this is probably not appropriate for this case. But then you could set what should be printed on the next page, but set it in advance.
i am trying to use the !isset on the '$class' variable to see if it has a value or not, and then base the mysql_query function on that. but it's a no go. see anything wrong?
<?php session_start();
$heyyou = $_SESSION['usern'];
$points = $_SESSION['points'];
$school = $_SESSION['school'];
$class = $_POST['class'];
$prof = $_POST['prof'];
$date = $_POST['dater'];
$fname = $_FILES['fileToUpload']["name"];
?>
<div id='contenttext' class='contenttext'>
<?php
#mysql_select_db($database) or die( "Unable to select database");
$query = "INSERT INTO uploadedfiles (usename, filename, date, teacher, class) VALUES ('$heyyou', '$fname', '$date', '$prof', '$class')";
if (!isset($class)){
echo 'You need to pick a class for the content'; }
else{
mysql_query($query); }
mysql_close();
?>
<?php
if (($_FILES["fileToUpload"]["type"] == "image/gif" || $_FILES["fileToUpload"]["type"] == "image/jpeg" || $_FILES["fileToUpload"]["type"] == "image/png") && $_FILES["fileToUpload"]["size"] < 10000000)
{
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
"upload/" . $_FILES["fileToUpload"]["name"]);
echo "Your file has successfully been uploaded, and is awaiting moderator approval for points." . "<html><br><a href='uploadfile.php'>Upload more.</a>";
}
else
{
echo "Files must be either JPEG, GIF, or PNG and less than 10,000 kb";
}
?>
</div>
</body>
</html>
Two major security problems with your code:
You're wide open to SQL injection attacks (see: http://bobby-tables.com/)
You're blindly trusting the user is not malicious for the file upload. The ['type'] and ['name'] fields are completely under user control, and it's trivial to hack the upload to say it's a gif while still uploading a PHP script. You then use the user-supplied filename, WHICH CAN CONTAIN PATH INFORMATION, and dump it directly to your server. This leaves the door wide open to a malicious user uploading any file they want, anywhere on the server.
Minor point #3:
You don't check if the database query succeeds. Never assume a query succeeds. Even if the SQL statement is perfectly valid, there's far too many other reasons that could make it fail anyways. Always check the query call with ... = mysql_query(...) or die(mysql_error()) as a bare minimum error handler.
Probably because $class is being set, by you. Try if (empty($class)){
I maybe wrong but class is a reserved word try another name and $class != ""
http://www.php.net/manual/en/reserved.keywords.php
BTW remove you DB Conect info please we me be nice but some of the people reading this may not be. ;-)
Try this, first initialize all your variables and then assign the POST values.
Eg:
$class='';
$class = $_POST['class'];
if (!isset($class)){
echo 'You need to pick a class for the content';
}
You can not use $class since class is a keyword reserved.
This may work too:
$query = "INSERT INTO uploadedfiles (usename, filename, date, teacher, class) VALUES ($heyyou, $fname, $date, $prof, $class)";
Since double quote can understand variables when they inside it.
Another think is date is a keyword too reserved by MySQL.
Finlly try to see what $_POST['class']; content like this:
echo $_POST['class'];
Because perhaps you forget to give a name to your html element.
The variable $class is always set because of $class = $_POST['class']. so isset($class) will always be true regardless of class posted value. notice the difference in below statements:
$class = '';
if (isset($class)) {
echo 'a';
}
if($class) {
echo 'b';
}
the output is: a
//replace this:
if (!isset($class)){
echo 'You need to pick a class for the content'; }
else{
mysql_query($query);
}
//with this:
if (isset($class) && $class){
mysql_query($query);
else{
echo 'You need to pick a class for the content'; }
}