-1

Firstly i added text view with notice(and some warning too) about my problem. Notice: Undefined index: first_name in C:\my_projects\phplearn\www\ch07\create_user.php on line 17 Notice: Undefined index: last_name in C:\my_projects\phplearn\www\ch07\create_user.php on line 19 Notice: Undefined index: email in C:\my_projects\phplearn\www\ch07\create_user.php on line 21 Notice: Undefined index: bio in C:\my_projects\phplearn\www\ch07\create_user.php on line 23 Notice: Undefined index: facebook_url in C:\my_projects\phplearn\www\ch07\create_user.php on line 25 Notice: Undefined index: twitter_handle in C:\my_projects\phplearn\www\ch07\create_user.php on line 40 Notice: Undefined index: user_pic in C:\my_projects\phplearn\www\ch07\create_user.php on line 49 Notice: Trying to access array offset on value of type null in C:\my_projects\phplearn\www\ch07\create_user.php on line 49 Notice: Undefined index: user_pic in C:\my_projects\phplearn\www\ch07\create_user.php on line 57 Notice: Trying to access array offset on value of type null in C:\my_projects\phplearn\www\ch07\create_user.php on line 57 Warning: Header may not contain more than a single header, new line detected in C:\my_projects\phplearn\www\stack\scripts\app_config.php on line 63

The problem started when I added this piece of code:

($_FILES[$image_fieldname]['error'] == 0)
or redirectToError("сервер не может получить выбранное вами изображение.", $php_errors[$_FILES[$image_fieldname]['error']]);


@is_uploaded_file($_FILES[$image_fieldname]['tmp_name'])
or redirectToError('<pre>',"Ты в норме? Зачем ты это пытался загрузить? 
Запрос на отправку: файл назывался " , "{$_FILES[$image_fieldname]['tmp_name']}", '</pre>');

@getimagesize($_FILES[$image_fieldname]['tmp_name'])
or redirectToError('<pre>', "вы выбрали файл для своего фото, который не является изображением." , "{$_FILES[$image_fieldname]['tmp_name']}" , "не является файлом изображения.", '</pre>');

$now = time();
while (file_exists($upload_filename = $upload_dir . $now . '-' . $_FILES[$image_fieldname]['name'])) {
    $now++;
}

move_uploaded_file($_FILES[$image_fieldname]['tmp_name'], $upload_filename)
or redirectToError('<pre>',"возникла проблема сохранения вашего изображения в его постоянном месте. Ошибка, связанная с правами доступа при перемещении файла в {$upload_filename}", '</pre>');

This is all my code in this file.

<?php 
$link = require_once ('../stack/scripts/database_connection.php');

$upload_dir = HOST_WWW_ROOT . "uploads/profile_pics";
$image_fieldname = "user_pic";

$php_errors = array(1 => 'Превышен макс. размер файла, указанный в  php.ini', 
                    2 => 'Превышен макс. размер файла, указанный в форме HTML',
                    3 => 'Была отправлена только часть файла',
                    4 => 'Файл для отправки не был выбран.');



$first_name = trim($_REQUEST['first_name']);

$last_name = trim($_REQUEST['last_name']);

$email = trim($_REQUEST['email']);

$bio = trim($_REQUEST['bio']);

$facebook_url = str_replace("facebook.org", "facebook.com", trim($_REQUEST['facebook_url']));



if (preg_match("/^\s*(http:\/\/www.facebook.com\/)/" , $facebook_url)) {
    $facebook_url === true;
} else {
    $facebook_url = "http://www.facebook.com/" . $facebook_url;
}

$twitter_handle = trim($_REQUEST['twitter_handle']);
$twitter_url = "http://www.twitter.com/";
if (preg_match("/^\s*(@)/" , $twitter_handle)) {
  $twitter_url = $twitter_url . $twitter_handle;
}

($_FILES[$image_fieldname]['error'] == 0)
or redirectToError("сервер не может получить выбранное вами изображение.", $php_errors[$_FILES[$image_fieldname]['error']]);


@is_uploaded_file($_FILES[$image_fieldname]['tmp_name'])
or redirectToError('<pre>',"Ты в норме? Зачем ты это пытался загрузить? 
Запрос на отправку: файл назывался " , "{$_FILES[$image_fieldname]['tmp_name']}", '</pre>');

@getimagesize($_FILES[$image_fieldname]['tmp_name'])
or redirectToError('<pre>', "вы выбрали файл для своего фото, который не является изображением." , "{$_FILES[$image_fieldname]['tmp_name']}" , "не является файлом изображения.", '</pre>');

$now = time();
while (file_exists($upload_filename = $upload_dir . $now . '-' . $_FILES[$image_fieldname]['name'])) {
    $now++;
}

move_uploaded_file($_FILES[$image_fieldname]['tmp_name'], $upload_filename)
or redirectToError('<pre>',"возникла проблема сохранения вашего изображения в его постоянном месте. Ошибка, связанная с правами доступа при перемещении файла в {$upload_filename}", '</pre>');




$insert_sql = "INSERT INTO users (first_name, last_name, email, bio, facebook_url, twitter_handle)
 VALUES  ('{$first_name}', '{$last_name}', '{$email}', '{$bio}', '{$facebook_url}', '{$twitter_handle}');";

mysqli_query($link, $insert_sql)
or die(mysqli_error($link));


header("Location: show_user.php?user_id=" . mysqli_insert_id($link));



?>

<html>
<head>
<link href="../stack/css/phpMM.css" rel="stylesheet" type="text/css" />
</head>


<body>
<div id="header"> <h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="example"> Пример 3.1</div>

<div id="content">
<p>Это запись той информации, которую вы отправили:</p>
<p>
Имя: <?php echo $first_name . " " . $last_name;?></br>
Адрес электронной почты: <?php echo $email;?></br>
<a href="<?php echo $facebook_url; ?>">Ваша страница на Facebook:</a></br>

<a href="<?php echo $twitter_url; ?>">Проверьте свой Twitter - канал</a></br>

</p>    
</div>

<div id="footer"></div>
</body>
</html> 

This is my first time I ask a question here, so I apologize if the form of my question is uncomfortable. Help, pls. Thx

UPD about header function. This is my AppConfig.php

<?php 

define("DEBUG_MODE", true);

define("SITE_ROOT", "/stack/");

define("HOST_WWW_ROOT", "C:/my_projects/phplearn/www/stack/");


define("DATABASE_HOST", "localhost");
define("DATABASE_USERNAME", "root");
define("DATABASE_PASSWORD", "");
define("DATABASE_NAME", "testdb");   


$testArray = [
  "key1" => "value1",
  "key2" => "value2",
  "key3" => "value3",
];


function debug_print($testArray) {
  if (DEBUG_MODE) {
    echo '<pre>' . print_r($testArray, 1) . '</pre>';
    echo generateCallTrace();
  }
}

/*My friend give me this function, im not good understand what`s going on here, eh*/
function generateCallTrace()
{
    $e = new Exception();
    $trace = explode("\n", $e->getTraceAsString());
    // reverse array to make steps line up chronologically
    $trace = array_reverse($trace);
    array_shift($trace); // remove {main}
    array_pop($trace); // remove call to this method
    $length = count($trace);
    $result = array();

    for ($i = 0; $i < $length; $i++)
    {
        $result[] = ($i + 1)  . ')' . substr($trace[$i], strpos($trace[$i], ' ')); // replace '#someNum' with '$i)', set the right ordering
    }

    return "\t" . implode("\n\t", $result);
}




function redirectToError($msg, $error_msg = null) {
  if ($error_msg != null) {
    header("Location: " . SITE_ROOT . "scripts/show_error.php?error_message={$msg}&system_error_message={$error_msg}");
  } else {
    header("Location: " . SITE_ROOT . "scripts/show_error.php?error_message={$msg}");
  }
  die();
}```
  • 1
    Not sure what is causing the error, but the code you have added is (IMHO) not particularly standard or well written. Using `@` is generally bad practice and your use of `( test ) or redirect()` seems just lazy. As for debugging - have you tried something like `print_r($_REQUEST);` to see what is in the request before using the values. – Nigel Ren May 24 '20 at 07:39
  • The problem with the "non-standard code" is that I have been studying php for the past 2 months with a book that is deprecated. Unfortunately, I did not find a good guide that could most closely explain the basics of the language from simple to complex. Therefore, I don’t know much yet, I try to read the documentation and turn to experienced people. In this case, it’s about the fact that I just don’t know yet about “checking variables” and don’t know how to apply it in my case, that would work. And yea, im know about ```@```, but im not know about alternative – Иван Грицай May 24 '20 at 07:44
  • Not, im not use ```print_r($_REQUEST);``` – Иван Грицай May 24 '20 at 07:47
  • 1
    Does this answer your question? ["Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP](https://stackoverflow.com/questions/4261133/notice-undefined-variable-notice-undefined-index-and-notice-undefined) – Nico Haase May 24 '20 at 07:51
  • May be worth having a look through https://phptherightway.com/ which may help with some more up to date ideas on how to use PHP. Not sure if you use an IDE - but this can also help. – Nigel Ren May 24 '20 at 07:52
  • @ИванГрицай Based on this error `Warning: Header may not contain more than a single header, new line detected in C:\my_projects\phplearn\www\stack\scripts\app_config.php on line 63` I would say the problem is in `redirectToError` function. Could you provide this function definition as well? – krlv May 24 '20 at 08:27
  • Oh, sorry, this answers cant help. Im already read it, but still not undersrtand logic about my problem. But, im know, if i delete piece of code(look up, i add it in my main), my code works fine. I apologize, I can be mistaken, but it seems to me that if I enter some kind of information in a separate html form, which is then captured by $ _REQUEST, this should work, and the index should be defined – Иван Грицай May 24 '20 at 08:41
  • krlv yep, im upd my post pls check it NigelRen thx for material! I will definitely learn this! – Иван Грицай May 24 '20 at 08:48

1 Answers1

0

There are several issues with the code snippet you've posted but to make it work again you should fix your error message.

From this:

@is_uploaded_file($_FILES[$image_fieldname]['tmp_name']) 
or redirectToError('<pre>',"Ты в норме? Зачем ты это пытался загрузить? 
Запрос на отправку: файл назывался " , "{$_FILES[$image_fieldname]['tmp_name']}", '</pre>');

To this:

@is_uploaded_file($_FILES[$image_fieldname]['tmp_name']) 
or redirectToError('<pre>',"Ты в норме? Зачем ты это пытался загрузить? Запрос на отправку: файл назывался " , "{$_FILES[$image_fieldname]['tmp_name']}", '</pre>');

Why does your original error message don't work? There is a new line between "Зачем ты это пытался загрузить?" and "Запрос на отправку" in your original error message. Now, based on redirectToError function definition, second parameter will be passed directly to header function without any transformation/encoding. It means, you will pass a multi-line string to as a single HTTP header, which is HTTP protocol violation.

Regarding other PHP Notices, they are shown because no POST data were sent to the page. You can add some very basic check to make sure your script is invoked by form submit:

<?php
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    // вернуть пользователя обратно на страницу формы
    header("Location: create_user.html");
}


$link = require_once ('../stack/scripts/database_connection.php');
...
krlv
  • 2,310
  • 1
  • 12
  • 15